branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep>const R = require('ramda'); const { ifNotAdmin, inClause, inClauseOr, isPatchEmpty, knex, prepare, query, whereAnd, } = require('./utils'); const Sql = { updateEnvironment: (cred, input) => { const { name, patch } = input; return knex('environment') .where('name', '=', name) .update(patch) .toString(); }, selectEnvironmentByName: name => knex('environment') .where('name', '=', name) .toString(), }; const getEnvironmentsByProjectId = sqlClient => async (cred, pid, args) => { const { projects } = cred.permissions; if (cred.role !== 'admin' && !R.contains(pid, projects)) { throw new Error('Unauthorized'); } const prep = prepare( sqlClient, `SELECT * FROM environment e WHERE e.project = :pid ${args.type ? 'AND e.environment_type = :type' : ''} `, ); const rows = await query(sqlClient, prep({ pid: pid, type: args.type })); return rows; }; const getEnvironmentByOpenshiftProjectName = sqlClient => async (cred, args) => { const { customers, projects } = cred.permissions; const str = ` SELECT e.* FROM environment e JOIN project p ON e.project = p.id JOIN customer c ON p.customer = c.id WHERE e.openshift_projectname = :openshiftProjectName ${ifNotAdmin( cred.role, `AND (${inClauseOr([ ['c.id', customers], ['p.id', projects], ])})`, )} `; const prep = prepare(sqlClient, str); const rows = await query(sqlClient, prep(args)); return rows[0]; }; const addOrUpdateEnvironment = sqlClient => async (cred, input) => { const { projects } = cred.permissions; const pid = input.project.toString(); if (cred.role !== 'admin' && !R.contains(pid, projects)) { throw new Error('Project creation unauthorized.'); } const prep = prepare( sqlClient, `CALL CreateOrUpdateEnvironment( :name, :project, :deploy_type, :environment_type, :openshift_projectname ); `, ); const rows = await query(sqlClient, prep(input)); const environment = R.path([0, 0], rows); return environment; }; const deleteEnvironment = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Unauthorized'); } const prep = prepare(sqlClient, 'CALL DeleteEnvironment(:name, :project)'); const rows = await query(sqlClient, prep(input)); // TODO: maybe check rows for changed result return 'success'; }; const updateEnvironment = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Unauthorized'); } if (isPatchEmpty(input)) { throw new Error('input.patch requires at least 1 attribute'); } const name = input.name; await query(sqlClient, Sql.updateEnvironment(cred, input)); const rows = await query(sqlClient, Sql.selectEnvironmentByName(name)); return R.prop(0, rows); }; const getAllEnvironments = sqlClient => async (cred, args) => { if (cred.role !== 'admin') { throw new Error('Unauthorized'); } const where = whereAnd([ args.createdAfter ? 'created >= :createdAfter' : '', ]); const prep = prepare(sqlClient, `SELECT * FROM environment ${where}`); const rows = await query(sqlClient, prep(args)); return rows; }; const Queries = { addOrUpdateEnvironment, getEnvironmentByOpenshiftProjectName, deleteEnvironment, getEnvironmentsByProjectId, updateEnvironment, getAllEnvironments, }; module.exports = { Sql, Queries, }; <file_sep>ARG IMAGE_REPO FROM ${IMAGE_REPO:-lagoon}/oc # the oc image comes with an HOME=/home which is needed to run as unpriviledged, but oc-build-deploy-dind will run as root RUN rm -rf /root && ln -s /home /root ENV LAGOON=oc-build-deploy-dind RUN mkdir -p /git WORKDIR /git COPY docker-entrypoint.sh /lagoon/entrypoints/100-docker-entrypoint.sh COPY build-deploy.sh /usr/sbin/build-deploy COPY build-deploy-docker-compose.sh /build-deploy-docker-compose.sh COPY scripts /scripts COPY openshift-templates /openshift-templates CMD ["build-deploy"] <file_sep>#!/bin/sh -v # This script calls the /ping endpoing of the php-fpm, if the return code is 0, the php-fpm has correctly started SCRIPT_NAME=/${1:-ping} SCRIPT_FILENAME=/${1:-ping} REQUEST_METHOD=GET /usr/bin/cgi-fcgi -bind -connect 127.0.0.1:9000<file_sep>ARG IMAGE_REPO FROM ${IMAGE_REPO:-lagoon}/elasticsearch COPY conf/elasticsearch.yml /usr/share/elasticsearch/config/elasticsearch.yml <file_sep>#!/bin/bash ep /etc/varnish/* exec "$@" <file_sep>#!/bin/sh set -e if [ -f /var/run/secrets/lagoon/sshkey/ssh-privatekey ]; then cp /var/run/secrets/lagoon/sshkey/ssh-privatekey /home/.ssh/id_rsa # add a new line to the key. OpenSSH is very picky that keys are always end with a newline echo >> /home/.ssh/id_rsa chmod 400 /home/.ssh/id_rsa eval $(ssh-agent -a /tmp/ssh-agent) ssh-add /home/.ssh/id_rsa fi # Test if pygmy or cachalot ssh-agents are mounted and symlink them as our known ssh-auth-sock file. # This will only be used in local development if [ -S /tmp/amazeeio_ssh-agent/socket ]; then ln -s /tmp/amazeeio_ssh-agent/socket $SSH_AUTH_SOCK fi<file_sep>ARG IMAGE_REPO FROM ${IMAGE_REPO:-lagoon}/commons as commons FROM alpine MAINTAINER amazee.io ENV LAGOON=varnish # Copying commons files COPY --from=commons /lagoon /lagoon COPY --from=commons /bin/fix-permissions /bin/ep /bin/docker-sleep /bin/ COPY --from=commons /home /home # When Bash is invoked via `sh` it behaves like the old Bourne Shell and sources a file that is given in `ENV` # When Bash is invoked as non-interactive (like `bash -c command`) it sources a file that is given in `BASH_ENV` ENV TMPDIR=/tmp TMP=/tmp HOME=/home ENV=/home/.bashrc BASH_ENV=/home/.bashrc RUN apk --no-cache add varnish RUN echo "${VARNISH_SECRET:-lagoon_default_secret}" >> /etc/varnish/secret COPY default.vcl /etc/varnish/default.vcl RUN fix-permissions /etc/varnish/ \ && fix-permissions /var/run/ \ && fix-permissions /var/lib/varnish COPY docker-entrypoint /lagoon/entrypoints/70-varnish-entrypoint EXPOSE 8080 # tells the local development environment on which port we are running ENV LAGOON_LOCALDEV_HTTP_PORT=8080 ENTRYPOINT ["/lagoon/entrypoints.sh"] CMD ["varnishd", "-a", ":8080", "-T", ":6082", "-F", "-f", "/etc/varnish/default.vcl", "-S", "/etc/varnish/secret"] <file_sep>const { Sql } = require('./sshKey'); describe('Sql', () => { describe('updateSshKey', () => { it('should create a proper query', () => { const cred = {}; const input = { id: 1, patch: { keyType: 'ssh-rsa', }, }; const ret = Sql.updateSshKey(cred, input); expect(ret).toMatchSnapshot(); }); }); describe('selectSshKey', () => { it('should create a proper query', () => { const ret = Sql.selectSshKey(1); expect(ret).toMatchSnapshot(); }); }); }); <file_sep>#!/bin/bash containsValue () { local e for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done return 1 } ############################################## ### PREPARATION ############################################## # Load path of docker-compose that should be used DOCKER_COMPOSE_YAML=($(cat .lagoon.yml | shyaml get-value docker-compose-yaml)) # Load all Services that are defined SERVICES=($(cat $DOCKER_COMPOSE_YAML | shyaml keys services)) # Figure out which services should we handle SERVICE_TYPES=() IMAGES=() for SERVICE in "${SERVICES[@]}" do # The name of the service can be overridden, if not we use the actual servicename SERVICE_NAME=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.name default) if [ "$SERVICE_NAME" == "default" ]; then SERVICE_NAME=$SERVICE fi # Load the servicetype. If it's "none" we will not care about this service at all SERVICE_TYPE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.type custom) # Allow the servicetype to be overriden by environment in .lagoon.yml ENVIRONMENT_SERVICE_TYPE_OVERRIDE=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH}.types.$SERVICE false) if [ ! $ENVIRONMENT_SERVICE_TYPE_OVERRIDE == "false" ]; then SERVICE_TYPE=$ENVIRONMENT_SERVICE_TYPE_OVERRIDE fi if [ "$SERVICE_TYPE" == "none" ]; then continue fi # We build all images IMAGES+=("${SERVICE}") # Create an array with all Service Types, Names and Original Service Name SERVICE_TYPES+=("${SERVICE_TYPE}:${SERVICE_NAME}:${SERVICE}") done ############################################## ### BUILD IMAGES ############################################## # we only need to build images for pullrequests and branches if [ "$TYPE" == "pullrequest" ] || [ "$TYPE" == "branch" ]; then BUILD_ARGS=() BUILD_ARGS+=(--build-arg IMAGE_REPO="${CI_OVERRIDE_IMAGE_REPO}") BUILD_ARGS+=(--build-arg LAGOON_GIT_SHA="${LAGOON_GIT_SHA}") BUILD_ARGS+=(--build-arg LAGOON_GIT_BRANCH="${BRANCH}") BUILD_ARGS+=(--build-arg LAGOON_PROJECT="${PROJECT}") BUILD_ARGS+=(--build-arg LAGOON_BUILD_TYPE="${TYPE}") if [ "$TYPE" == "pullrequest" ]; then BUILD_ARGS+=(--build-arg LAGOON_PR_HEAD_BRANCH="${PR_HEAD_BRANCH}") BUILD_ARGS+=(--build-arg LAGOON_PR_HEAD_SHA="${PR_HEAD_SHA}") BUILD_ARGS+=(--build-arg LAGOON_PR_BASE_BRANCH="${PR_BASE_BRANCH}") BUILD_ARGS+=(--build-arg LAGOON_PR_BASE_SHA="${PR_BASE_SHA}") BUILD_ARGS+=(--build-arg LAGOON_PR_TITLE="${PR_TITLE}") fi for IMAGE_NAME in "${IMAGES[@]}" do # We need the Image Name uppercase sometimes, so we create that here IMAGE_NAME_UPPERCASE=$(echo "$IMAGE_NAME" | tr '[:lower:]' '[:upper:]') # To prevent clashes of ImageNames during parallel builds, we give all Images a Temporary name TEMPORARY_IMAGE_NAME="${OPENSHIFT_PROJECT}-${IMAGE_NAME}" DOCKERFILE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$IMAGE_NAME.build.dockerfile false) if [ $DOCKERFILE == "false" ]; then # No Dockerfile defined, assuming to download the Image directly PULL_IMAGE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$IMAGE_NAME.image false) if [ $PULL_IMAGE == "false" ]; then echo "No Dockerfile or Image for service ${IMAGE_NAME} defined"; exit 1; fi # allow to overwrite image that we pull OVERRIDE_IMAGE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$IMAGE_NAME.labels.lagoon\\.image false) if [ ! $OVERRIDE_IMAGE == "false" ]; then # expand environment variables from ${OVERRIDE_IMAGE} PULL_IMAGE=$(echo "${OVERRIDE_IMAGE}" | envsubst) fi . /scripts/exec-pull-tag.sh else # Dockerfile defined, load the context and build it BUILD_CONTEXT=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$IMAGE_NAME.build.context .) if [ ! -f $BUILD_CONTEXT/$DOCKERFILE ]; then echo "defined Dockerfile $DOCKERFILE for service $IMAGE_NAME not found"; exit 1; fi . /scripts/exec-build.sh fi # adding the build image to the list of arguments passed into the next image builds BUILD_ARGS+=(--build-arg ${IMAGE_NAME_UPPERCASE}_IMAGE=${TEMPORARY_IMAGE_NAME}) done fi ############################################## ### CREATE OPENSHIFT SERVICES AND ROUTES ############################################## for SERVICE_TYPES_ENTRY in "${SERVICE_TYPES[@]}" do echo "=== BEGIN route processing for service ${SERVICE_TYPES_ENTRY} ===" echo "=== OPENSHIFT_SERVICES_TEMPLATE=${OPENSHIFT_SERVICES_TEMPLATE} " IFS=':' read -ra SERVICE_TYPES_ENTRY_SPLIT <<< "$SERVICE_TYPES_ENTRY" SERVICE_TYPE=${SERVICE_TYPES_ENTRY_SPLIT[0]} SERVICE_NAME=${SERVICE_TYPES_ENTRY_SPLIT[1]} SERVICE=${SERVICE_TYPES_ENTRY_SPLIT[2]} SERVICE_TYPE_OVERRIDE=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH}.types.$SERVICE false) if [ ! $SERVICE_TYPE_OVERRIDE == "false" ]; then SERVICE_TYPE=$SERVICE_TYPE_OVERRIDE fi OPENSHIFT_SERVICES_TEMPLATE="/openshift-templates/${SERVICE_TYPE}/services.yml" if [ -f $OPENSHIFT_SERVICES_TEMPLATE ]; then OPENSHIFT_TEMPLATE=$OPENSHIFT_SERVICES_TEMPLATE . /scripts/exec-openshift-resources.sh fi OPENSHIFT_ROUTES_TEMPLATE="/openshift-templates/${SERVICE_TYPE}/routes.yml" if [ -f $OPENSHIFT_ROUTES_TEMPLATE ]; then # The very first generated route is set as MAIN_GENERATED_ROUTE if [ -z "${MAIN_GENERATED_ROUTE+x}" ]; then MAIN_GENERATED_ROUTE=$SERVICE_NAME fi OPENSHIFT_TEMPLATE=$OPENSHIFT_ROUTES_TEMPLATE . /scripts/exec-openshift-resources.sh fi done ############################################## ### CUSTOM ROUTES FROM .lagoon.yml ############################################## # Two while loops as we have multiple services that want routes and each service has multiple routes ROUTES_SERVICE_COUNTER=0 while [ -n "$(cat .lagoon.yml | shyaml keys environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER 2> /dev/null)" ]; do ROUTES_SERVICE=$(cat .lagoon.yml | shyaml keys environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER) ROUTE_DOMAIN_COUNTER=0 while [ -n "$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER 2> /dev/null)" ]; do # Routes can either be a key (when the have additional settings) or just a value if cat .lagoon.yml | shyaml keys environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER &> /dev/null; then ROUTE_DOMAIN=$(cat .lagoon.yml | shyaml keys environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER) # Route Domains include dots, which need to be esacped via `\.` in order to use them within shyaml ROUTE_DOMAIN_ESCAPED=$(cat .lagoon.yml | shyaml keys environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER | sed 's/\./\\./g') ROUTE_TLS_ACME=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER.$ROUTE_DOMAIN_ESCAPED.tls-acme true) ROUTE_INSECURE=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER.$ROUTE_DOMAIN_ESCAPED.insecure Redirect) else # Only a value given, assuming some defaults ROUTE_DOMAIN=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.routes.$ROUTES_SERVICE_COUNTER.$ROUTES_SERVICE.$ROUTE_DOMAIN_COUNTER) ROUTE_TLS_ACME=true ROUTE_INSECURE=Redirect fi # The very first found route is set as MAIN_CUSTOM_ROUTE if [ -z "${MAIN_CUSTOM_ROUTE+x}" ]; then MAIN_CUSTOM_ROUTE=$ROUTE_DOMAIN fi ROUTE_SERVICE=$ROUTES_SERVICE . /scripts/exec-openshift-create-route.sh let ROUTE_DOMAIN_COUNTER=ROUTE_DOMAIN_COUNTER+1 done let ROUTES_SERVICE_COUNTER=ROUTES_SERVICE_COUNTER+1 done ############################################## ### PROJECT WIDE ENV VARIABLES ############################################## # If we have a custom route, we use that as main route if [ "$MAIN_CUSTOM_ROUTE" ]; then MAIN_ROUTE_NAME=$MAIN_CUSTOM_ROUTE # no custom route, we use the first generated route elif [ "$MAIN_GENERATED_ROUTE" ]; then MAIN_ROUTE_NAME=$MAIN_GENERATED_ROUTE fi # Load the found main routes with correct schema if [ "$MAIN_ROUTE_NAME" ]; then ROUTE=$(oc --insecure-skip-tls-verify -n ${OPENSHIFT_PROJECT} get route "$MAIN_ROUTE_NAME" -o=go-template --template='{{if .spec.tls.termination}}https://{{else}}http://{{end}}{{.spec.host}}') fi # Load all routes with correct schema and comma separated ROUTES=$(oc --insecure-skip-tls-verify -n ${OPENSHIFT_PROJECT} get routes -o=go-template --template='{{range $index, $route := .items}}{{if $index}},{{end}}{{if $route.spec.tls.termination}}https://{{else}}http://{{end}}{{$route.spec.host}}{{end}}') # Generate a Config Map with project wide env variables oc process --insecure-skip-tls-verify \ -n ${OPENSHIFT_PROJECT} \ -f /openshift-templates/configmap.yml \ -p NAME="lagoon-env" \ -p SAFE_BRANCH="${SAFE_BRANCH}" \ -p SAFE_PROJECT="${SAFE_PROJECT}" \ -p BRANCH="${BRANCH}" \ -p PROJECT="${PROJECT}" \ -p ENVIRONMENT_TYPE="${ENVIRONMENT_TYPE}" \ -p ROUTE="${ROUTE}" \ -p ROUTES="${ROUTES}" \ | oc apply --insecure-skip-tls-verify -n ${OPENSHIFT_PROJECT} -f - if [ "$TYPE" == "pullrequest" ]; then oc patch --insecure-skip-tls-verify \ -n ${OPENSHIFT_PROJECT} \ configmap lagoon-env \ -p "{\"data\":{\"LAGOON_PR_HEAD_BRANCH\":\"${PR_HEAD_BRANCH}\", \"LAGOON_PR_BASE_BRANCH\":\"${PR_BASE_BRANCH}\", \"LAGOON_PR_TITLE\":\"${PR_TITLE}\"}}" fi ############################################## ### PUSH IMAGES TO OPENSHIFT REGISTRY ############################################## if [ "$TYPE" == "pullrequest" ] || [ "$TYPE" == "branch" ]; then for IMAGE_NAME in "${IMAGES[@]}" do # Before the push the temporary name is resolved to the future tag with the registry in the image name TEMPORARY_IMAGE_NAME="${OPENSHIFT_PROJECT}-${IMAGE_NAME}" . /scripts/exec-push.sh done elif [ "$TYPE" == "promote" ]; then for IMAGE_NAME in "${IMAGES[@]}" do . /scripts/exec-openshift-tag.sh done fi ############################################## ### CREATE PVC, DEPLOYMENTS AND CRONJOBS ############################################## for SERVICE_TYPES_ENTRY in "${SERVICE_TYPES[@]}" do IFS=':' read -ra SERVICE_TYPES_ENTRY_SPLIT <<< "$SERVICE_TYPES_ENTRY" SERVICE_TYPE=${SERVICE_TYPES_ENTRY_SPLIT[0]} SERVICE_NAME=${SERVICE_TYPES_ENTRY_SPLIT[1]} SERVICE=${SERVICE_TYPES_ENTRY_SPLIT[2]} # Some Templates need additonal Parameters, like where persistent storage can be found. TEMPLATE_PARAMETERS=() PERSISTENT_STORAGE_PATH=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.persistent false) if [ ! $PERSISTENT_STORAGE_PATH == "false" ]; then TEMPLATE_PARAMETERS+=(-p PERSISTENT_STORAGE_PATH="${PERSISTENT_STORAGE_PATH}") PERSISTENT_STORAGE_CLASS=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.persistent\\.class false) if [ ! $PERSISTENT_STORAGE_CLASS == "false" ]; then TEMPLATE_PARAMETERS+=(-p PERSISTENT_STORAGE_CLASS="${PERSISTENT_STORAGE_CLASS}") fi PERSISTENT_STORAGE_NAME=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.persistent\\.name false) if [ ! $PERSISTENT_STORAGE_NAME == "false" ]; then TEMPLATE_PARAMETERS+=(-p PERSISTENT_STORAGE_NAME="${PERSISTENT_STORAGE_NAME}") fi PERSISTENT_STORAGE_SIZE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.persistent\\.size false) if [ ! $PERSISTENT_STORAGE_SIZE == "false" ]; then TEMPLATE_PARAMETERS+=(-p PERSISTENT_STORAGE_SIZE="${PERSISTENT_STORAGE_SIZE}") fi fi DEPLOYMENT_STRATEGY=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.deployment\\.strategy false) if [ ! $DEPLOYMENT_STRATEGY == "false" ]; then TEMPLATE_PARAMETERS+=(-p DEPLOYMENT_STRATEGY="${DEPLOYMENT_STRATEGY}") fi # Generate PVC if service type defines one OPENSHIFT_SERVICES_TEMPLATE="/openshift-templates/${SERVICE_TYPE}/pvc.yml" if [ -f $OPENSHIFT_SERVICES_TEMPLATE ]; then OPENSHIFT_TEMPLATE=$OPENSHIFT_SERVICES_TEMPLATE . /scripts/exec-openshift-create-pvc.sh fi OPENSHIFT_TEMPLATE="/openshift-templates/${SERVICE_TYPE}/deployment.yml" OVERRIDE_TEMPLATE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.$SERVICE.labels.lagoon\\.template false) if [ "${OVERRIDE_TEMPLATE}" == "false" ]; then if [ -f $OPENSHIFT_TEMPLATE ]; then . /scripts/exec-openshift-create-deployment.sh fi else OPENSHIFT_TEMPLATE=$OVERRIDE_TEMPLATE if [ ! -f $OPENSHIFT_TEMPLATE ]; then echo "defined template $OPENSHIFT_TEMPLATE for service $SERVICE_TYPE not found"; exit 1; else . /scripts/exec-openshift-create-deployment.sh fi fi # Generate cronjobs if service type defines them OPENSHIFT_SERVICES_TEMPLATE="/openshift-templates/${SERVICE_TYPE}/cronjobs.yml" if [ -f $OPENSHIFT_SERVICES_TEMPLATE ]; then OPENSHIFT_TEMPLATE=$OPENSHIFT_SERVICES_TEMPLATE . /scripts/exec-openshift-resources.sh fi ### CUSTOM CRONJOBS # Save the current deployment template parameters so we can reuse them for cronjobs DEPLOYMENT_TEMPLATE_PARAMETERS=("${TEMPLATE_PARAMETERS[@]}") CRONJOB_COUNTER=0 while [ -n "$(cat .lagoon.yml | shyaml keys environments.${BRANCH//./\\.}.cronjobs.$CRONJOB_COUNTER 2> /dev/null)" ] do CRONJOB_SERVICE=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.cronjobs.$CRONJOB_COUNTER.service) # Only implement the cronjob for the services we are currently handling if [ $CRONJOB_SERVICE == $SERVICE ]; then # loading original $TEMPLATE_PARAMETERS as multiple cronjobs use the same values TEMPLATE_PARAMETERS=("${DEPLOYMENT_TEMPLATE_PARAMETERS[@]}") # Creating a save name (special characters removed ) CRONJOB_NAME=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.cronjobs.$CRONJOB_COUNTER.name | sed "s/[^[:alnum:]-]/-/g" | sed "s/^-//g") CRONJOB_SCHEDULE=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.cronjobs.$CRONJOB_COUNTER.schedule) CRONJOB_COMMAND=$(cat .lagoon.yml | shyaml get-value environments.${BRANCH//./\\.}.cronjobs.$CRONJOB_COUNTER.command) TEMPLATE_PARAMETERS+=(-p CRONJOB_NAME="${CRONJOB_NAME}") TEMPLATE_PARAMETERS+=(-p CRONJOB_COMMAND="${CRONJOB_COMMAND}") # Convert the Cronjob Schedule for additional features and better spread CRONJOB_SCHEDULE=$(/scripts/convert-crontab.sh "$CRONJOB_SCHEDULE") TEMPLATE_PARAMETERS+=(-p CRONJOB_SCHEDULE="${CRONJOB_SCHEDULE}") OPENSHIFT_TEMPLATE="/openshift-templates/${SERVICE_TYPE}/custom-cronjob.yml" if [ ! -f $OPENSHIFT_TEMPLATE ]; then echo "No cronjob Template for service type ${SERVICE_TYPE} found"; exit 1; fi . /scripts/exec-openshift-resources.sh fi let CRONJOB_COUNTER=CRONJOB_COUNTER+1 done done ############################################## ### WAIT FOR POST-ROLLOUT TO BE FINISHED ############################################## for SERVICE_TYPES_ENTRY in "${SERVICE_TYPES[@]}" do IFS=':' read -ra SERVICE_TYPES_ENTRY_SPLIT <<< "$SERVICE_TYPES_ENTRY" SERVICE_TYPE=${SERVICE_TYPES_ENTRY_SPLIT[0]} SERVICE_NAME=${SERVICE_TYPES_ENTRY_SPLIT[1]} SERVICE_ROLLOUT_TYPE=$(cat $DOCKER_COMPOSE_YAML | shyaml get-value services.${SERVICE_NAME}.labels.lagoon\\.rollout deploymentconfigs) # if mariadb-galera is a statefulset check also for maxscale if [ $SERVICE_TYPE == "mariadb-galera" ]; then STATEFULSET="${SERVICE_NAME}-galera" . /scripts/exec-monitor-statefulset.sh SERVICE_NAME="${SERVICE_NAME}-maxscale" . /scripts/exec-monitor-deploy.sh elif [ ! $SERVICE_ROLLOUT_TYPE == "false" ]; then . /scripts/exec-monitor-deploy.sh fi done ############################################## ### RUN POST-ROLLOUT tasks defined in .lagoon.yml ############################################## COUNTER=0 while [ -n "$(cat .lagoon.yml | shyaml keys tasks.post-rollout.$COUNTER 2> /dev/null)" ] do TASK_TYPE=$(cat .lagoon.yml | shyaml keys tasks.post-rollout.$COUNTER) echo $TASK_TYPE case "$TASK_TYPE" in run) COMMAND=$(cat .lagoon.yml | shyaml get-value tasks.post-rollout.$COUNTER.$TASK_TYPE.command) SERVICE_NAME=$(cat .lagoon.yml | shyaml get-value tasks.post-rollout.$COUNTER.$TASK_TYPE.service) CONTAINER=$(cat .lagoon.yml | shyaml get-value tasks.post-rollout.$COUNTER.$TASK_TYPE.container false) SHELL=$(cat .lagoon.yml | shyaml get-value tasks.post-rollout.$COUNTER.$TASK_TYPE.shell sh) . /scripts/exec-post-rollout-tasks-run.sh ;; *) echo "Task Type ${TASK_TYPE} not implemented"; exit 1; esac let COUNTER=COUNTER+1 done <file_sep>const R = require('ramda'); const { ifNotAdmin, inClause, inClauseOr, isPatchEmpty, knex, prepare, query, whereAnd, } = require('./utils'); const { validateSshKey } = require('@lagoon/commons/src/jwt'); const fullSshKey = ({keyType, keyValue}) => `${keyType} ${keyValue}`; const Sql = { updateSshKey: (cred, input) => { const { id, patch } = input; return knex('ssh_key') .where('id', '=', id) .update(patch) .toString(); }, selectSshKey: id => knex('ssh_key') .where('id', '=', id) .toString(), }; const getCustomerSshKeys = sqlClient => async cred => { if (cred.role !== 'admin') { throw new Error('Unauthorized'); } const rows = await query( sqlClient, `SELECT CONCAT(sk.keyType, ' ', sk.keyValue) as sshKey FROM ssh_key sk, customer c, customer_ssh_key csk WHERE csk.cid = c.id AND csk.skid = sk.id`, ); return R.map(R.prop('sshKey'), rows); }; const getSshKeysByProjectId = sqlClient => async (cred, pid) => { const { customers, projects } = cred.permissions; const prep = prepare( sqlClient, `SELECT sk.id, sk.name, sk.keyValue, sk.keyType, sk.created FROM project_ssh_key ps JOIN ssh_key sk ON ps.skid = sk.id JOIN project p ON ps.pid = p.id WHERE ps.pid = :pid ${ifNotAdmin( cred.role, `AND (${inClauseOr([['p.customer', customers], ['p.id', projects]])})`, )} `, ); const rows = await query(sqlClient, prep({ pid })); return rows ? rows : null; }; const getSshKeysByCustomerId = sqlClient => async (cred, cid) => { const { customers } = cred.permissions; const prep = sqlClient.prepare(` SELECT id, name, keyValue, keyType, created FROM customer_ssh_key cs JOIN ssh_key sk ON cs.skid = sk.id WHERE cs.cid = :cid ${ifNotAdmin(cred.role, `AND ${inClause('cs.cid', customers)}`)} `); const rows = await query(sqlClient, prep({ cid })); return rows; }; const deleteSshKey = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Unauthorized'); } const prep = prepare(sqlClient, 'CALL DeleteSshKey(:name)'); const rows = await query(sqlClient, prep(input)); //TODO: maybe check rows for any changed rows? return 'success'; }; const addSshKey = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Project creation unauthorized.'); } if (!validateSshKey(fullSshKey(input))) { throw new Error('Invalid SSH key format! Please verify keyType + keyValue'); } const prep = prepare( sqlClient, `CALL CreateSshKey( :id, :name, :keyValue, :keyType ); `, ); const rows = await query(sqlClient, prep(input)); const ssh_key = R.path([0, 0], rows); return ssh_key; }; const addSshKeyToProject = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Unauthorized.'); } const prep = prepare( sqlClient, 'CALL CreateProjectSshKey(:project, :sshKey)', ); const rows = await query(sqlClient, prep(input)); const project = R.path([0, 0], rows); return project; }; const removeSshKeyFromProject = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Unauthorized.'); } const prep = prepare( sqlClient, 'CALL DeleteProjectSshKey(:project, :sshKey)', ); const rows = await query(sqlClient, prep(input)); const project = R.path([0, 0], rows); return project; }; const addSshKeyToCustomer = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('unauthorized.'); } const prep = prepare( sqlClient, 'CALL CreateCustomerSshKey(:customer, :sshKey)', ); const rows = await query(sqlClient, prep(input)); const customer = R.path([0, 0], rows); return customer; }; const removeSshKeyFromCustomer = sqlClient => async (cred, input) => { if (cred.role !== 'admin') { throw new Error('Unauthorized.'); } const prep = prepare( sqlClient, 'CALL DeleteCustomerSshKey(:customer, :sshKey)', ); const rows = await query(sqlClient, prep(input)); const customer = R.path([0, 0], rows); return customer; }; const updateSshKey = sqlClient => async (cred, input) => { const sshKeyId = R.path(['permissions', 'sshKeyId'], cred); const skid = input.id.toString(); if (cred.role !== 'admin' && !R.equals(sshKeyId, skid)) { throw new Error('Unauthorized.'); } if (isPatchEmpty(input)) { throw new Error('input.patch requires at least 1 attribute'); } if (!validateSshKey(fullSshKey(input.patch))) { throw new Error('Invalid SSH key format! Please verify keyType + keyValue'); } await query(sqlClient, Sql.updateSshKey(cred, input)); const rows = await query(sqlClient, Sql.selectSshKey(skid)); return R.prop(0, rows); }; const Queries = { addSshKey, addSshKeyToCustomer, addSshKeyToProject, deleteSshKey, getCustomerSshKeys, getSshKeysByCustomerId, getSshKeysByProjectId, removeSshKeyFromCustomer, removeSshKeyFromProject, updateSshKey, }; module.exports = { Sql, Queries, }; <file_sep>#!/bin/bash if [ -n "$ROUTER_URL" ]; then SERVICE_ROUTER_URL=${SERVICE_NAME}.${ROUTER_URL} else SERVICE_ROUTER_URL="" fi JSON=$(oc process --insecure-skip-tls-verify \ -n ${OPENSHIFT_PROJECT} \ -f ${OPENSHIFT_TEMPLATE} \ -p SERVICE_NAME="${SERVICE_NAME}" \ -p SAFE_BRANCH="${SAFE_BRANCH}" \ -p SAFE_PROJECT="${SAFE_PROJECT}" \ -p BRANCH="${BRANCH}" \ -p PROJECT="${PROJECT}" \ -p LAGOON_GIT_SHA="${LAGOON_GIT_SHA}" \ -p SERVICE_ROUTER_URL="${SERVICE_ROUTER_URL}" \ -p REGISTRY="${OPENSHIFT_REGISTRY}" \ -p OPENSHIFT_PROJECT=${OPENSHIFT_PROJECT} \ "${TEMPLATE_PARAMETERS[@]}") # If the deploymentconfig already exists, remove `image` from all DeploymentConfig Container definition # As setting this causes OpenShift => 3.7 to think the image has changed even though there is an ImageTrigger if oc --insecure-skip-tls-verify -n ${OPENSHIFT_PROJECT} get dc "$SERVICE_NAME" &> /dev/null; then echo "$JSON" | jq --raw-output 'del(.items[].spec.template.spec.containers[]?.image)' | oc apply --insecure-skip-tls-verify -n ${OPENSHIFT_PROJECT} -f - else echo "$JSON" | oc apply --insecure-skip-tls-verify -n ${OPENSHIFT_PROJECT} -f - fi
f1c0b2ae503492519065757367212a5a17684e62
[ "JavaScript", "Dockerfile", "Shell" ]
11
JavaScript
RoSk0/lagoon
d9981a627f6050f70928735d18f13a7fea3400d1
aad52ef41819193f972a6b99bb3cbfa66b89c15b
refs/heads/master
<file_sep>import React, { Component } from "react" import { Link, Route, withRouter } from "react-router-dom" import axios from "axios" import { verifyUser, singleSpots, putSpot, deleteSpot, commentDaSpot, getComments } from "../services/apiHelper" class SingleSpot extends Component { constructor(props) { super(props) this.state = { show: false, comments: [], commentData: { text: '', name: localStorage.getItem('name') }, spot_Id: null, userId: null, currentUser: null, spot: null, spotUp: { name: null, boro: null, address: null, trains: null, obstacles: null, description: null, noteworthy: null, photo_main: null, photo2: null, photo3: null, phto4: null, photo5: null } } } showComments = async () => { const comments = await getComments(this.props.spotId); this.setState({ comments: [...this.state.comments, ...comments] }) } oneSpot = async () => { const spot = await singleSpots(this.props.spotId); console.log(spot) this.setState({ spot }) this.setState({ spot_Id: spot.id }) this.setState({ userId: spot.user_id }) this.setState({ spotUp: { name: spot.name, boro: spot.boro, address: spot.address, trains: spot.trains, obstacles: spot.obstacles, description: spot.description, noteworthy: spot.notworthy, photo_main: spot.photo_main, photo2: spot.photo2, photo3: spot.photo3, phto4: spot.photo4, photo5: spot.photo5 } }) } componentDidMount = async () => { verifyUser(); this.oneSpot(); this.showComments(); } // componentDidMount = async () => { // verifyUser(); // const resp = await axios(`localhost:3000/spot/${this.props.spotId}`) // this.setState({ // currentSpot: resp // }) // } handleChange = (e) => { const { name, value } = e.target; let spotUp = { ...this.state.spotUp }; spotUp[name] = value; this.setState({ spotUp }) this.setState({ commentData: { text: value, name: localStorage.getItem('name') } }) } handleUpdate = async (e, event) => { e.preventDefault() verifyUser(); putSpot(this.props.spotId, event) console.log(putSpot(this.props.spotId, event)) } handleDelete = async (e) => { e.preventDefault(); deleteSpot(this.state.spot_Id) this.props.history.push("/spot") } postComment = async (e, comment) => { e.preventDefault(); verifyUser(); commentDaSpot(this.props.spotId, comment); this.setState({ comments: [...this.state.comments, comment] }) } showupdate = async (e) => { this.setState ({ show: true }) } hideUpdate = async (e) => { this.setState({ show: false }) } render() { console.log(this.state.show) console.log(this.state.userId); // console.log(this.state.spotUp) // console.log(this.state.comments) return ( <div> window.scrollTo(0,0); {this.state.spot && <div className="single"> <div className="locinfo"> <img src={this.state.spot.photo_main} /> {/* <div className="locinfo"> */} <div className="wtf"> <h2 className="mainsingle">{this.state.spot.name}</h2> <h3>{this.state.spot.boro}</h3> <h3>{this.state.spot.address}</h3> <h4>{this.state.spot.trains}</h4> </div> </div> <br /> <div className="info"> <h4>{this.state.spot.obstacles}</h4> <p>{this.state.spot.description}</p> <p>{this.state.spot.noteworthy}</p> </div> <div className="singlespotpics"> <img src={this.state.spot.photo2} /> <img src={this.state.spot.photo3} /> <img src={this.state.spot.phto4} /> <img src={this.state.spot.photo5} /> </div> </div> } { this.state.show === false ? <button onClick={(e) => this.showupdate()}> Show Update Form</button> : <button onClick={(e) => this.hideUpdate()}>Hide</button>} {localStorage.getItem('id') == this.state.userId && localStorage.getItem('name') && localStorage.getItem('id') !== null && (this.state.show === true) && <div className="submitform"> <form onSubmit={(e) => this.handleUpdate(e, this.state.spotUp)}> <input type="text" name="name" value={this.state.spotUp.name} placeholder="Name Of Spot" onChange={e => this.handleChange(e)} /> <input type="text" name="boro" value={this.state.spotUp.boro} placeholder="Boro" onChange={e => this.handleChange(e)} /> <input type="text" name="address" value={this.state.spotUp.address} placeholder="Address" onChange={e => this.handleChange(e)} /> <input type="text" name="trains" value={this.state.spotUp.trains} placeholder="Trains" onChange={e => this.handleChange(e)} /> <input type="text" name="obstacles" value={this.state.spotUp.obstacles} placeholder="Stuffs to skate..." onChange={e => this.handleChange(e)} /> <input type="text" name="description" value={this.state.spotUp.description} placeholder="Spot description" onChange={e => this.handleChange(e)} /> <input type="text" name="noteworthy" value={this.state.spotUp.noteworthy} placeholder="Noteworthy" onChange={e => this.handleChange(e)} /> <input type="text" name="photo_main" value={this.state.spotUp.photo_main} placeholder="Noteworthy" onChange={e => this.handleChange(e)} /> <input type="text" name="photo2" value={this.state.spotUp.photo2} placeholder="Photo 2" onChange={e => this.handleChange(e)} /> <input type="text" name="photo3" value={this.state.spotUp.photo3} placeholder="Photo 3" onChange={e => this.handleChange(e)} /> <input type="text" name="phto4" value={this.state.spotUp.phto4} placeholder="Photo 4" onChange={e => this.handleChange(e)} /> <input type="text" name="photo5" value={this.state.spotUp.photo5} placeholder="Photo 5" onChange={e => this.handleChange(e)} /> <input className="subbutt" type="submit" /> <button onClick={this.handleDelete}>DELETE</button> </form> </div> } <br/> <h1 className="comintro">Survey says. . .</h1> <br /> {this.state.comments && this.state.comments.map((comment, index) => <div key={index} className="comments"> <p>{comment.text}</p> <h5>Yours truly, {comment.name}</h5> </div> )} {localStorage.getItem('name') && <form className="cominput" onSubmit={(e) => this.postComment(e, this.state.commentData)}> <input type="text" name="text" value={this.state.commentData.text} onChange={e => this.handleChange(e)} /> <button >Tell us your thoughts..</button> </form> } </div> ) } } export default withRouter(SingleSpot);<file_sep>import axios from 'axios'; const api = axios.create({ baseURL: "https://immense-forest-21610.herokuapp.com/" }) export const loginUser = async (loginData) => { const resp = await api.post('/auth/login', loginData); console.log(resp.data.user.id); api.defaults.headers.common.authorization = `Bearer ${resp.data.auth_token}`; localStorage.setItem('authToken', resp.data.auth_token); localStorage.setItem('name', resp.data.user.name); localStorage.setItem('email', resp.data.user.email); localStorage.setItem('id', resp.data.user.id) console.log(resp.data.user.id) return resp.data.user; } export const registerUser = async (registerData) => { try { const resp = await api.post('/signup', registerData); api.defaults.headers.common.authorization = `Bearer ${resp.data.auth_token}`; localStorage.setItem('authToken', resp.data.auth_token); localStorage.setItem('name', resp.data.user.name); localStorage.setItem('email', resp.data.user.email); localStorage.setItem('id', resp.data.user.id) return resp.data.user; } catch (e) { console.log(e.response); if (e.response.status === 422) { return { errorMessage: "Email is already associated with a user, please login to continue" } } } } export const indexSpots = async () => { const resp = await api.get('/spot'); console.log(resp) return resp.data } export const singleSpots = async (id) => { const resp = await api.get(`/spot/${id}`); console.log(resp) return resp.data } export const verifyUser = () => { const token = localStorage.getItem('authToken'); if (token) { api.defaults.headers.common.authorization = `Bearer ${token}`; } } export const postSpot = async (spotInfo) => { const resp = await api.post('/spot', spotInfo) return resp.data } export const putSpot = async (id, postData) => { const resp = await api.put(`/spot/${id}`, postData); console.log(resp.data) const todo = { id: id, name: resp.data.data } console.log(todo) // return todo } export const deleteSpot = async (spotToDeleteId) => { await api.delete(`/spot/${spotToDeleteId}`); } export const commentDaSpot = async (id, comment) => { console.log(comment) const resp = await api.post(`/spot/${id}/comment`, comment) console.log(resp) return resp.data } export const getComments = async (id) => { const resp = await api.get(`/spot/${id}/comment`) console.log(resp) return resp.data } export const brooklynSpots = async () => { const resp = await api.get('/brooklyn'); console.log(resp) return resp.data } export const manSpots = async () => { const resp = await api.get('/manhattan'); console.log(resp) return resp.data } export const queenSpots = async () => { const resp = await api.get("/queens") console.log(resp) return resp.data } export const bxSpots = async () => { const resp = await api.get("/bronx") console.log(resp) return resp.data } export const statSpots = async () => { const resp = await api.get("/staten") return resp.data }<file_sep>Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html post 'auth/login', to: 'authentication#authenticate' post 'signup', to: 'user#create' get 'manhattan', to: 'spot#manhattan' get 'brooklyn', to: 'spot#brooklyn' get 'queens', to: 'spot#queens' get 'bronx', to: 'spot#bronx' get 'staten', to: 'spot#staten' resources :user resources :spot do resources :comment end end <file_sep>class SpotController < ApplicationController before_action :set_spot, only: [:show, :update, :destroy] def index #@spots = current_user.spots @spots = Spot.all json_response(@spots) end def create @spot = current_user.spots.create!(spot_params) json_response(@spot, :created) end def manhattan @spotM = Spot.where( boro: "manhattan") json_response(@spotM) end def queens @spotQ = Spot.where( boro: "queens") json_response(@spotQ) end def brooklyn @spotB = Spot.where( boro: "brooklyn") json_response(@spotB) end def bronx @spotBx = Spot.where( boro: "bronx") json_response(@spotBx) end def staten @spotStat = Spot.where( boro: "staten island") json_response(@spotStat) end def show json_response(@spot) end def update @spot.update(spot_params) json_response(status: 'Updated!', message: 'Updated!') end def destroy @spot.destroy json_response(status: 'Deleted!', message: 'Deaded!') end private def spot_params params.permit(:name, :address, :boro, :trains, :obstacles, :rating, :bust_factor, :description, :noteworthy, :photo_main, :photo2, :photo3, :phto4, :photo5) end def set_spot @spot = Spot.find(params[:id]) end end <file_sep>import React, { Component } from 'react'; import { Link, Route, withRouter } from "react-router-dom" import './App.css'; import Header from "./components/header" import Login from "./components/Login" import { loginUser, verifyUser, registerUser, indexSpots } from './services/apiHelper'; import AllSpots from "./components/spotsContainer" import Register from "./components/register" import MakeSpot from "./components/makeSpot" import SingleSpot from "./components/singleSpot" import SpotsContainer from "./components/spotsContainer"; import Footer from "./components/footer" import ManSpots from "./components/manhattanSpots" import BrookSpots from "./components/brookSpots" import Qspots from "./components/queenSpot" import BronxSpots from "./components/bronxSpots" import StatenSpots from "./components/statenSpots" import { thisTypeAnnotation } from '@babel/types'; class App extends Component { constructor(props) { super(props); this.state = { name: "", email: "", password: "", currentUser: null, errorText: "", spots: [] } } handleLogin = async (e, loginData) => { e.preventDefault(); const currentUser = await loginUser(loginData) this.setState({ currentUser }); localStorage.getItem('name') const resp = indexSpots(); this.setState({ spots: resp }) // indexSpots(); this.props.history.push("/spot") } componentDidMount() { verifyUser(); if (localStorage.getItem('authToken')) { const name = localStorage.getItem('name'); const email = localStorage.getItem('email'); const id = localStorage.getItem('id') console.log(id) const user = { name, email, id }; user && this.setState({ currentUser: user }) } const elmt = document.querySelector("#show"); elmt.scrollIntoView(); const resp = indexSpots(); this.setState({ spots: resp }) } handleLogout = () => { this.setState({ currentUser: null }) localStorage.removeItem('authToken'); localStorage.removeItem('name'); localStorage.removeItem('email') localStorage.removeItem('id'); } handleRegister = async (e, registerData) => { e.preventDefault(); const currentUser = await registerUser(registerData); if (!currentUser.errorMessage) { this.setState({ currentUser }); } else { this.setState({ errorText: currentUser.errorMessage }) } this.props.history.push("/spot"); } render() { console.log(this.state.currentUser) return ( <div className="App"> <Header handleLogin={this.handleLogin} handleLogout={this.handleLogout} /> {/* <Login handleLogin={this.handleLogin} handleLogout={this.handleLogout} /> */} <div id="show" className="pic"> <br /> {this.state.currentUser && <h1 className="intro">Sup {this.state.currentUser.name} ?</h1>} </div> <nav className="navbar"> <Link className="golden hov" to="/spot">See All Spots</Link> <Link className="golden hov" to="/signup">Register</Link> <Link className="golden hov" to="/spot/new">Make a Spot</Link> <div className="dropdown"> <a className="golden">Spots by Boro</a> <div className="dropdownmenu"> <Link className="golden" to="/manhattan">Manhattan Spots</Link> <Link className="golden" to="/brooklyn">Brooklyn Spots</Link> <Link className="golden" to="/queens">Queens Spots</Link> <Link className="golden" to="/bronx">Bronx Spots</Link> <Link className="golden" to="/staten">Staten Island Spots</Link> </div> </div> </nav> <Route exact path="/spot/new" render={() => <MakeSpot />} /> <Route exact path="/spot" render={() => <SpotsContainer />} /> <Route path="/signup" render={() => <Register handleRegister={this.handleRegister} />} /> <Route exact path path="/spot/:id" render={(props) => ( <SingleSpot spotId={props.match.params.id} user={this.state.currentUser} /> )} /> <Route exact path="/manhattan" render={() => <ManSpots />} /> <Route path="/brooklyn" render={() => <BrookSpots />} /> <Route path="/queens" render={() => <Qspots />} /> <Route path="/bronx" render={() => <BronxSpots />} /> <Route path="/staten" render={() => <StatenSpots />} /> <Footer /> </div> ); } } export default withRouter(App); <file_sep>Title: Skate Spot Finder Overview: An application that allows users to pinpoint skate spots on a map. The spots are user sourced and will require an address/description, as well as other information, such as obstacles to skate, if you will get kicked out, and a place to list tricks done/maybe links to the tricks. Users can comment on skate spots so that other users can see whether or not the information provided by initial user is accurate, etc. This app I plan on being NYC centric so the locations will be divided up by boro/train stop. Features: - Create User/Log in - Only registered users may upload spots/comment - Users can click on individual spots for more information on them - Users can comment on spots - Spots may be updated by user incase they are no longer vialbe to skate, or the recently become a place you get kicked out of - Ideally would like to implement a rating system Goals: My goal is to have full functionality on this website for the map aspect. Challenges: I think the biggest hurdle for me is going to be implementing the map system to actually update when users makes new spots. I am at the moment totally unsure of how to work this into my project easily. MVP: Create/Log in for users. Post Skate Spots. Post Comments. Client: Mid-fi wireframes, component heirarchy, component breakdown, and timeframe estimates.^^ ![homepage](./homepage.png) ![singespot](./singlespot.png) ![singleuser](./singleuser.png) ![map](./map.png) ![erd](./erd.png) components - header/nav - 30 mins - map - i have no idea - SO LONG - single-spot - two hours - single user - one hour - spots designated by borough - all spots - three hours for carousel - log in/register - two hours - footer - 30 mins CSS - A TON OF TIME Server: Dependencies: React, Link/router, GoogleMapReact Post-MVP: I would like to implement a feature for users to mark themsevles as "skating here" to let their friends know where they are skating that day, also would like to turn it into an actual social network site in this way. Where people can interact with each other. Also would like to implement a feature that has non skate spots to check out nearby. Mainly just like where to get food in the area or a good bar to stop for a drink.# SkateSpots <file_sep>class Spot < ApplicationRecord belongs_to :user has_many :comments validates_presence_of :name, :address, :boro, :trains end <file_sep>class CreateSpots < ActiveRecord::Migration[6.0] def change create_table :spots do |t| t.string :name t.string :address t.string :boro t.string :trains t.string :obstacles t.integer :rating t.text :description t.text :directions t.string :bust_factor t.text :noteworthy t.string :photo_main t.string :photo2 t.string :photo3 t.string :phto4 t.string :photo5 t.references :user, null: false, foreign_key: true t.timestamps end end end <file_sep>import React, { Component } from "react" class Register extends Component { constructor(props) { super(props) this.state = { name: "", location: "", description: "", favorite_spot: "", current_skate: "", best_vids: "", photo: "", email: "" } } componentDidMount = () => { const elmt = document.querySelector("#reg"); elmt.scrollIntoView(); } handleChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }) } render() { return ( <div className="skatingback"> <form id="reg" className="register" onSubmit={(e) => this.props.handleRegister(e, this.state)}> <h2>Sign da fuck up!</h2> <label htmlFor="name"> Name (required)</label> <input type="text" name="name" value={this.state.name} onChange={this.handleChange} /> <label htmlFor="email">E-mail (required)</label> <input type="text" name="email" value={this.state.email} onChange={this.handleChange} /> <label htmlFor="password">Password (required)</label> <input type="password" name="password" value={this.state.password} onChange={this.handleChange} /> <label htmlFor="location">Location</label> <input type="text" name="location" value={this.state.location} onChange={this.handleChange} /> <label htmlFor="description">About yoself...</label> <input type="text" name="description" value={this.state.description} onChange={this.handleChange} /> <label htmlFor="current_skate">Skating?</label> <input type="text" name="current_skate" value={this.state.current_skate} onChange={this.handleChange} /> <label htmlFor="best_vids">Name your favorite skate videos..</label> <input type="text" name="best_vids" value={this.state.best_vids} onChange={this.handleChange} /> <label htmlFor="photo">Upload a picture! Has to be an image address unfortunetly..</label> <input type="text" name="photo" value={this.state.photo} onChange={this.handleChange} /> <button className="submitbutt">Submit!</button> </form> </div> ) } } export default Register;<file_sep>import React, { Component } from "react" import { postSpot } from "../services/apiHelper"; import { withRouter } from "react-router-dom" class MakeSpot extends Component { constructor(props) { super(props); this.state = { name: "", address: "", boro: "", obstacles: "", rating: "", description: "", directions: "", bust_factor: "", noteworthy: "", photo_main: "", photo2: "", photo3: "", phto4: "", photo5: "", spots: [] } } handleChange = (e) => { const { name, value } = e.target this.setState({ [name]: value }) } createSpot = async (e, spotInfo) => { e.preventDefault(); const newSpot = await postSpot(spotInfo) return newSpot } render() { return( <div className="makeform"> <form className="register" id="theseguys" onSubmit={(e) => this.createSpot(e, this.state)}> <h2>Add a spot</h2> <label htmlFor="name">Name (required)</label> <input type="text" name="name" value={this.state.name} onChange={this.handleChange} /> <label htmlFor="address">address (required)</label> <input type="text" name="address" value={this.state.address} onChange={this.handleChange} /> <label htmlFor="boro">Which boro?(required) </label> <input type="text" name="boro" value={this.state.boro.toLowerCase()} onChange={this.handleChange} /> <label htmlFor="trains">Closest Train? (required)</label> <input type="text" name="trains" value={this.state.trains} onChange={this.handleChange} /> <label htmlFor="obstacles">What's there to skate?</label> <input type="text" name="obstacles" value={this.state.obstacles} placeholder="Stuffs to skate..." onChange={e => this.handleChange(e)} /> <label htmlFor="description">Spot Inforomation/Description</label> <input type="text" name="description" value={this.state.description} placeholder="Spot description" onChange={e => this.handleChange(e)} /> <label htmlFor="noteworthy">Noteworthy tricks that have been done there?</label> <input type="text" name="noteworthy" value={this.state.noteworthy} placeholder="Noteworthy" onChange={e => this.handleChange(e)} /> <label htmlFor="photo_main">Upload main photo here</label> <input type="text" name="photo_main" value={this.state.photo_main} placeholder="Main Photo" onChange={e => this.handleChange(e)} /> <label htmlFor="photo2">Upload 2nd Photo</label> <input type="text" name="photo2" value={this.state.photo2} placeholder="Photo2" onChange={e => this.handleChange(e)} /> <label htmlFor="photo3">Upload 3rd Photo</label> <input type="text" name="photo3" value={this.state.photo3} placeholder="Photo3" onChange={e => this.handleChange(e)} /> <label htmlFor="phto4">Upload 4th photo here</label> <input type="text" name="phto4" value={this.state.phto4} placeholder="Photo 4" onChange={e => this.handleChange(e)} /> <label htmlFor="photo5">Upload 5th photo here</label> <input type="text" name="photo5" value={this.state.photo5} placeholder="Photo5" onChange={e => this.handleChange(e)} /> <button>Share thine knowledge with the world</button> </form> </div> ) } } export default withRouter(MakeSpot);<file_sep>class CommentController < ApplicationController before_action :set_spot before_action :set_spot_comment, only: [:show, :update, :destroy] # GET /spot/:todo_id/items def index json_response(@spot.comments) end # GET /todos/:todo_id/items/:id def show json_response(@comment) end # POST /spot/:spot_id/comment def create puts comment_params @spot = current_user.comments.create!(comment_params) json_response(@spot, :created) end # PUT /todos/:todo_id/items/:id def update @comment.update(comment_params) json_response(status: 'SUCCESS', message: 'Did you regret what you said? Or make a bad typo') end # DELETE /todos/:todo_id/items/:id def destroy @comment.destroy json_response(status: 'SUCCESS', message: 'Should have stood your ground') end private def comment_params params.permit(:text, :spot_id, :name) end def set_spot @spot = Spot.find(params[:spot_id]) puts @spot.name end def set_spot_comment @comment = @spot.comments.find_by!(id: params[:id]) if @spot end end <file_sep>class UserController < ApplicationController skip_before_action :authorize_request, only: :create def create user = User.create!(user_params) auth_token = AuthenticateUser.new(user.email, params[:password]).call response = { message: Message.account_created, auth_token: auth_token, user: user_params } json_response(response, :created) end def login @user = User.find_by_email(params[:email]) if @user.authenticate(params[:password]) token = endcode(id: @user.id, name: @user.name) response = {auth_token: token, message: "fuck ruby", user: @user} json_response(response) else response = {message: "Unauthorized!"} json_response(response) end end def index @users = User.all json_response(@users) end def show @user = User.find(params[:id]) json_response(@user) end private def user_params params.permit( :name, :email, :password, :description, :favorite_spot, :current_skate, :best_vids, :photo ) end end <file_sep>import React, { Component } from "react" import { Link } from 'react-router-dom'; class AllSpots extends Component { constructor(props) { super(props); this.state = { spots: [] } } componentDidMount = () => { const elmt = document.querySelector("#show"); elmt.scrollIntoView(); } render() { console.log(this.props); return ( < div id="show" className="showcase" > { localStorage.getItem('name') && this.props.spots.map((spot, index) => ( <div key={index} className="indyshowcase"> <Link to={`/spot/${spot.id}`}> {(spot.photo_main) ? <img src={spot.photo_main} /> : <img className="altpic" src="https://lh3.googleusercontent.com/proxy/M10GxwnqpB1UaZh5iNCYjYcVDKJTMvq5vpViOprua-yNqEyITuC9gleIte7kcYMr-0XZgAoi5btdg21Jb4r4cZKiuhi5pnR2gbHp_C3mYpAncrjd4j8sq53qtiXF9TL5zQ97K-RIrZDJhO9q30OtP0gT" /> } <div className="skate"> <h2 className="goaway">{spot.name}</h2> <h4 className="goaway">{spot.address}</h4> <h4 className="goaway goaway2">{spot.boro}</h4> </div> </Link> </div> )) } </div> ) } } export default AllSpots; <file_sep>import React from "react" import Login from "./Login" import { checkPropTypes } from "prop-types" function Header(props) { return ( <div className="header" > <div className="loginmobile"> <h1 className="head">spotted.</h1> <Login handleLogin={props.handleLogin} handleLogout={props.handleLogout} /> </div> </div> ) } export default Header;<file_sep>class Comment < ApplicationRecord belongs_to :user belongs_to :spot validates_presence_of :text end <file_sep>import React, { Component } from "react" import { Link, Route } from "react-router-dom" import { statSpots, verifyUser} from "../services/apiHelper" class StatenSpots extends Component { constructor(props) { super(props); this.state = { statenSpots: [] } } readStatenSpots = async () => { const statenSpots = await statSpots(); console.log(statenSpots) this.setState({ statenSpots }) } componentDidMount = async () => { verifyUser(); this.readStatenSpots(); } render() { console.log(this.state); return ( <div className="showcase"> {this.state.statenSpots.map((spot, index) => ( <div key={index} className="indyshowcase"> <Link to={`/spot/${spot.id}`}> {(spot.photo_main) ? <img src={spot.photo_main} /> : <img className="altpic" src="https://lh3.googleusercontent.com/proxy/M10GxwnqpB1UaZh5iNCYjYcVDKJTMvq5vpViOprua-yNqEyITuC9gleIte7kcYMr-0XZgAoi5btdg21Jb4r4cZKiuhi5pnR2gbHp_C3mYpAncrjd4j8sq53qtiXF9TL5zQ97K-RIrZDJhO9q30OtP0gT" /> } <div className="skate"> <h2 className="goaway">{spot.name}</h2> <h4 className="goaway">{spot.address}</h4> <h4 className="goaway">{spot.boro}</h4> </div> </Link> </div> ))} </div> ) } } export default StatenSpots;
8d3cfad3d2fadf2c1ec24dad0fe5037b12aeefc5
[ "JavaScript", "Ruby", "Markdown" ]
16
JavaScript
SirRichardM/SkateSpots
d4e4701f39316a8fdca31dc20bd480095ab19887
6c7067a39df6c3a3e66a74e94480e7271d01dc6f
refs/heads/master
<file_sep>package Homework1; public interface Sport { boolean getIsDead(); void jump(Wall wall); void run(Track track); void letsMake(Object let); } <file_sep>package Homework1; import java.util.Random; public class Human implements Sport { private String name; private boolean isDead = false; private float jumpLimit; private float runLimit; Random rnd = new Random(); public boolean getIsDead() { return isDead; } public Human(String name) { this.name = name; this.jumpLimit = (float) rnd.nextInt(100); this.runLimit = (float) rnd.nextInt(100); } @Override public void jump(Wall wall) { if (wall.getHeight() > jumpLimit) { isDead = true; System.out.printf("Человек %s не смог подпрыгнуть на %f метров и сдох %n", this.name,wall.getHeight()); return; } System.out.printf("Человек %s подпрыгнул на %f метров %n", this.name, wall.getHeight()); } @Override public void run(Track track) { if (track.getLength() > runLimit) { isDead = true; System.out.printf("Человек %s не смог пробежать %f метров и сдох %n", this.name,track.getLength()); return; } System.out.printf("Человек %s пробежал %f метров %n", this.name, track.getLength()); } @Override public void letsMake(Object let) { if (let instanceof Wall) { jump((Wall) let); } else if (let instanceof Track) { run((Track) let); } else { isDead = true; //Если неизвестное препятствие - то разбился об него насмерть } } public String toString() { return "Имя: " + this.name + "\nМакс.прыжок: " + this.jumpLimit + "\nМакс.бег: " + this.runLimit + "\nСостояние: " + (isDead ? "Сдох" : "Живой"); } }
01f4f3afd0c8cdf2d89b09f41beb902677fd78d7
[ "Java" ]
2
Java
DrGrizzly/JavaCore2
60d36ec6d1f11ba619eee59ac12779afc5950bd9
febac715ddac0d244f39dbc99ef96d84dc0a28e9
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Xml; using TwinCAT.Ads; namespace PlcSimInterface { class Program { static void Main(string[] args) { ArrayList plcInterfaceList = new ArrayList(); ArrayList simInterfaceList = new ArrayList(); string filename = "config.xml"; var currentDirectory = Directory.GetCurrentDirectory(); var configFilepath = Path.Combine(currentDirectory, filename); System.Xml.XmlDataDocument xmldoc = new System.Xml.XmlDataDocument(); XmlNodeList xmlAddresses; string str = null; FileStream fs = new FileStream(configFilepath, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlAddresses = xmldoc.GetElementsByTagName("Address"); var numOfPlcs = xmlAddresses.Count; for(int i = 0; i<numOfPlcs; i++) { string amsAddress = xmlAddresses[i].ChildNodes.Item(0).InnerText.Trim(); Console.WriteLine("AmsNetId: {0}",amsAddress); PlcInterface plcInterface = new PlcInterface(amsAddress); plcInterfaceList.Add(plcInterface); plcInterface.Fetch(); SimInterface simInterface = new SimInterface(plcInterface); simInterfaceList.Add(simInterface); simInterface.Init(); } Console.WriteLine("Press enter to end the program."); Console.WriteLine(); while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); if(key.Key == ConsoleKey.Enter) { break; } } } Console.WriteLine("Cleaning up and exiting."); foreach(SimInterface simInterface in simInterfaceList) { simInterface.Dispose(); } foreach(PlcInterface plcInterface in plcInterfaceList) { plcInterface.Dispose(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Threading; using EngineIO; namespace PlcSimInterface { class SimInterface { private PlcInterface plcInterface; private string plcHash, simuHash; private MD5 md5Hash; private int[] inputDecoder,outputDecoder; private MemoryBit[] memoryInputBits,memoryOutputBits; private Thread inputThread,outputThread; Boolean endThread; public SimInterface(PlcInterface plcInterface) { this.plcInterface = plcInterface; endThread = new Boolean(); endThread = false; inputDecoder = new int[this.plcInterface.IBoolInPathCtr-1]; outputDecoder = new int[this.plcInterface.IBoolOutPathCtr-1]; for(int i = 0; i < this.plcInterface.IBoolInPathCtr -1 ; i++) { inputDecoder[i] = -1; } for(int i = 0; i < this.plcInterface.IBoolOutPathCtr -1 ; i++) { outputDecoder[i] = -1; } md5Hash = MD5.Create(); } public void Dispose() { endThread = true; //Wait for threads to clean up while(inputThread.IsAlive || outputThread.IsAlive); Console.WriteLine("SimInterface disposed."); ((IDisposable)md5Hash).Dispose(); } public void Init() { //MemoryMap.Instance.Update(); memoryInputBits = MemoryMap.Instance.GetBitMemories(MemoryType.Input); for (int i = 0; i < memoryInputBits.Length - 1; i++) { MemoryBit memoryBit = memoryInputBits[i]; simuHash = memoryBit.Name; if(simuHash.Equals("") || simuHash.Length!=32) continue; //Search for the hash in the list of plc symbols //Console.WriteLine("simuHash: {0} index: {1} ", simuHash, i ); for (int k = 0; k < plcInterface.IBoolInPathCtr - 1; k++) { plcHash = plcInterface.GetMd5Hash(md5Hash, plcInterface.ArrBoolInPaths[k]); //Console.WriteLine("PLCHash: {0} SimuHash: {1}", plcHash, simuHash ); if (plcHash.Equals(simuHash)) { //Console.Write("plcHash: {0} index: {1} ", plcHash, k ); //Console.WriteLine("Memory input found: index plc: {0} index simulation: {1}", k, i ); //Store the simuHash index inputDecoder[k] = i; //Console.WriteLine("Input PLCHash: {0} Input SimuHash: {1} k: {2} inputDecoder[k]: {3}", plcHash, memoryInputBits[inputDecoder[k]].Name,k ,inputDecoder[k] ); //Exit the loop break; } } } //MemoryMap.Instance.Update(); memoryOutputBits = MemoryMap.Instance.GetBitMemories(MemoryType.Output); for (int i = 0; i < memoryOutputBits.Length - 1; i++) { //Get outputs from the plc and transfer them to the simulation. if(memoryOutputBits[i].Name.Equals("") || memoryOutputBits[i].Name.Length!=32) continue; for (int k = 0; k < plcInterface.IBoolOutPathCtr - 1; k++) { plcHash = plcInterface.GetMd5Hash(md5Hash, plcInterface.ArrBoolOutPaths[k]); if (plcHash.Equals(memoryOutputBits[i].Name) ) { outputDecoder[k] = i; //Console.WriteLine("Output PLCHash: {0} Output SimuHash: {1} k: {2} ouputDecoder[k]: {3}", plcHash, memoryOutputBits[outputDecoder[k]].Name,k ,outputDecoder[k] ); //Exit the loop break; } } } inputThread = new Thread(InputsExchange); outputThread = new Thread(OutputsExchange); inputThread.Start(); outputThread.Start(); } public void InputsExchange() { while(!endThread) { //var watch = System.Diagnostics.Stopwatch.StartNew(); MemoryMap.Instance.Update(); for (int k = 0; k < (plcInterface.IBoolInPathCtr - 1) ; k++) { if(inputDecoder[k] == -1) continue; //plcHash = plcInterface.GetMd5Hash(md5Hash, plcInterface.ArrBoolInPaths[k]); //Console.WriteLine("Input PLCHash: {0} Input SimuHash: {1} k: {2} inputDecoder[k]: {3}", plcHash, memoryInputBits[inputDecoder[k]].Name,k ,inputDecoder[k] ); plcInterface.writeBooleanInput(k, memoryInputBits[inputDecoder[k]].Value); } //watch.Stop(); //var elapsedMs = watch.ElapsedMilliseconds; //Console.WriteLine("InputsExchange elapsed time: {0}",elapsedMs); } } public void OutputsExchange() { while(!endThread) { //var watch = System.Diagnostics.Stopwatch.StartNew(); for (int k = 0; k < (plcInterface.IBoolOutPathCtr - 1) ; k++) { if(outputDecoder[k] == -1) continue; memoryOutputBits[outputDecoder[k]].Value = plcInterface.readBooleanOutput(k); } MemoryMap.Instance.Update(); //watch.Stop(); //var elapsedMs = watch.ElapsedMilliseconds; //Console.WriteLine("OutputsExchange elapsed time: {0}",elapsedMs); } } public void Execute() { while(true) { var watch = System.Diagnostics.Stopwatch.StartNew(); MemoryMap.Instance.Update(); for (int k = 0; k < (plcInterface.IBoolInPathCtr - 1) ; k++) { if(inputDecoder[k] == -1) continue; //plcHash = plcInterface.GetMd5Hash(md5Hash, plcInterface.ArrBoolInPaths[k]); //Console.WriteLine("Input PLCHash: {0} Input SimuHash: {1} k: {2} inputDecoder[k]: {3}", plcHash, memoryInputBits[inputDecoder[k]].Name,k ,inputDecoder[k] ); plcInterface.writeBooleanInput(k, memoryInputBits[inputDecoder[k]].Value); } for (int k = 0; k < (plcInterface.IBoolOutPathCtr - 1) ; k++) { if(outputDecoder[k] == -1) continue; //plcHash = plcInterface.GetMd5Hash(md5Hash, plcInterface.ArrBoolOutPaths[k]); //Console.WriteLine("Output PLCHash: {0} Output SimuHash: {1} k: {2} outputDecoder[k]: {3}", plcHash, memoryOutputBits[outputDecoder[k]].Name,k ,outputDecoder[k] ); memoryOutputBits[outputDecoder[k]].Value = plcInterface.readBooleanOutput(k); } MemoryMap.Instance.Update(); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; Console.WriteLine("Elapsed time: {0}",elapsedMs); } // the code that you want to measure comes here } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using TwinCAT.Ads; namespace PlcSimInterface { class PlcInterface { public PlcInterface(string amsNetId) { this.amsNetId = amsNetId; readerReadBoolOut = new AdsBinaryReader(streamReadBoolOut); } private int hBoolInPaths, hBoolInPathCtr, hBoolOutPaths, hBoolOutPathCtr, iBoolInPathCtr, iBoolOutPathCtr; public int IBoolInPathCtr { get => iBoolInPathCtr; } public int IBoolOutPathCtr { get => iBoolOutPathCtr; } public string[] ArrBoolInPaths { get => arrBoolInPaths; } public string[] ArrBoolOutPaths { get => arrBoolOutPaths;} private AdsStream streamReadBoolOut = new AdsStream(1); private AdsBinaryReader readerReadBoolOut; private TcAdsClient tcClient; private string[] arrBoolInPaths = null; private string[] arrBoolOutPaths = null; private int[] inputHandleArray, outputHandleArray; private string amsNetId; public void Dispose() { for (int i = 0; i < IBoolInPathCtr-1; i++) { tcClient.DeleteVariableHandle(inputHandleArray[i]); } for (int i = 0; i < IBoolOutPathCtr-1; i++) { tcClient.DeleteVariableHandle(outputHandleArray[i]); } tcClient.Disconnect(); tcClient.Dispose(); } public string GetMd5Hash(MD5 md5Hash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } public void writeBooleanInput(int index, bool value) { tcClient.WriteAny(inputHandleArray[index], value); } public bool readBooleanOutput(int index) { tcClient.Read(outputHandleArray[index], streamReadBoolOut); bool val = readerReadBoolOut.ReadBoolean(); streamReadBoolOut.Position = 0; return val; } public void Fetch() { tcClient = new TcAdsClient(); tcClient.Connect(amsNetId,851); try { //get the input paths hBoolInPathCtr = tcClient.CreateVariableHandle("SymbolPathStorage.uiBoolInPathCtr"); AdsStream streamBoolInPathCtr = new AdsStream(2); AdsBinaryReader readerBoolInPathCtr = new AdsBinaryReader(streamBoolInPathCtr); tcClient.Read(hBoolInPathCtr, streamBoolInPathCtr); iBoolInPathCtr = readerBoolInPathCtr.ReadInt16(); arrBoolInPaths = new string[iBoolInPathCtr - 1]; Console.WriteLine("Input variables nr: {0}", IBoolInPathCtr); hBoolInPaths = tcClient.CreateVariableHandle("SymbolPathStorage.aBoolInPaths"); AdsStream streamBoolInPaths = new AdsStream((IBoolInPathCtr - 1) * 256); BinaryReader readerBoolInPaths = new BinaryReader(streamBoolInPaths); tcClient.Read(hBoolInPaths, streamBoolInPaths); inputHandleArray = new int[IBoolInPathCtr-1]; for (int i = 1; i < IBoolInPathCtr; i++) { byte[] buffer = readerBoolInPaths.ReadBytes(256); string var = Encoding.UTF8.GetString(buffer, 0, buffer.Length); int index = var.IndexOf('\0'); var = var.Remove(index); arrBoolInPaths[i - 1] = var; inputHandleArray[i - 1] = tcClient.CreateVariableHandle(arrBoolInPaths[i - 1]); using (MD5 md5Hash = MD5.Create()) { string hash = GetMd5Hash(md5Hash, var); Console.WriteLine("Input {0} : {1} - Hash: {2}", i, var, hash); } } //get the output paths hBoolOutPathCtr = tcClient.CreateVariableHandle("SymbolPathStorage.uiBoolOutPathCtr"); AdsStream streamBoolOutPathCtr = new AdsStream(2); AdsBinaryReader readerBoolOutPathCtr = new AdsBinaryReader(streamBoolOutPathCtr); tcClient.Read(hBoolOutPathCtr, streamBoolOutPathCtr); iBoolOutPathCtr = readerBoolOutPathCtr.ReadInt16(); arrBoolOutPaths = new string[iBoolOutPathCtr - 1]; Console.WriteLine("Output variables nr: {0}", IBoolOutPathCtr); hBoolOutPaths = tcClient.CreateVariableHandle("SymbolPathStorage.aBoolOutPaths"); AdsStream streamBoolOutPaths = new AdsStream((IBoolOutPathCtr - 1) * 256); BinaryReader readerBoolOutPaths = new BinaryReader(streamBoolOutPaths); tcClient.Read(hBoolOutPaths, streamBoolOutPaths); outputHandleArray = new int[IBoolOutPathCtr-1]; for (int i = 1; i < IBoolOutPathCtr; i++) { byte[] buffer = readerBoolOutPaths.ReadBytes(256); string var = Encoding.UTF8.GetString(buffer, 0, buffer.Length); int index = var.IndexOf('\0'); var = var.Remove(index); arrBoolOutPaths[i - 1] = var; outputHandleArray[i - 1] = tcClient.CreateVariableHandle(arrBoolOutPaths[i - 1]); using (MD5 md5Hash = MD5.Create()) { string hash = GetMd5Hash(md5Hash, var); Console.WriteLine("Output {0} : {1} - Hash: {2}", i, var, hash); } } } catch (Exception err) { Console.WriteLine("Error while retrieving handle."); } } } }
c582b90f04bc5be215b12b018159e88639050db0
[ "C#" ]
3
C#
fengxing1121/CS_PlcSimInterface
1c0d333a7c935abdefd7512c1f045a6009f034c6
5e1bda337f5740864ea6266cf25b5c3231713b01
refs/heads/master
<file_sep>import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class MainTest { @Before public void setUp() throws Exception { System.out.println("Setting up..."); } @After public void tearDown() throws Exception { System.out.println("Tearing down..."); } @Test public void testBasicCase() throws Exception { System.out.println("Running basic test..."); } }
5626a02b7a12916e4a842e92c370ea294727e895
[ "Java" ]
1
Java
nikkieverett/reverse-polish-calc
673c21a41d492670c88b07ed129828f27acd798d
e61513257b5d3816e7614b1ae03181f393a8b696
refs/heads/master
<repo_name>nlopez59/poc-template<file_sep>/pocMig.sh #! /bin/sh ## Change this to your new "poc" on GHE or any Git Server url ## This assumes you setup an SSH credentials in Git Server. yourRepoURL="<EMAIL>:XXX/poc.git" ## confirm the location of the DBB toolkit mig="/var/dbb/migration/bin/migrate.sh" ## Enter the MVS PDS (don’t include the LLQ) add a member name prefix hlq="HLQ.SLQ" prefix="APPID*" clear; echo "***" ; echo "Migrating Client Source PDS $hlq.* to your repo called $yourRepoURL ..." ; echo "***" groovy -v ; java -version ; git --version ; echo "***" w=~/poc-template ; rm -rf $w git clone <EMAIL>:nlopez59/poc-template.git cd $w ; rm -rf .git ; git init rm poc*.* ; rm -rf cobol/; rm -rf copybook/ ## These lines migrate source using the HLQ above and the LLQ like cobol & copy ## The prefix is used to filter which members are selected ## Repeat the $mig line to include any other PDS's needed for the migration like BMS files $mig -r $w -m MappingRule[hlq:$hlq,toLower:true,pdsMapping:false,targetDir:cobol,extension:CBL] "cobol($prefix*)" $mig -r $w -m MappingRule[hlq:$hlq,toLower:true,pdsMapping:false,targetDir:copybook,extension:CPY] "copy($prefix*)" git add ** ; git add . ; git commit -m "Initial Migration" git remote add origin $yourRepoURL git push -u --force origin master echo "** " ; echo "** Migration complete. Please review the contents of your new repo ->" $yourRepoURL <file_sep>/pocConf.sh #! /bin/sh # un-tar the DBB Samples into the $zApp variable and initialize IDz userBuild Files ############################################################################### zApp=poc-zAppBuild clear ; echo "*** Setting up DBB Samples on ->" $zApp FILE=$zApp/build.groovy if test -f "$FILE"; then clear ; echo "ERROR: $zApp exists. If you want to re-create it, delete it and rerun this script." ; echo " *** Be careful all your customized properties will be lost" ; exit 12 fi rm -Rf dbb-samples; rm -Rf $zApp mkdir dbb-samples; mkdir $zApp tar -C dbb-samples -xovf /var/dbb/dbb-samples-1.0.5.tar cp -r dbb-samples/Build/zAppBuild/ $zApp rm $zApp/.gitattributes rm -Rf poc-sandbox ; rm -Rf poc-IDz-logs mkdir -p poc-sandbox ; mkdir poc-IDz-logs echo "Done. Follow the instructions in the 'PoC cookbook' to configure the zAppBuild properties."
6bf2d988047c5a6c38f404950ac173e72dcf087f
[ "Shell" ]
2
Shell
nlopez59/poc-template
ccb28eb0c157d6c28f19b34627d25bb7e627e111
c87cc394414cc1d035612b3bca53bb31602e8eb2
refs/heads/master
<file_sep>"use strict"; // jshint ignore:line /* global Context, document */ /** * Return a random integer within min/max bounds; if not specified, min * defaults to 0 and max defaults to the length of the array. */ Array.prototype.random = function(min, max) { min = min || 0; max = max || this.length; return Math.floor(Math.random() * (max - min) + min); }; function random(min, max) { min = Math.floor(min || 0); max = Math.ceil(max || 100); return Math.floor(Math.random() * (max - min) + min); } /** * Return a random element from the array */ Array.prototype.choice = function() { return this[this.random()]; }; /** * Remove the item if found, return boolean indicating actual removal. */ Array.prototype.remove = function(item) { var index = this.indexOf(item); if (index > -1) { return !! this.splice(index, 1); } return false; }; /** * Remove and return a random element, or undefined from an empty array. */ Array.prototype.draw = function() { return this.splice(this.random(), 1)[0]; }; /** * Return the last element of the array */ Array.prototype.last = function() { return this[this.length - 1]; }; /** * Return the string padded with spaces on the left to the specified length; * truncates the string to the specified length from the right if necessary */ var spaces = " "; String.prototype.lpad = function(length, classes) { var string = (spaces + (this || "")).slice(0 - length); string = "<span class='" + (classes || "") + "'>" + string + "</span>"; return string; }; /** * Return the string padded with spaces on the right to the specified length; * truncates the string to the specified length from the left if necessary */ String.prototype.rpad = function(length, classes) { var string = ((this || "") + spaces).slice(0, length); string = "<span class='" + (classes || "") + "'>" + string + "</span>"; return string; }; /** * Return the string with {x} placeholders replaced by their ordinal match in * the arguments list; if arguments run out before ordinals, no replacement * occurs, leaving the placeholder. */ String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] !== undefined ? args[number] : match; }); }; /** * Return the object's name attribute if it has one, standard string otherwise */ Object.prototype.toString = function() { return this.name || String({}); }; var helpText = "\n" + " \n" + " Crawl the dungeon the find the lozenge of power! It looks like this:" + " <span class='item treasure'>\u22c4</span>\n" + " \n" + " To move in eight directions:\n" + " <strong>u</strong> <strong>i</strong> <strong>o</strong>\n" + " <strong>j</strong> <strong>l</strong>\n" + " <strong>m</strong> <strong>,</strong> <strong>.</strong>\n" + " \n" + " To attack, stand next to a monster and move into its square!\n" + " \n" + " Chests (<span class='item'>\u2709</span>) and Piles" + " (<span class='item'>\u2234</span>) hold gold or better equipment!\n" + " \n" + " To use whatever you're on: <strong>k</strong>!\n" + " \n" + " Stairs up (<span class='stairs'>\u2191</span>) and down (<span " + "class='stairs'>\u2193</span>) carry you between levels!\n" + " \n" + " Messages:\n" + " <strong>t</strong> To scroll down\n" + " <strong>g</strong> To scroll up\n" + " <strong>b</strong> To delete the current message\n" + " \n" + " <strong>?</strong> To go back to the dungeon\n" + "\n", gameOverText = "\n" + " \n" + " You died on level {0}, killed by a {1}.\n" + " \n" + " You had {2} gold, a {3}, and {4} armor.\n" + " \n" + " Reload the page to start over.\n" + " \n" + " The lozenge of power is still down there...\n" + "\n", lozengeText = "\n" + " \n" + " You found the lozenge of power! Your nagging cough will soon be " + "vanquished...\n" + " \n" + " if you make it back to town.\n" + " \n" + " Hit <strong>k</strong> to continue.\n" + "\n", victoryText = "\n" + " \n" + " You found the lozenge of power, and brought it back to civilization!\n" + " \n" + " And made {0} gold along the way.\n" + " \n" + " Reload the page to try again.\n" + "\n", townText = "\n" + " \n" + " This is where the town would go if one existed.\n" + " \n" + " Hit <strong>k</strong> to return to the dungeon.\n" + "\n"; var context = null, screens = { dungeon: undefined, town: townText, help: helpText, gameOver: undefined, lozenge: lozengeText, victory: undefined, blank: undefined }, config = { screens: screens, // dungeon parameters height: 25, width: 50, lozenge_level: 10, initial_visibility: 0, weapon: "Sword", armor: "Scale", // room generation max_attempts: 60, max_rooms: 15, max_mobs: 10, max_items: 5, }; var LEFT = 0, UP = 1, RIGHT = 2, DOWN = 3, X = 0, Y = 1; var N = 'i', NE = 'o', E = 'l', SE = '.', S = ',', SW = 'm', W = 'j', NW = 'u'; function init() { context = new Context(config); document.body.insertBefore(context.element, document.body.firstChild); document.onkeypress = context.handleInput; context.add_message("Initialization complete!"); context.refresh(); } <file_sep>/* global Dungeon, document, random, Hero, window, config, context */ /** * A screen-like container for conveniently flipping screens of content */ var Screen = (function() { "use strict"; var Screen = function(content) { this.element = document.createElement("div"); this.element.className = "screen"; this.element.style.display = "none"; this.element.innerHTML = content || ""; }; return Screen; }()); /** * A gamewide context container */ var Context = (function() { "use strict"; var Context = function(options) { this.element = document.createElement("div"); this.element.setAttribute("id", "context"); this.height = options.height; this.width = options.width; this.messages = []; this.message_idx = undefined; this.options = options; this.screens = {}; for (var name in options.screens || {}) { this.screens[name] = new Screen(options.screens[name]); this.element.appendChild(this.screens[name].element); } this.dungeon = new Dungeon({width: this.width, height: this.height, context: this}); this.element.appendChild(this.screens.dungeon.element); this.currentScreen = this.screens.dungeon; var start = {x: Math.floor(this.width / 2), y: Math.floor(this.height / 2)}; start = {x: random(2, this.dungeon.maxX - 2), y: random(2, this.dungeon.maxY - 2)}; this.dungeon.addLevel(start, this.screens.dungeon.element); this.hero = new Hero(); this.hero.square = this.dungeon.currentLevel.entry; this.hero.square.add(this.hero); this.hero.inventory.push(Object.create(new window[config.weapon]())); this.hero.equipped = this.hero.inventory.last(); this.hero.inventory.push(Object.create(new window[config.armor]())); this.hero.worn = this.hero.inventory.last(); this.hero.killed = 0; this.hero.regenerate = function() { if (random(0, 100) < 20 && context.hero.hp < context.hero.max_hp) { context.hero.hp += 1; } }; this.dungeon.currentLevel.updateVisibility(this.hero.square); this.dungeon.hero = this.hero; this.status_bar = document.createElement("div"); this.status_bar.className = "status"; this.element.appendChild(this.status_bar); this.message_bar = document.createElement("div"); this.message_bar.className = "messages"; this.element.appendChild(this.message_bar); this.showScreen("dungeon"); }; /** * Set the named screen to display */ Context.prototype.showScreen = function(name) { this.currentScreen.element.style.display = "none"; this.currentScreen = this.screens[name]; this.currentScreen.element.style.display = "block"; }; Context.prototype.refresh = function() { this.print_status(); this.print_message(); }; Context.prototype.print_status = function() { var hero = this.hero, level = this.dungeon.levelIndex + 1, status = "HP: {0} E: {1} W: {2} G: {3} Level: {4} ? for help" .replace("{0}", String(hero.hp).rpad(4, "data")) .replace("{1}", String(hero.equipped).rpad(12, "data")) .replace("{2}", String(hero.worn).rpad(12, "data")) .replace("{3}", String(hero.gold).rpad(4, "data")) .replace("{4}", String(level).lpad(2, "data")); this.status_bar.innerHTML = status; }; var msg_classes = ["first", "second", "third"]; Context.prototype.print_message = function() { var messages = ''; for (var ii = 0; ii < 3; ++ii) { if (this.messages[ii + this.message_idx]) { var idx = ii + this.message_idx, didx = this.messages.length - idx; messages += "<div class='" + msg_classes[ii] + "'>" + (didx) + ". " + this.messages[idx] + "</span>"; } } this.message_bar.innerHTML = messages; }; Context.prototype.add_message = function(message) { this.messages.unshift(message); if (! this.message_idx) { this.message_idx = 0; } }; /* global N, NE, E, SE, S, SW, W, NW, init */ Context.prototype.handleInput = function(event) { var key = Context.prototype.getChar(event || window.event); switch (key) { case N: case NE: case E: case SE: case S: case SW: case W: case NW: if (context.currentScreen === context.screens.dungeon) { context.dungeon.move(key); } break; case "k": // "use" object in current square if (context.currentScreen === context.screens.dungeon) { context.dungeon.activate(); context.dungeon.checkMobs(); } else { context.showScreen("dungeon"); } break; case "g": // scrolling messages up i.e., back through earlier messages if (context.message_idx + 1 < context.messages.length) { ++context.message_idx; } break; case "t": // scrolling messages down i.e., to latest messages if (context.message_idx > 0) { --context.message_idx; } break; case "b": // delete current messages context.messages.splice(context.message_idx, 1); context.message_idx = Math.min(context.message_idx, context.messages.length - 1); break; case "r": // restart if (false && context.currentScreen === context.screens.gameOver) { context.showScreen("blank"); var container = document.getElementById("context"); document.body.removeChild(container); window.setTimeout(function() { context = null; // jshint ignore:line init(); }, 10); } break; case "?": if (context.currentScreen === context.screens.help) { context.showScreen("dungeon"); } else { context.showScreen("help"); } break; default: return true; } if (context.currentScreen === context.screens.dungeon) { context.hero.regenerate(); context.refresh(); } return false; }; Context.prototype.getChar = function(event) { if (event.which === null) { return String.fromCharCode(event.keyCode); // IE } else if (event.which !== 0 && event.charCode !== 0) { return String.fromCharCode(event.which); // the rest } }; /** * Placeholder for town functionality */ /* global victoryText */ Context.prototype.town = function() { if (this.hero.has_lozenge) { this.screens.victory.element.innerHTML = victoryText.format(this.hero.gold); this.showScreen("victory"); } else { this.showScreen("town"); } }; return Context; }()); <file_sep>jogue ===== Javascript Roguelike [See IO page](http://fatbird.github.io/jogue) <file_sep>/* global config, wall, Mob, document, floor, Item, up, down */ var Square = (function() { "use strict"; var Square = function(options) { this.x = options.x; this.y = options.y; this.visibility = config.initial_visibility; this.entity = options.entity || wall; this.level = options.level; this._span = undefined; this._classes = ['grid'].concat(this.entity.classes || []); this._previous = []; }; Square.prototype.add = function(entity) { this._previous.unshift(this.entity); this.entity.classes.forEach(function(cls) { this.removeClass(cls); }, this); this.entity = entity; if (this.entity instanceof Mob) { if (this.entity.aware()) { this.addClass("aware"); } if (this.entity.focused()) { this.removeClass("aware"); this.addClass("focused"); } } this.entity.square = this; this.entity.classes.forEach(function(cls) { this.addClass(cls); }, this); this.span().innerHTML = entity.html; }; Square.prototype.last = function() { return this._previous[0]; }; Square.prototype.remove = function(entity) { this.entity.classes.forEach(function(cls) { this.removeClass(cls); }, this); if (this.entity instanceof Mob) { this.entity.square = undefined; this.removeClass(["focused", "aware"]); } this.entity = this._previous.shift(); this.entity.classes.forEach(function(cls) { this.addClass(cls); }, this); this.span().innerHTML = this.entity.html; }; Square.prototype.cardinals = {"nw": [-1, -1], "n": [0, -1], "ne": [1, -1], "e": [1, 0], "se": [1, 1], "s": [0, 1], "sw": [-1, 1], "w": [-1, 0]}; Square.prototype.reverse = {"nw": "se", "n": "s", "ne": "sw", "e": "w", "se": "nw", "s": "n", "sw": "ne", "w": "e"}; Square.prototype.lighting = ["pitch", "dark", "dim", "visible"]; Square.prototype.span = function() { if (this._span === undefined) { this._span = document.createElement("span"); this._span.setAttribute("id", this.x + "," + this.y); this._span.innerHTML = this.entity.html; this._classes.push(this.lighting[this.visibility]); this._span.className = this._classes.join(" "); } return this._span; }; Square.prototype.updateVisibility = function(level) { if (level > this.visibility) { this.removeClass(this.lighting[this.visibility]); this.visibility = level; this.addClass(this.lighting[this.visibility]); } }; Square.prototype.addClass = function(cls) { if (! (cls instanceof Array)) { cls = [cls]; } for (var ii = 0; ii < cls.length; ++ii) { if (this._classes.indexOf(cls[ii]) === -1) { this._classes.push(cls[ii]); } } this.span().className = this._classes.join(" "); }; Square.prototype.removeClass = function(cls) { if (! (cls instanceof Array)) { cls = [cls]; } for (var ii = 0, jj; ii < cls.length; ++ii) { if ((jj = this._classes.indexOf(cls[ii])) > -1) { this._classes.splice(jj, 1); } } this.span().className = this._classes.join(" "); }; Square.prototype.getOpenAdjacent = function() { var adj = []; if (this.n && this.n.entity != wall) { adj.push({x: this.n.x, y: this.n.y, dir: "n"}); } if (this.e && this.e.entity != wall) { adj.push({x: this.e.x, y: this.e.y, dir: "e"}); } if (this.s && this.s.entity != wall) { adj.push({x: this.s.x, y: this.s.y, dir: "s"}); } if (this.w && this.w.entity != wall) { adj.push({x: this.w.x, y: this.w.y, dir: "w"}); } return adj; }; Square.prototype.isOkForRoom = function() { for (var ii = 0; ii < arguments.length; ++ii) { if (! this[arguments[ii]] || this[arguments[ii]].entity !== wall) { return false; } } return true; }; Square.prototype.markAvailableWalls = function(dir) { var contender = this[dir], cursor = this[dir], id = contender.span().getAttribute("id"), dz, l, r; if (dir === "n") { dz = -1; l = "w"; r = "e"; } else if (dir === "s") { dz = 1; l = "e"; r = "w"; } else if (dir === "w") { dz = -1; l = "s"; r = "n"; } else { dz = 1; l = "n"; r = "s"; } for (var ii = 0; ii < 3 && contender && cursor; ++ii) { if (! (cursor && cursor.entity === wall && cursor[l] && cursor[l].entity === wall && cursor[r] && cursor[r].entity === wall && cursor[dir])) { //contender.removeClass("available"); delete this.level.available[id]; return false; } cursor = cursor[dir]; } this.level.available[id] = {wall: contender, dir: dir}; //contender.addClass("available"); return true; }; Square.prototype.isOpen = function() { return (this.entity === floor || this.entity instanceof Item || this.entity === up || this.entity === down); }; Square.prototype.id = function() { return this.x + "," + this.y; }; return Square; }); <file_sep>/* global document, Square, config, window */ /* global up, down, mobs, items, Gold, Lozenge, floor, wall */ var Level = (function() { "use strict"; var Level = function(options) { this.width = options.width; this.height = options.height; this.level = options.level; this.start = options.start; this.dungeon = options.dungeon; this.element = document.createElement("div"); this.grid = []; this.available = {}; this.open = []; this.mobs = []; this.items = []; var xx, yy, row; for (yy = 0; yy < this.height; ++yy) { row = document.createElement("div"); row.className = "row"; for (xx = 0; xx < this.width; ++xx) { if (! this.grid[xx]) { this.grid[xx] = []; } this.grid[xx].push(new Square({x: xx, y: yy, level: this})); row.appendChild(this.grid[xx][yy].span()); } this.element.appendChild(row); } // Give each square a cardinal direction reference to its neighbours for (xx = 0; xx < this.width; ++xx) { for (yy = 0; yy < this.height; ++yy) { for (var dir in Square.prototype.cardinals) { try { var nx = xx + Square.prototype.cardinals[dir][0], ny = yy + Square.prototype.cardinals[dir][1]; this.grid[xx][yy][dir] = this.grid[nx][ny]; } catch(err) { this.grid[xx][yy][dir] = undefined; } } } } }; /** */ Level.prototype.random = function(min, max) { return Math.floor(Math.random() * (max - min) + min); }; Level.prototype.choice = function() { return arguments[this.random(0, arguments.length)]; }; Level.prototype.getRoomParameters = function(door) { var direction = this.choice("n", "w", "e", "s"), a = {min: this.random(2, 3), max: this.random(3, 8)}, b = {min: this.random(2, 4), max: this.random(4, 12)}, ew = (door && door.x < this.width / 2) ? "e" : "w", ns = (door && door.y < this.height / 2) ? "s" : "n"; if (door) { // starting room, have to choose best direction var cx = door.x / this.width, cy = door.y / this.height; cx = door.x > this.width / 2 ? 1 - cx : cx; cy = door.y > this.height / 2 ? 1 - cy : cy; direction = cx < cy ? ew : ns; //console.log("{0} {1} {2} {3} {4}".format(door.x, door.y, cx, cy, direction)); } if (direction === "n" || direction === "s") { return {dir: direction, lat: b, lng: a}; } return {dir: direction, lat: a, lng: b}; }; Level.prototype.generateLevel = function() { this.entry = this.grid[this.start.x][this.start.y]; var params = this.getRoomParameters(this.entry), num_rooms = 1, mob, item, loc, xy; this.addRoom(this.entry, params.dir, params.lat, params.lng); for (var ii = 0; ii < config.max_attempts && num_rooms < config.max_rooms; ++ii) { var keys = Object.keys(this.available), available = this.available[keys.choice()], door = available.wall, dir = available.dir; params = this.getRoomParameters(); if (this.addRoom(door, dir, params.lat, params.lng)) { ++num_rooms; } } // add entry and exit this.entry = this.grid[this.entry.x][this.entry.y]; this.entry.add(up); this.open.remove(this.entry.id()); this.exit = this.choice.apply(this, this.open).split(","); this.exit = this.grid[this.exit[0]][this.exit[1]]; this.exit.add(down); // add mobs for (var kk = 0; kk < config.max_mobs; ++kk) { mob = this.generateMob(); xy = this.open.draw().split(","); this.mobs.push(mob); this.grid[xy[0]][xy[1]].add(mob); } // add items for (var ll = 0; ll < config.max_items; ++ll) { item = this.generateItem(["Chest", "Pile"].choice()); xy = this.open.draw().split(","); this.items.push(item); this.grid[xy[0]][xy[1]].add(item); } if (this.level === config.lozenge_level) { item = new Lozenge(); xy = this.open.draw().split(","); this.grid[xy[0]][xy[1]].add(item); } }; Level.prototype.generateMob = function() { var type = Object.keys(mobs).choice(), mob = new window[type]({level: this.level}); return mob; }; Level.prototype.generateItem = function() { var type = arguments[0] || Object.keys(items).choice(), item = new window[type](); if (item.consumable && ! item.carryable) { // chest or pile if ([true, false, item.name === "Chest", item.name === "Chest"].choice()) { var gold = new Gold({amount: this.random(0, 10) * this.level }); if (gold.amount > 0) { item.contains.push(gold); } } if ([true, false, item.name === "Chest"].choice()) { var obj = this.generateItem(); if (obj !== Gold) { item.contains.push(obj); } } } return item; }; Level.prototype.addRoom = function(door, dir, lat, lng) { /** * The meat of dungeon generation: this algorithm finds an available wall, * adds a door to it, then tries to carve out a room at least min height * and width and at most max height and width. The direction in which the * carver is facing (i.e., in which wall of the existing room the door is) * is the longitudinal axis of the new room (lng* variables, below; lat* * are lateral equivalents). The carver digs laterally to max_lat, * randomly alternating between left and right for the first row, and then * advances along the longitudinal axis and and carves laterally to the * left/right boundaries established in the first row. * * If at any time, the carver cannot continue because the possible square * doesn't have wall in the next square laterally and longitudinally, room * generation stops and min_* values are checked. If the room is big * enough, it's committed; otherwise it's abandoned. */ var lat_choices = (dir === "n" || dir === "s" ? ["w", "e"] : ["n", "s"]), choices = lat_choices.slice(), lng_choices = (dir === "n" || dir === "s" ? ["n", "s"] : ["w", "e"]), lng_axis = (dir === "n" || dir === "s" ? "y" : "x"), lat_axis = (dir === "n" || dir === "s" ? "x" : "y"), dz = (dir === "n" || dir === "w" ? -1 : 1), rdir = Square.prototype.reverse[dir], ldir = lat_choices[Number(dz === 1)], nw = dir + ldir, se = dir + lat_choices[Number(dz === -1)], room = {}, ii, kk, xx, yy; for (ii = 0; ii < lat_choices.length; ++ii) { room[lat_choices[ii]] = door[dir]; room[lng_choices[ii]] = door[dir]; room[nw] = door[dir]; room[se] = door[dir]; } for (ii = 0; ii < lat.max - 1 && choices.length > 0; ++ii) { var cdir = choices.choice(), latp = room[cdir][cdir], cpdir = ["n", "s"].indexOf(dir) > -1 ? dir + cdir : cdir + dir; if (latp.isOkForRoom(dir, cdir, rdir, cpdir)) { room[cdir] = latp; room[dir + cdir] = latp; } else { if ((ii = choices.indexOf(cdir)) > -1) { choices.splice(ii, 1); } } } var width = room[lat_choices[1]][lat_axis] - room[lat_choices[0]][lat_axis]; if (width + 1 < lat.min) { return false; } loop: for (kk = 1; kk < lng.max; ++kk) { var cdir = lat_choices[1], // jshint ignore:line dirs = [dir, cdir]; if (room[lat_choices[0]][dir].isOkForRoom(dir, cdir, lat_choices[0])) { if (["n", "s"].indexOf(dir) > -1) { dirs.push(dir + lat_choices[0]); dirs.push(dir + lat_choices[1]); } else { dirs.push(lat_choices[0] + dir); dirs.push(lat_choices[1] + dir); } var xdir = ["n", "s"].indexOf(dir) > -1 ? dir + cdir : cdir + dir; room[cdir] = room[lat_choices[0]] = room[lat_choices[0]][dir]; for (ii = 0; ii < width; ++ii) { if (! room[cdir][cdir].isOkForRoom.apply(dirs)) { break loop; } room[cdir] = room[cdir][cdir]; } room[nw] = room[ldir]; } } if (room[nw][lat_axis] > room[se][lat_axis]) { room.tmp = room[nw]; room[nw] = room[se]; room[se] = room.tmp; } var height = room[se][lng_axis] - room[nw][lng_axis]; if (height + 1 < lng.min) { return false; } for (xx = room[nw].x; xx <= room[se].x; ++xx) { for (yy = room[nw].y; yy <= room[se].y; ++yy) { this.grid[xx][yy].add(floor); this.open.push(xx + "," + yy); } } this.grid[door.x][door.y].add(floor); // update available walls for (xx = room[nw].x; xx <= room[se].x; ++xx) { this.grid[xx][room[nw].y].markAvailableWalls("n"); this.grid[xx][room[se].y].markAvailableWalls("s"); } for (yy = room[nw].y; yy <= room[se].y; ++yy) { this.grid[room[nw].x][yy].markAvailableWalls("w"); this.grid[room[se].x][yy].markAvailableWalls("e"); } return true; }; var visibility_grid = [ [[1, 2], [2], [1, 2]], [[2], [], [2]], [[1, 2], [2], [1, 2]], ]; Level.prototype.updateVisibility = function(square) { var x = square.x, y = square.y; for (var yy = -1; yy <= 1; ++yy) { for (var xx = -1; xx <= 1; ++xx) { if (! this.grid[x + xx]) { continue; } if (! this.grid[x + xx][y + yy]) { continue; } this.grid[x + xx][y + yy].updateVisibility(3); if (this.grid[x + xx][y + yy].entity != wall) { var xtd = visibility_grid[xx + 1][yy + 1]; this.grid[x + xx + xx][y + yy + yy].updateVisibility(xtd[0]); if (xtd.length > 1) { this.grid[x + xx + xx][y + yy].updateVisibility(xtd[1]); this.grid[x + xx][y + yy + yy].updateVisibility(xtd[1]); } } } } }; Level.prototype.resetMobs = function(resetFocus) { this.mobs.forEach(function(mob) { mob.reset(resetFocus); }); }; return Level; }); <file_sep>module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Package pkg: grunt.file.readJSON('package.json'), concat: { options: { banner: '<!DOCTYPE html>\n<%= grunt.option("gitRevision") %>\n', process: function(src, filepath) { var files = grunt.file.expand('src/*.js'), anchor = 'init();\n</script>', css = grunt.file.read('src/default.css'); files.forEach(function(filename) { var file = grunt.file.read(filename); file = file.replace('"use strict";\n', ''); src = src.replace(anchor, file + anchor); src = src.replace('<script src="' + filename.replace('src/', '') + '"></script>\n', ''); }, grunt); src = src.replace('<link rel="stylesheet" href="default.css">', '<style>\n' + css + '</style>'); return src; }, }, dist: { src: ['src/index.html'], dest: 'index.html' } }, "git-describe": { concat: { options: { template: '<!-- {%=object%}{%=dirty%} -->' } } } }); // load npm plugins grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-git-describe'); // default tasks grunt.registerTask('default', ['saveRevision', 'concat']); grunt.registerTask('saveRevision', function() { grunt.event.once('git-describe', function (rev) { grunt.option('gitRevision', rev); }); grunt.task.run('git-describe'); }); }; <file_sep>"use strict"; // jshint ignore:line /* global random, window */ function Mob(properties, options) { this.html = ''; this.classes = ['mob']; this.hp = 0; this.inventory = []; this.equipped = undefined; this.worn = undefined; this.gold = 0; this.level = 1; this.square = undefined; this._aware = false; this._focused = false; properties = properties || {}; options = options || {}; for (var attr in properties) { this[attr] = properties[attr]; } for (var opt in options) { this[opt] = options[opt]; } this.setup = function() { for (var ii = 0; ii < this.level; ++ii) { this.hp += random(5, 10); this.gold += random(0, 10); } this.max_hp = this.hp; ["equipped", "has", "worn", "borne"].forEach(function(property) { if (this[property] instanceof Array) { var choice = this[property].choice(); this[property] = new window[choice]({level: this.level}); } }, this); }; } /** * Focus means the mob is focused on killing the hero. Focus is only reset * when the hero leaves the level. */ Mob.prototype.focused = function(set) { if (set !== undefined) { this._focused = !! set; this._aware = !! set; if (this._focused) { this.square.addClass(["focused"]); this.square.removeClass(["aware"]); } else { this.square.removeClass(["focused"]); } } return this._focused; }; /** * Awareness means the mob is weakly focused on killing the hero. If the mob * is focused, the mob is aware and its awareness is not reset; if the mob is * not focused, awareness is reset by the hero running away. */ Mob.prototype.aware = function(set) { if (set !== undefined && ! this._focused) { this._aware = !! set; if (this._aware) { this.square.addClass("aware"); } else { this.square.removeClass("aware"); } } return this._aware; }; Mob.prototype.reset = function(resetFocus) { if (resetFocus !== undefined) { this._focused = !! resetFocus; } this.aware(false); }; function Item(properties, options) { this.html = ''; this.classes = ['item']; this.contains = []; this.consumable = false; this.carryable = true; this.level = 1; properties = properties || {}; options = options || {}; for (var attr in properties) { this[attr] = properties[attr]; } for (var opt in options) { this[opt] = options[opt]; } this.setup = function() { if (this.damage) { this.damage = (this.damage - random(0, this.damage / 2)) * this.level; } if (this.armor) { this.armor = (this.armor - random(0, this.armor / 2)) * this.level; } if (this.name && (this.damage || this.armor)) { this.name = "{0} ({1})".format(this.name, (this.damage || this.armor)); } }; } var mobs = { Bard: {html: '\u266a', equipped: ["Dagger", "Sword"], worn: ["Tunic", "Leather"]}, Snake: {html: '\u2621', has: ["Fang"]}, Skull: {html: '\u2620', has: ["Tooth"], borne: ["Bone"]}, Bishop: {html: '\u2657', equipped: ["Mitre", "Dagger"], worn: ["Tunic"]}, Dwarf: {html: '\u2692', equipped: ["Pick", "Sword"], worn: ["Studded", "Scale", "Chain", "Plate"]}, Cuberoot: {html: '\u221b', equipped: ["Modulo"], borne: ["Indivisibility"]}, Empty: {html: '\u2205', has: ["Void"], borne: ["Haze"]} }, hero = {html: 'I', }, items = { Dagger: {damage: 4}, Sword: {damage: 8}, Mitre: {damage: 10}, Fang: {damage: 3}, Bong: {damage: 5}, Pick: {damage: 7}, Void: {damage: 12}, Modulo: {damage: 8}, Tooth: {damage: 1}, Tunic: {armor: 1}, Leather: {armor: 2}, Bone: {armor: 2}, Studded: {armor: 3}, Haze: {armor: 3}, Scale: {armor: 4}, Chain: {armor: 5}, Plate: {armor: 8}, Indivisibility: {armor: 4}, Gold: {amount: 0}, Chest: {html: '\u2709', consumable: true, carryable: false}, Pile: {html: '\u2234', consumable: true, carryable: false} }, lozenge = {html: '\u22c4', consumable: true, carryable: true, classes: ["item", "treasure"]}, wall = {html: ' ', classes: ['wall']}, floor = {html: '\u203b', classes: ['floor']}, up = {html: '\u2191', classes: ['stairs']}, down = {html: '\u2193', classes: ['stairs']}, none = null ; /** * Create a class of each mob described above */ function makeClass(Prototype, type, properties) { window[type] = function(options) { Prototype.call(this, properties, options); this.kind = type.toLowerCase(); this.name = type; this.classes.push(type.toLowerCase()); if (this.setup) { this.setup(); } }; window[type].prototype = new Prototype(); window[type].constructor = window[type]; } for (var type in items) { makeClass(Item, type, items[type]); } for (var type in mobs) { makeClass(Mob, type, mobs[type]); } makeClass(Mob, "Hero", hero); makeClass(Item, "Lozenge", lozenge);
404ca96b1283e433c0d5e18a265220656d5e6d67
[ "JavaScript", "Markdown" ]
7
JavaScript
fatbird/jogue
10cc1008e908b0839e763c069cdf0eabb8d47ed7
8147b456da59ca6f0dc02c6c6e37799d784d478c
refs/heads/master
<file_sep><?php function validate($title, $content) { if (!( isset($title) && isset($content) && strlen($title) > 0 && strlen($content) > 0 )) { return 'Title AND content required!'; } } ?> <file_sep><?php $title = 'Logging In'; $from = $_GET['from']; include '../../views/blog/login.php'; ?> <file_sep>CREATE TABLE test.posts ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255), content TEXT, created_at DATETIME ); CREATE TABLE test.comments ( id INT PRIMARY KEY AUTO_INCREMENT, post_id INT, author VARCHAR(255), comment TEXT, comment_date DATETIME ); CREATE TABLE test.members ( id INT PRIMARY KEY AUTO_INCREMENT, nickname VARCHAR(255), password VARCHAR(255), email VARCHAR(255), joined_at DATE ); <file_sep>Read [php_tutorial/README.md](../README.md) first! Following exercise 1 (page 110) ------------------------------- Steps: - Go on http://localhost/php_tutorial/ex1/secret.php (the correct password is "<PASSWORD>") <file_sep>Your nickname doesn't match the given password.<br/> <a href="login.php?from=<?php echo $from; ?>">Try again</a> <file_sep><!DOCTYPE html> <html> <head> <title>My awesome blog!</title> <meta charset="utf8" /> <link rel="stylesheet" href="../../views/blog/style.css" type="text/css" /> </head> <body> <h1>My awesome blog!</h1> <a href="index.php">Back to posts list</a> <div class="news"> <h3> <?php echo $post['title']; ?> <em> on (french fashion display) <?php echo $post['created_at']; ?></em> </h3> <p><?php echo $post['content']; ?></p> </div> <h2>Comments</h2> <form method="post" action="comments_post.php"> <fieldset> <legend>Add a comment</legend> <p> <label for="author">Author:</label> <br/> <input type="text" id="author" name="author" /> </p> <p> <label for="comment">Comment:</label> <br/> <textarea id="comment" name="comment"></textarea> </p> <input type="hidden" name="post_id" value="<?php echo $post_id; ?>" /> <input type="submit" value="Send" /> </fieldset> </form> <?php if (count($comments) > 0) { foreach($comments as $comment) { ?> <p> <strong><?php echo $comment['author']; ?></strong> on (french fashion display) <?php echo $comment['comment_date_french_fashion']; ?> </p> <p><?php echo $comment['comment']; ?></p> <?php } } else { echo '<p><em>No comments for this post</em></p>'; } ?> </body> </html> <file_sep><!DOCTYPE httml> <html> <head> <title><?php echo $title; ?></title> <meta charset="utf8" /> </head> <body> <h1><?php echo $title; ?></h1> <form method="post" action="signup_post.php"> <label for="nickname">Nickname:</label> <br/> <input type="text" id="nickname" name="nickname" /> <br/> <label for="pwd">Password:</label> <br/> <input type="<PASSWORD>" id="pwd" name="pwd" /> <br/> <label for="pwd_again">Type again your password:</label> <br/> <input type="<PASSWORD>" id="pwd_again" name="pwd_<PASSWORD>" /> <br/> <label for="email">Email:</label> <br/> <input type="text" id="email" name="email" /> <br/> <input type="submit" value="Sign up" /> </form> </body> </html> <file_sep><!DOCTYPE html> <html> <head> <title><?php echo $title; ?></title> <meta charset="utf8" /> </head> <body> <h1><?php echo $title; ?></h1> <form method="post" action="login_post.php"> <input type="hidden" name="from" value="<?php echo $from; ?>" /> <label for="nickname">Nickname:</label> <br/> <input type="text" id="nickname" name="nickname" /> <br/> <label for="pwd">Password:</label> <br/> <input type="password" id="pwd" name="pwd" /> <br/> <label for="stay_connected">Stay connected?</label> <br/> <input type="checkbox" id="stay_connected" name="stay_connected" /> <br/> <input type="submit" value="Log in" /> </form> </body> </html> <file_sep><?php try { $db = new PDO( 'mysql:host=localhost;dbname=test', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) ); } catch (Exception $e) { die('ERROR: ' . $e->getMessage()); } ?> <file_sep><?php $title = 'Signing Up'; include '../../views/blog/signup.php'; ?> <file_sep><?php echo $msg; ?><br/> <a href="signup.php">Try again!</a> <file_sep><?php $pwd = <PASSWORD>; if (isset($_POST['pwd'])) { $pwd = $_POST['pwd']; } if (!isset($pwd) && htmlspecialchars($pwd) != '<PASSWORD>') { ?> <!DOCTYPE html> <html> <head> <title>Restricted access - PHP Tutorial</title> </head> <body> <form method="POST" action="secret.php"> <label for="pwd">Please, enter password:</label> <br/> <input type="password" id="pwd" name="pwd"/> <br/> <input type="submit"/> </form> </body> </html> <?php } elseif (isset($pwd) && $pwd != '<PASSWORD>') { echo 'Wrong password, try again! <br/>'. '<a href="secret.php">Enter password</a>'; } else { echo 'Welcome to this restricted area. <br/>' . 'The secret message is: CONGRATULATIONS!'; } ?> <file_sep>Welcome <strong><?php echo $nickname; ?>!</strong><br/> <a href="index.php">Go to our Home Page</a> <file_sep><?php include '../../models/db.php'; $post_id = $_GET['post_id']; function get_post($post_id) { global $db; $get_post = $db->prepare( "SELECT title, content, DATE_FORMAT(created_at, '%d/%m/%Y at %Hh%imin%ss') AS created_at " . "FROM posts " . "WHERE id = :post_id" ); $get_post->execute(array( 'post_id' => $post_id )); $post = $get_post->fetch(); $get_post->closeCursor(); return $post; } function get_comments_from_post($post_id) { global $db; $get_comments_from_post = $db->prepare( "SELECT author, comment, DATE_FORMAT(comment_date, '%d/%m/%Y at %Hh%imin%ss') AS comment_date_french_fashion " . "FROM comments " . "WHERE post_id = :post_id " . "ORDER BY comment_date" ); $get_comments_from_post->execute(array( 'post_id' => $post_id )); $comments = $get_comments_from_post->fetchAll(); $get_comments_from_post->closeCursor(); return $comments; } ?> <file_sep><?php $title = 'Admin - Add post'; $form_action = 'add_post.php'; include 'edit_form.php'; ?> <file_sep>Following a (french) PHP [tutorial](14668-concevez-votre-site-web-avec-php-et-mysql.pdf) from [Open Classrooms](http://www.openclassrooms.com) Tools: - XAMPP 5.6.8-0 (Apache 2.4.12, PHP 5.6.8, MySQL 5.6.24, phpMyAdmin 4.4.3) Steps: - Start Apache from XAMPP's panel - Synchronize this folder (php_tutorial) in XAMPP's htdocs folder - Follow one of the following link: [ex1](ex1) [ex2](ex2) [ex3](ex3) [ex4](ex4) <file_sep><?php session_start(); $_SESSION = array(); session_destroy(); setcookie('member_nickname', null); setcookie('member_pwd', null); header('Location: index.php'); ?> <file_sep><?php include '../../models/db.php'; function insert_post($title, $content) { global $db; $insert_post = $db->prepare( 'INSERT INTO posts(title, content, created_at) ' . 'VALUES(:title, :content, NOW())' ); $insert_post->execute(array( 'title' => $title, 'content' => $content )); $insert_post->closeCursor(); return $db->lastInsertId(); } ?> <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf8" /> <title>Page not found</title> </head> <body> <h1>Page not found</h1> <p>We are sorry, but we can't find the page you are looking for.</p> <p> You should check the URL you entered or return to our <a href="<?php echo $SERVER['DOCUMENT_ROOT'] . '/php_tutorial/ex4/'; ?>index.php">Home Page</a> </p> </body> </html> <file_sep><?php $page_number = -1; if (isset($_GET['page'])) { $page_number = (int) $_GET['page']; } if ($page_number < 1) { $page_number = 1; // Display first page by default } $offset = ($page_number - 1) * 10; try { $db = new PDO( 'mysql:host=localhost;dbname=test;', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) ); } catch (Exception $e) { die('ERROR: ' . $e->getMessage()); } //TODO(find a way to use an integer in prepared statement) $response = $db->query('SELECT nickname, message FROM chat ORDER BY id DESC LIMIT ' . $offset . ', 10'); $nickname = ''; if (isset($_COOKIE['nickname'])) { $nickname = $_COOKIE['nickname']; } ?> <!DOCTYPE html> <html> <head> <meta charset="utf8" /> <title>Chat</title> </head> <body> <form action="chat_post.php" method="post"> Nickname: <br/> <input type="text" name="nickname" value="<?php echo $nickname; ?>" /> <br/> Message: <br/> <textarea name="message"/></textarea> <br/> <input type="submit" value="Send" /> </form> <p><a href="chat.php">Refresh</a></p> <?php while ($data = $response->fetch()) { ?> <p> <strong><?php echo htmlspecialchars($data['nickname']); ?>:</strong> <?php echo htmlspecialchars($data['message']); ?> </p> <?php } ?> </body> </html> <?php $response->closeCursor(); ?> <file_sep><!DOCTYPE html> <html> <head> <title><?php echo $title; ?></title> <meta charset="utf8" /> <link rel="stylesheet" type="text/css" href="../style.css" /> </head> <body> <h1><?php echo $title; ?></h1> <a href="../../controllers/blog/index.php">Back to Home Page</a> <br/> <a href="add.php">Add a new post</a> <ul class="no-decoration"> <?php foreach ($posts as $post) { ?> <li> <!--TODO(how to put "return false;" in a function?)--> <form method="get" action="delete.php" onsubmit="confirmDeletion(this); return false;"> <input type="hidden" name="post_id" value="<?php echo $post['id']; ?>" /> <input type="submit" value="Delete" /> <a href="edit.php?post_id=<?php echo $post['id']; ?>"> <?php echo $post['title']; ?> </a> </form> </li> <?php } ?> </ul> </body> <script> function confirmDeletion(thisParam) { if(confirm('Are you sure?')) thisParam.submit(); } </script> </html> <file_sep><!DOCTYPE html> <html> <head> <title><?php echo $title; ?></title> <meta charset="utf8" /> </head> <body> <h1><?php echo $title; ?></h1> <form method="post" action="<?php echo $form_action; ?>"> <input type="hidden" name="post_id" value="<?php echo $post_id; ?>" /> Title: <br/> <input type="text" name="title" value="<?php echo $post['title']; ?>" size="50" /> <br/> Content: <br/> <textarea name="content" rows="5" cols="100"><?php echo $post['content']; ?></textarea> <br/> <input type="button" value="Cancel" onclick="goToAdminHomePage()" /> <input type="submit" value="Save" /> </form> </body> <script> function goToAdminHomePage() { location.href = '.'; } </script> </html> <file_sep><?php include '../../models/blog/comments.php'; $post_id = $_GET['post_id']; if (isset($post_id)) { $post_id = intval($post_id); $post = get_post($post_id); if (empty($post)) { include '../../views/404.php'; exit; } $post['title'] = htmlspecialchars($post['title']); $post['content'] = nl2br(htmlspecialchars($post['content'])); $comments = get_comments_from_post($post_id); foreach($comments as $key => $comment) { $comments[$key]['author'] = htmlspecialchars($comment['author']); $comments[$key]['comment'] = nl2br(htmlspecialchars($comment['comment'])); } include '../../views/blog/comments.php'; } ?> <file_sep><?php include '../models/add_post.php'; include 'edit_validation.php'; $title = $_POST['title']; $content = $_POST['content']; if ($error_msg = validate($title, $content)) { include '../views/add_post_error.php'; exit; } else { if ($post_id = insert_post($title, $content)) header('Location: ../../controllers/blog/comments.php?post_id=' . $post_id); } include '../../views/404.php'; // If no posts have been inserted, display error page ?> <file_sep><?php echo $error_msg; ?> <a href="edit.php?post_id=<?php echo $post_id; ?>">Try again</a> <file_sep><?php include '../../models/db.php'; function get_post($post_id) { global $db; $get_post = $db->prepare('SELECT * FROM posts WHERE id = :post_id'); $get_post->execute(array( 'post_id' => $post_id )); $post = $get_post->fetch(); $get_post->closeCursor(); return $post; } ?> <file_sep><?php $pwd = $_POST['pwd']; if (isset($pwd)) { if ($pwd == '<PASSWORD>') { echo 'Welcome to this restricted area. <br/>' . 'The secret message is: CONGRATULATIONS!'; } else { echo 'Wrong password, try again! <br/>'. '<a href="secret.php">Enter password</a>'; } } else { echo 'Password required'; } ?> <file_sep><?php include '../../models/blog/index.php'; function display_pagination() { global $page, $nb_pages; echo '<p>Page'; for ($i = 1; $i <= $nb_pages; $i++) { if ($i !== $page) echo ' <a href="index.php?page=' . $i . '">' . $i . '</a>'; else echo ' ' . $i; } echo '</p>'; } session_start(); $member_nickname = ''; $member_pwd = ''; $connected_member_nickname = ''; if (isset($_COOKIE['member_nickname'])) { $member_nickname = $_COOKIE['member_nickname']; } if (isset($_COOKIE['member_pwd'])) { $member_pwd = $_COOKIE['member_pwd']; } if (isset($_SESSION['connected_member_nickname'])) { $connected_member_nickname = $_SESSION['connected_member_nickname']; } if ( !$connected_member_nickname && $member_nickname && $member_pwd ) { if (check_cookies($member_nickname, $member_pwd)) { $connected_member_nickname = $_SESSION['connected_member_nickname'] = $member_nickname; }; } define('NB_POSTS_PER_PAGE', 5); $page = 0; if (isset($_GET['page'])) { $page = (int) $_GET['page']; } if ($page === 0) $page++; // Get the number of posts $nb_posts = get_nb_posts(); // Get the number of pages $remainder = $nb_posts % NB_POSTS_PER_PAGE; $nb_pages = intval($nb_posts / NB_POSTS_PER_PAGE) + ($remainder > 0 ? 1 : 0);//TODO(use ceil() instead?) $offset = ($page - 1) * NB_POSTS_PER_PAGE; $posts = get_posts($offset);//TODO(add NB_POSTS_PER_PAGE as a parameter) foreach($posts as $key => $post) { $posts[$key]['title'] = htmlspecialchars($post['title']); $posts[$key]['content'] = nl2br(htmlspecialchars($post['content'])); } include '../../views/blog/index.php'; ?> <file_sep><?php include '../../models/db.php'; function get_pwd($nickname) { global $db; $get_pwd = $db->prepare( 'SELECT password ' . 'FROM members ' . 'WHERE nickname = :nickname' ); $get_pwd->execute(array( 'nickname' => $nickname )); $hashed_pwd = $get_pwd->fetch(); $get_pwd->closeCursor(); return $hashed_pwd['password']; } ?> <file_sep>Read [README.md](README.md) first! Steps: - Start MySQL from XAMPP's panel - Go on http://localhost/phpmyadmin/ - Create test database from [db.sql](db.sql) file - Follow one of the following link: [ex3](ex3) [ex4](ex4) <file_sep><?php include '../../models/db.php'; function list_posts() { global $db; $list_posts = $db->query('SELECT * FROM posts'); $posts = $list_posts->fetchAll(); $list_posts->closeCursor(); return $posts; } ?> <file_sep><?php include '../../models/blog/signup_post.php'; $nickname = $_POST['nickname']; $pwd = $_POST['pwd']; $pwd_again = $_POST['pwd_again']; $email = $_POST['email']; function display_error($msg) { include '../../views/blog/signup_post_error.php'; exit; } if ( isset($nickname) && isset($pwd) && isset($pwd_again) && isset($email) ) { if (strlen($nickname) === 0) { display_error('Nickname required.'); } if (strlen($pwd) === 0) { display_error('Password required.'); } if (count_identical_nicknames($nickname) > 0) { display_error( 'Another member is already using the nickname ' . '<strong>' . $nickname . '</strong>. Please choose another one.' ); } if ($pwd !== $pwd_again) { display_error('The two passwords are not identical.'); } //TODO(replace by official email format specification) if (!preg_match('#^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,}$#i', $email)) { display_error('Email format is invalid.'); } //TODO(what if password_hash() returns FALSE?) if (insert_member($nickname, password_hash($pwd, PASSWORD_DEFAULT), $email) === 1) { include '../../views/blog/signup_post_success.php'; } else { display_error( "We haven't been able to register you. " . "We are sorry for the inconvenience." ); } } else { header('Location: signup.php'); } ?> <file_sep>Read [php_tutorial/README_ex3_ex4.md](../README_ex3_ex4.md) first! Following exercise 2 (page 166) ------------------------------- Steps: - Create chat table from [db.sql](db.sql) file - Go on http://localhost/php_tutorial/ex3/chat.php <file_sep>CREATE TABLE test.chat ( id INT PRIMARY KEY AUTO_INCREMENT, nickname VARCHAR(255), message VARCHAR(255) ); <file_sep>Read [php_tutorial/README.md](../README.md) first! Following exercise 1, going further (page 113) ---------------------------------------------- Steps: - Go on http://localhost/php_tutorial/ex2/secret.php (the correct password is "<PASSWORD>") <file_sep><?php include '../models/edit_post.php'; include 'edit_validation.php'; $title = $_POST['title']; $content = $_POST['content']; $post_id = (int) $_POST['post_id']; if ($error_msg = validate($title, $content)) { include '../views/edit_post_error.php'; exit; } else { if (update_post($title, $content, $post_id) === 1) header('Location: ../../controllers/blog/comments.php?post_id=' . $post_id); } //TODO(should not display a "not found" error when there are no changes) include '../../views/404.php'; // If no posts have been updated, display error page ?> <file_sep><?php include '../../models/db.php'; function update_post($title, $content, $post_id) { global $db; $update_post = $db->prepare( 'UPDATE posts ' . 'SET title = :title, content = :content ' . 'WHERE id = :post_id' ); $update_post->execute(array( 'title' => $title, 'content' => $content, 'post_id' => $post_id )); $nb_updated_posts = $update_post->rowCount(); $update_post->closeCursor(); return $nb_updated_posts; } ?> <file_sep><?php if (!isset($post)) { $post = array('title' => '', 'content' => ''); } $post['title'] = htmlspecialchars($post['title']); $post['content'] = htmlspecialchars($post['content']); include '../views/edit_form.php'; ?> <file_sep><?php include '../../models/db.php'; function count_identical_nicknames($nickname) { global $db; //TODO(check unique constraint instead) $count_identical_nicknames = $db->prepare( 'SELECT COUNT(*) AS nb_identical_nicknames ' . 'FROM members ' . 'WHERE nickname = :nickname' ); $count_identical_nicknames->execute(array( 'nickname' => $nickname )); $nb_identical_nicknames = $count_identical_nicknames->fetch(); $count_identical_nicknames->closeCursor(); return $nb_identical_nicknames['nb_identical_nicknames']; } function insert_member($nickname, $hashed_pwd, $email) { global $db; $insert_member = $db->prepare( 'INSERT INTO members(nickname, password, email, joined_at) '. 'VALUES(:nickname, :password, :email, NOW())' ); $insert_member->execute(array( 'nickname' => $nickname, 'password' => $<PASSWORD>, 'email' => $email )); $nb_inserted_members = $insert_member->rowCount(); $insert_member->closeCursor(); return $nb_inserted_members; } ?> <file_sep><?php echo $error_msg; ?> <a href="../controllers/add.php">Try again</a> <file_sep><?php include '../../models/db.php'; function check_cookies($member_nickname, $member_pwd) { global $db; $check_cookies = $db->prepare( 'SELECT nickname ' . 'FROM members ' . 'WHERE nickname = :nickname AND password = :<PASSWORD>' ); $check_cookies->execute(array( 'nickname' => $member_nickname, 'password' => $<PASSWORD> )); $nickname = $check_cookies->fetch(); $check_cookies->closeCursor(); return $nickname['nickname']; } function get_nb_posts() { global $db; $get_nb_posts = $db->query('SELECT COUNT(*) AS nb_posts FROM posts'); $nb_posts = $get_nb_posts->fetch(); $get_nb_posts->closeCursor(); return $nb_posts['nb_posts']; } function get_posts($offset) { global $db; $get_posts = $db->prepare("" . "SELECT title, id, content, DATE_FORMAT(created_at, '%d/%m/%Y at %Hh%imin%ss') AS created_at_french_fashion " . "FROM posts " . "ORDER BY created_at DESC " . "LIMIT :offset, 5" ); $get_posts->bindParam(':offset', $offset, PDO::PARAM_INT); $get_posts->execute(); $posts = $get_posts->fetchAll(); $get_posts->closeCursor(); return $posts; } ?> <file_sep><?php include '../../models/db.php'; function remove_comments_from_post($post_id) { global $db; //TODO(add constraint on foreign key) $remove_comments_from_post = $db->prepare('DELETE FROM comments WHERE post_id = :post_id'); $remove_comments_from_post->execute(array( 'post_id' => $post_id )); $remove_comments_from_post->closeCursor(); } function remove_post($post_id) { global $db; $remove_post = $db->prepare('DELETE FROM posts WHERE id = :post_id'); $remove_post->execute(array( 'post_id' => $post_id )); $nb_deleted_posts = $remove_post->rowCount(); $remove_post->closeCursor(); return $nb_deleted_posts; } ?> <file_sep><?php include '../models/edit.php'; $post_id = $_GET['post_id']; if (isset($post_id)) { $post_id = (int) $post_id; $post = get_post($post_id); if (empty($post)) { include '../../views/404.php'; exit; } $title = 'Admin - Edit post'; $form_action = 'edit_post.php'; } else { header('Location: index.php'); } include 'edit_form.php'; ?> <file_sep><?php include '../../models/blog/login_post.php'; session_start(); $from = $_POST['from']; $nickname = $_POST['nickname']; $pwd = $_POST['pwd']; $hashed_pwd = get_pwd($nickname); if (password_verify($pwd, $hashed_pwd)) { if ($_POST['stay_connected']) { setcookie('member_nickname', $nickname, time() + 365 * 24 * 3600, null, null, null, true); setcookie('member_pwd', $hashed_pwd, time() + 365 * 24 * 3600, null, null, null, true); } $_SESSION['connected_member_nickname'] = $nickname; header('Location: ' . $from); } else { include '../../views/blog/login_post_error.php'; } ?> <file_sep><?php include '../models/index.php'; $posts = list_posts(); foreach($posts as $key => $post) { $posts[$key]['title'] = htmlspecialchars($post['title']); } $title = 'Admin - Posts list'; include '../views/index.php'; ?> <file_sep><!DOCTYPE html> <html> <head> <title>My awesome blog!</title> <meta charset="utf8" /> <link rel="stylesheet" href="../../views/blog/style.css" type="text/css" /> </head> <body> <p> <?php if ($connected_member_nickname) { ?> Connected as <em><?php echo $connected_member_nickname; ?></em> | <a href="../../controllers/blog/logout.php">Log out</a> <?php } else { ?> <a href="../../controllers/blog/login.php?from=<?php echo $_SERVER['PHP_SELF']; ?>">Log in</a> | <a href="../../controllers/blog/signup.php">Sign up</a> <?php } ?> <a class="float-right" href="../../admin/controllers/index.php">Admin section</a> </p> <h1>My awesome blog!</h1> <?php display_pagination(); ?> <?php foreach ($posts as $post) { ?> <div class="news"> <h3> <?php echo $post['title']; ?> <em>on (french fashion display) <?php echo $post['created_at_french_fashion']; ?></em> </h3> <p> <?php echo $post['content']; ?> <br/> <a href="comments.php?post_id=<?php echo $post['id']; ?>"><em>Comments</em></a> </p> </div> <?php } display_pagination(); ?> </body> </html> <file_sep><?php include '../../models/db.php'; function insert_comment($post_id, $author, $comment) { global $db; $insert_comment = $db->prepare( 'INSERT INTO comments(post_id, author, comment, comment_date)' . 'VALUES(:post_id, :author, :comment, NOW())' ); $insert_comment->execute(array( 'post_id' => $post_id, 'author' => $author, 'comment' => $comment )); $insert_comment->closeCursor(); } ?> <file_sep><?php include '../models/delete.php'; $post_id = $_GET['post_id']; if (isset($post_id)) { $post_id = (int) $post_id; remove_comments_from_post($post_id); if (remove_post($post_id) === 1) header('Location: .'); } include '../../views/404.php'; // If no posts have been deleted, display error page ?> <file_sep><?php include '../../models/blog/comments_post.php'; $author = $_POST['author']; $comment = $_POST['comment']; $post_id = (int) $_POST['post_id'];//TODO(check that the post_id exists in order to avoid orphan comments) if (!( isset($author) && isset($comment) && strlen($author) > 0 && strlen($comment) > 0 )) { include '../../views/blog/comments_post_error.php'; exit; } insert_comment($post_id, $author, $comment); header('Location: comments.php?post_id=' . $post_id); ?> <file_sep><?php try { $db = new PDO( 'mysql:host=localhost;dbname=test;', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) ); } catch (Exception $e) { die('ERROR: ' . $e->getMessage()); } $nickname = $_POST['nickname']; $message = $_POST['message']; if (isset($nickname) && isset($message)) { if (strlen($nickname) > 0 && strlen($message) > 0) { $query = $db->prepare( 'INSERT INTO chat(nickname, message) VALUES(:nickname, :message)' ); $query->execute(array( 'nickname' => $nickname, 'message' => $message )); $query->closeCursor(); // Retain user's nickname setcookie('nickname', $nickname, time() + 60, null, null, null, true); } else { echo '<p>You must provide a nickname AND a message!</p>'; echo '<a href="chat.php">Back</a>'; return; // Avoid header() call } } header('Location: chat.php'); ?> <file_sep>Read [php_tutorial/README_ex3_ex4.md](../README_ex3_ex4.md) first! Following exercise 3 (page 186) and 4 (page 265) ------------------------------------------------ Steps: - Create posts, comments and members tables from [db.sql](db.sql) file - Edit the file at [admin/.htaccess](admin/.htaccess) according to your server configuration: look for the line starting by AuthUserFile and change the absolute path to .htpasswd file - Use XAMPP's htpasswd utility (in /Applications/XAMPP/bin on Mac OS) to edit the file at [admin/.htpasswd](admin/.htpasswd) by issuing the following command: htpasswd -b admin/.htpasswd login password - Go on http://localhost/php_tutorial/ex4/controllers/blog/ (admin section login is "login" and password is "<PASSWORD>")
ea883b89a00813eba73c5d077b7f83da17f5b71e
[ "Markdown", "SQL", "PHP" ]
51
PHP
amir-toly/php_tutorial
8bb2c0e752a93a1af6f4e586ff931a3a653cbde7
9c975b62370286a6291853c031ac9533d058dea6
refs/heads/master
<repo_name>ahmedthewavemaker/swole-mate-api<file_sep>/migrations/001.do.create.workout.sql CREATE TABLE workout ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, email TEXT NOT NULL , muscle TEXT NOT NULL , exercise TEXT NOT NULL , sets INTEGER , reps INTEGER )<file_sep>/test/workout-fixture.js function makeWorkoutArray (){ return [ { id: 23, email: "<EMAIL>", muscle: "legs", exercise: "squats", sets: 3, reps: 15, }, { id: 26, email: "<EMAIL>", muscle: "arms", exercise: "biceps", sets: 3, reps: 10, } ] } module.exports = {makeWorkoutArray};<file_sep>/seeds/seed.workout.sql INSERT INTO workout (id, email, muscle, exercise, sets, reps) VALUES (1, '<EMAIL>', 'chest', 'chest workout 1', 3, 10) <file_sep>/seeds/truncate.sql TRUNCATE workout RESTART IDENTITY CASCADE<file_sep>/src/config.js module.exports = { PORT: process.env.PORT || 8000, NODE_ENV: process.env.NODE_ENV || 'development', REACT_APP_BASE_URL: process.env.REACT_APP_BASE_URL || "http://localhost:8000", CLIENT_ORIGIN: 'https://swole-mate-app.vercel.app/', DATABASE_URL:process.env.DATABASE_URL || 'postgresql://dunder_mifflin@localhost/swole-mate', TEST_DATABASE_URL:'postgresql://dunder_mifflin@localhost/swole-mate-test', }<file_sep>/Router/workout-router.js const express = require('express') const xss = require('xss') const WorkoutService = require('./workout-service') const workoutRouter = express.Router() const jsonParser = express.json() const serializeWorkout = workout=> ({ id: workout.id, email: workout.email, muscle: workout.muscle, exercise: workout.exercise, sets: workout.sets, reps: workout.reps, }) workoutRouter .route('/') .get((req, res, next) =>{ const knexInstance = req.app.get('db') WorkoutService.getByEmail(knexInstance, req.query.email) .then(workouts =>{ res.json(workouts.map(serializeWorkout)) }) .catch(next) }) .post(jsonParser, (req, res, next) =>{ const {email, muscle, exercise, sets, reps} = req.body; const newWorkout = {email, muscle, exercise, sets, reps} if(!email){ return res .status(400) .json({message: "Missing 'email' in request body"}) } if(!muscle){ return res .status(400) .json({message: "Missing 'muscle' in request body"}) } if(!exercise){ return res .status(400) .json({message: "Missing 'exercise' in request body"}) } if(!sets){ return res .status(400) .json({message: "Missing 'sets' in request body"}) } if(!reps){ return res .status(400) .json({message: "Missing 'reps' in request body"}) } WorkoutService.insertWorkout( req.app.get('db'), newWorkout ) .then(workout =>{ res .status(201) .json(serializeWorkout(workout)) }) .catch(next) }) workoutRouter .route('/:workout_id') .delete((req, res, next) => { WorkoutService.deleteWorkout( req.app.get('db'), req.params.workout_id ) .then(numRowsAffected => { res.status(204).end() }) .catch(next) }) module.exports = workoutRouter
a3348f45c8ac57f4703b8250c2d3eb7b86c36f60
[ "JavaScript", "SQL" ]
6
SQL
ahmedthewavemaker/swole-mate-api
1493e60cd076213929452b89e32b5ff81305884f
7c9958b7853dda99a19ebc04049cf0af182d4478
refs/heads/master
<repo_name>golfchanut/sratong<file_sep>/modules/print/index.js var opPage = 'print'; $(document).ready(function() { get_coures_id_list(); //$(".course_detal_box").hide(); }); function set_room(){ $(".room_value").val($("#room_search").val()); } function get_downloadPDF_all(){ $( "#form_pdf_all_page" ).submit(); } function get_downloadPDF_cover(){ $( "#form_pdf_cover_page" ).submit(); } function get_class_level(){ var coures_id_list_val =$("#coures_id_list").val(); $(".pdf_value").val(coures_id_list_val); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_class_level" }); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#place_class_level").html(data.class_level); $("#place_class_level_val").val(data.class_level); if (data.status==2) { if (data.status_form==25 ||data.status_form==26 || data.status_form==27) { $(".class_set").css('display','inline-block'); }else{ $(".class_set").css('display','none'); } }else{ $(".class_set").css('display','inline-block'); } $("#room_search").html(data.room); $(".status").val(data.status); $(".status_form").val(data.status_form); $(".room_value").val($("#room_search").val()); }) } function get_coures_id_list(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_coures_id_list" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#coures_id_list").html(data.coures_id_list); get_class_level(); }) }<file_sep>/modules/attend_class/index.php <?php session_start(); ?> <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="circle-bg-violet"> <img class="head-img-circle" src="assets/images/9.png"> </div> <div class="text-head-title"> <p>บันทึกเข้าเรียน</p> </div> <div class="text-head-desc"> <p>ใช้สำหรับการบันทึกคะแนนของนักเรียนในแต่ละรายวิชา</p> </div> <div class="row pd-40 pt-80 stage-set" > <?php if($_SESSION['ss_status']==2){ ?> <div class="col-sm-12 col-xs-12 mt-30"> <div class="set-line"> <form id="frm_data_room_admin"> <p class="text-bold text-inline fs-16">เลือกภาคเรียน</p> <select id="term_data" name="term_data" class="form-control search-drop-sub-class mr-20"> <option value="1">1</option> <option value="2">2</option> <option selected="selected" value="1,2">1,2</option> </select> <p class="text-inline fs-14">ปีการศึกษา</p> <select id="year_data" name="year_data" class="form-control search-drop-sub-years mr-20"> </select> <div id="btn_search_course_detail_admin" class="btn-search-save-score"> <div class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </form> </div> </div> <?php } ?> <div class="col-sm-12 col-xs-12 mt-5"> <div class="set-line"> <form id="frm_data_room"> <p class="text-bold text-inline fs-16">เลือกรายวิชา</p> <select onchange="get_class_level()" id="coures_id_list" name="coures_id_list" class="form-control search-drop-sub-id mr-30"> </select> <p class="text-inline fs-14">ชั้น</p> <p id="place_class_level" class="text-inline mr-20"></p> <span id="slash-class" class="slash-class" style="display: none;">/</span> <form id="frm_data_room"> <select id="room_search" style="display: none;" name="room_search" class="form-control search-drop-sub-class mr-20"> </select> <div id="btn_search_course_detail" class="btn-search-save-score"> <div class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </form> </div> </div> </div> <div class="row"> <div class="hr-co-text-depart mt-nega-30"></div> </div> <div class="ml-50 mr-50 mt-nega-10 course_detal_box" style="display: none;" > <div class="row"> <div class="box-search-depart"> <div class="set-line"> <div id="rate_score_box" class="col-sm-12 col-xs-12" style="display: block;"> <div class="row"> <table> <tbody style="border: none;"> <tr > <td class="text-before-box3 text-bold" style="float: right;"> รหัสวิชา </td> <td width="100px"> <p id="place_detail_courseID" class=" text-before-box2 " ></p> </td> <td class="text-before-box3 text-bold"> รายวิชา </td> <td width="350px"> <p id="place_detail_name" class=" text-before-box2 "></p> </td> <td class="text-before-box3 text-bold"> น.น./นก. </td> <td width="40px"> <p id="place_detail_unit" class=" text-before-box2 "></p> </td> <td class="text-before-box3 text-bold"> เวลาเรียน/สัปดาห์ </td> <td > <p id="place_detail_hr_learn" class=" text-before-box2 "></p> </td> </tr> <tr > <td class="text-before-box3 text-bold" style="float: right;"> ชั้น </td> <td> <p id="place_detail_class_level" class=" text-before-box2 "> </p> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <input type="text" hidden="hidden" id="registed_course_id" name="registed_course_id"> <div class="ml-50 mr-50 course_detal_box " style="display: none;" > <div class="row"> <div class="box-search-depart"> <div class="set-line"> <div id="rate_score_box" class="col-sm-12 col-xs-12" style="display: block;"> <div class="row"> <table> <tbody style="border: none;"> <tr id="get_day_set"> </tr> </tbody> </table> <table class="mt-20"> <tbody style="border: none;"> <tr> <td class="text-before-box3 text-bold" style="float: right;"> สัปดาห์ </td> <td width="200px"> <form id="frm_data_legth_score"> <select onchange="get_day_list()" id="length_list_val" name="length_list_val" class="form-control search-drop-length-ob mt-5 week_m"> </select> </form> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="alert_attend_day_chk ml-50 mr-50 mt-20 " style="display: none;"> <div class="row"> <div class="col-md-12"> <div style="width: 70%;background-color: #ac68cc;margin: 0 auto;padding: 30px;"> <p style="color: #fff;font-size: 30px;text-align: center;">กรุณากำหนดวันเรียน</p> </div> </div> </div> </div> <div class=" ml-50 mr-50 mt-20 course_detal_box num_attend_day_chk" style="display: none;"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "3" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "3" width="8%" style=" vertical-align: middle;">รหัส</td> <td id="room_col" rowspan = "3" width="8%" style="display: none; vertical-align: middle;">ห้อง</td> <td rowspan = "3" width="35%" style=" vertical-align: middle;">ชื่อ-สกุล</td> <td id="set_colspan_save_score_title" colspan="6">บันทึกเข้าเรียน</td> </tr> <tr> <td colspan="5" id="week_title"></td> <td style="width: 8%">เวลาเรียน</td> <td style="width: 8%">เฉลี่ย<br>(ร้อยละ)</td> </tr> <tr id="week_header"> </tr> </thead> <tbody id="detail_std" class="body-table"> </tbody> </table> </div> </div> </div> <!-- <div class="btn-group-set-add-delete row pd-30 "> <div class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalAddAttend" class="btn-violet"> บันทึก </div> </div>--> <input id="all_attendID" hidden="hidden" type="text" name="" value=""> <div class="ml-50"> <div class="row"> <div class="col-sm-2"> <p>หมายเหตุ : </p> </div> <div class="col-sm-6"> <table> <tbody class="border-none"> <tr> <td width="20px">1</td> <td width="70px">หมายถึง</td> <td width="70px">มา</td> <td width="80px">มีค่าเท่ากับ</td> <td width="30px">1</td> <td width="40">คะแนน</td> </tr> <tr> <td width="20px">ล</td> <td width="70px">หมายถึง</td> <td width="70px">ลากิจ</td> <td width="80px">มีค่าเท่ากับ</td> <td width="30px">0</td> <td width="40">คะแนน</td> </tr> <tr> <td width="20px">ป</td> <td width="70px">หมายถึง</td> <td width="70px">ลาป่วย</td> <td width="80px">มีค่าเท่ากับ</td> <td width="30px">0</td> <td width="40">คะแนน</td> </tr> <tr> <td width="20px">ข</td> <td width="70px">หมายถึง</td> <td width="70px">ขาด</td> <td width="80px">มีค่าเท่ากับ</td> <td width="30px">0</td> <td width="40">คะแนน</td> </tr> <tr> <td width="20px">น</td> <td width="70px">หมายถึง</td> <td width="70px">หนีเรียน</td> <td width="80px">มีค่าเท่ากับ</td> <td width="30px">0</td> <td width="40">คะแนน</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <input id="std_id_all" type="text" hidden="hidden" name=""> </div><file_sep>/modules/mobile_api/config.php <?php @header( 'Pragma: no-cache' ); @header( 'Content-Type:text/html; charset=utf-8'); date_default_timezone_set('Asia/Bangkok'); error_reporting(0); define("DB_SERVER","localhost"); define("DB_USER","admin_eva"); define("DB_PASS","<PASSWORD>"); define("DB_DATABASE","sratongact_eva"); ?> <file_sep>/modules/attend_class/backup/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_week_between"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_week_between($coures_id_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_count_adttend_class_val"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_count_adttend_class_val($coures_id_list_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_attend_score_std"){ $std_id_all=$_POST['std_id_all']; $value_attend_week=$_POST['value_attend_week']; $all_attendID=$_POST['all_attendID']; $coures_id_list_val=$_POST['coures_id_list_val']; //$set_count_adttend_class_val=$_POST['set_count_adttend_class_val']; $arr_std_id_all = explode("-", $std_id_all); $arr_value_attend_week = explode(",", $value_attend_week); $arr_all_attendID = explode("-", $all_attendID); $num_1=0; for ($i=0; $i <count($arr_std_id_all) ; $i++) { for ($k=0; $k < 10; $k++) { $class_data->sql =" UPDATE tbl_attend_class SET score_status='$arr_value_attend_week[$num_1]' WHERE DataID=$arr_all_attendID[$num_1] "; echo $class_data->query(); $num_1++; } } //echo $class_data->set_count_adttend_class_val($coures_id_list_val,$set_count_adttend_class_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_week_list_data"){ $room_search=$_GET['room_search']; $coures_id_list_val=$_GET['coures_id_list_val']; $length_list_val=$_GET['length_list_val']; echo $class_data->get_week_list_data($coures_id_list_val,$length_list_val,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_week_list"){ $length_list_val=$_GET['length_list_val']; echo $class_data->get_week_list($length_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_detail"){ $coures_id_list=$_GET['coures_id_list']; $room_search=$_GET['room_search']; echo $class_data->search_course_detail($coures_id_list,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_class_level"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_class_level($coures_id_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list"){ echo $class_data->get_coures_id_list(); }<file_sep>/modules/report/pdf_form.php <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/custom.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); $class_data->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$data_id "; $class_data->select(); $class_data->setRows(); $courseID=$class_data->rows[0]['courseID']; $name=$class_data->rows[0]['name']; $class_level=$class_data->rows[0]['class_level']; //$class_level_new=$class_data->get_class_level_new($class_level); if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_level_remove=str_replace('p','',$class_level); }else{ $class_level_remove=str_replace('m','',$class_level); } $get_grade_summary=$class_data->get_grade_summary($data_id,$room_search,$status); if($status==1/* || $page=='all_page'*/){ $attend=$class_data->get_attend($data_id,$status,$room_search); $objective_list=$class_data->get_objective_list($data_id,$room_search); $std_desirable=$class_data->get_std_desirable($data_id,$room_search); } if ($status==2) { $attend=$class_data->get_attend($data_id,$status,$room_search); $std_desirable=$class_data->get_std_desirable($data_id,$room_search); $dev_summary=$class_data->get_dev_summary($data_id); $num_all_std_dev=$dev_summary['num_all_std']; $data_atte_pass=$dev_summary['data_atte_pass']; $data_atte_nopass=$dev_summary['data_atte_nopass']; $summary_atte_pass_per=round(($data_atte_pass*100)/$num_all_std_dev,2); $summary_atte_nopass_per=round(($data_atte_nopass*100)/$num_all_std_dev,2); } $num_all_std=$get_grade_summary['num_all_std']; $data_i=$get_grade_summary['data_i']; $data_atte=$get_grade_summary['data_atte']; $data_00=$get_grade_summary['data_00']; $data_10=$get_grade_summary['data_10']; $data_15=$get_grade_summary['data_15']; $data_20=$get_grade_summary['data_20']; $data_25=$get_grade_summary['data_25']; $data_30=$get_grade_summary['data_30']; $data_35=$get_grade_summary['data_35']; $data_40=$get_grade_summary['data_40']; $data_i=$get_grade_summary['data_i']; $data_atte=$get_grade_summary['data_atte']; $get_per_00=round(($data_00*100)/$num_all_std,2); $get_per_10=round(($data_10*100)/$num_all_std,2); $get_per_15=round(($data_15*100)/$num_all_std,2); $get_per_20=round(($data_20*100)/$num_all_std,2); $get_per_25=round(($data_25*100)/$num_all_std,2); $get_per_30=round(($data_30*100)/$num_all_std,2); $get_per_35=round(($data_35*100)/$num_all_std,2); $get_per_40=round(($data_40*100)/$num_all_std,2); $get_per_i=round(($data_i*100)/$num_all_std,2); $get_per_atte=round(($data_atte*100)/$num_all_std,2); $data_desirable_nopass=$get_grade_summary['data_desirable_nopass']; $data_desirable_pass=$get_grade_summary['data_desirable_pass']; $data_desirable_good=$get_grade_summary['data_desirable_good']; $data_desirable_verygood=$get_grade_summary['data_desirable_verygood']; $get_per_desirable_nopass=round(($data_desirable_nopass*100)/$num_all_std,2); $get_per_desirable_pass=round(($data_desirable_pass*100)/$num_all_std,2); $get_per_desirable_good=round(($data_desirable_good*100)/$num_all_std,2); $get_per_desirable_verygood=round(($data_desirable_verygood*100)/$num_all_std,2); $data_read_think_write_nopass=$get_grade_summary['data_read_think_write_nopass']; $data_read_think_write_pass=$get_grade_summary['data_read_think_write_pass']; $data_read_think_write_good=$get_grade_summary['data_read_think_write_good']; $data_read_think_write_verygood=$get_grade_summary['data_read_think_write_verygood']; $get_per_read_think_write_nopass=round(($data_read_think_write_nopass*100)/$num_all_std,2); $get_per_read_think_write_pass=round(($data_read_think_write_pass*100)/$num_all_std,2); $get_per_read_think_write_good=round(($data_read_think_write_good*100)/$num_all_std,2); $get_per_read_think_write_verygood=round(($data_read_think_write_verygood*100)/$num_all_std,2); ?> <page> <img style="margin-left: 300px;" class="logo-print-size" src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 24px;margin-top: -5px;"> <p class="text-bold " style="margin-top: -8px;">แบบบันทึกผลการพัฒนาคุณภาพผู้เรียน (ปพ.5)</p> <p class="text-bold " style="margin-top: -8px;">โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อำเภอเมือง จังหวัดร้อยเอ็ด</p> <p style="margin-top: -8px;">รหัสวิชา <span class="text-bold"><?php echo $courseID; ?></span> รายวิชา <span class="text-bold"><?php echo $name; ?></span></p> <?php if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' || $status==2) { ?> <?php if ($status==2) { ?> <p style="margin-top: -8px;">ระดับชั้นประถมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove; ?></span> ปีการศึกษา <span class="text-bold">2560</span> </p> <?php }else{ ?> <p style="margin-top: -8px;">ระดับชั้นประถมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove.'/'.$room_search; ?></span> ปีการศึกษา <span class="text-bold">2560</span> </p> <?php } ?> <?php }else{ ?> <p style="margin-top: -8px;">ระดับชั้นมัธยมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove.'/'.$room_search; ?></span> ภาคเรียนที่ <span class="text-bold">1</span> ปีการศึกษา <span class="text-bold">2560</span> </p> <?php } ?> </div> <br> <?php if($status==1){ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="10" style="width: 60%;padding: 5px;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style=" vertical-align: middle;width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="10" style="padding: 5px;border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td style="width: 7%;"><?php echo $num_all_std.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 7%;">4.0</td> <td style="width: 7%;">3.5</td> <td style="width: 7%;">3.0</td> <td style="width: 7%;">2.5</td> <td style="width: 7%;">2.0</td> <td style="width: 7%;">1.5</td> <td style="width: 7%;">1.0</td> <td style="width: 7%;">0</td> <td style="width: 7%;">ร</td> <td style="width: 7%;">มส</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_40; ?></td> <td><?php echo $data_35; ?></td> <td><?php echo $data_30; ?></td> <td><?php echo $data_25; ?></td> <td><?php echo $data_20; ?></td> <td><?php echo $data_15; ?></td> <td><?php echo $data_10; ?></td> <td><?php echo $data_00; ?></td> <td><?php echo $data_i; ?></td> <td><?php echo $data_atte; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_40; ?></td> <td><?php echo $get_per_35; ?></td> <td><?php echo $get_per_30; ?></td> <td><?php echo $get_per_25; ?></td> <td><?php echo $get_per_20; ?></td> <td><?php echo $get_per_15; ?></td> <td><?php echo $get_per_10; ?></td> <td><?php echo $get_per_00; ?></td> <td><?php echo $get_per_i; ?></td> <td><?php echo $get_per_atte; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ เขียน</td> <td style=" vertical-align: middle;width: 14%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <?php }else{ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead> <tr> <td rowspan="2" style="width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="2" style="width: 70%;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style="width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="2" style="border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td><?php echo $num_all_std_dev.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 13.8px;">ผ่าน</td> <td>ไม่ผ่าน</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_atte_pass; ?></td> <td><?php echo $data_atte_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $summary_atte_pass_per; ?></td> <td><?php echo $summary_atte_nopass_per; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ เขียน</td> <td style=" vertical-align: middle;width: 14%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <?php } ?> <div style="margin-left: 100px;margin-top: 60px;"> <p>.................................................................ครูผู้สอน </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 410px;margin-top: -64px;"> <p>.................................................................หัวหน้างานวัดผล </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 100px;margin-top: 60px;"> <p>.................................................................หัวหน้ากลุ่มสาระ</p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 410px;margin-top: -64px;"> <p>.................................................................ครูประจำชั้น </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 440px;margin-top: 40px;"> <p>( ) อนุมัติ</p> <p style="margin-top: -25px;margin-left: 60px;">( ) ไม่อนุมัติ</p> </div> <div style="margin-left: 100px;margin-top: 40px;"> <p>.................................................................รองผู้อำนวยการ</p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 410px;margin-top: -64px;"> <p>..................................................................ผู้อำนวยการ</p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> </page> <?php if($page=='all_page'){ ?> <page orientation="<?php if($attend['set_page']=='land'){echo "landscape";}else{echo "portrait";}?>"> <p style="font-size:22px ;margin-left: 30px;margin-top: 10px;">บันทึกเวลาเข้าเรียน</p> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <?php if($attend['set_page']=='port'){ ?> <tr class="text-middle"> <td rowspan="3" style="width: 10%;vertical-align: middle;">เลขที่</td> <td rowspan="3" style="width: 22%;vertical-align: middle;">ชื่อ-สกุล</td> <td colspan="20" style="width: 60%;padding: 5px;"><?php echo $attend['num_day']; ?> ชั่วโมง/สัปดาห์</td> <td rowspan="3" style="width: 5%;">รวม&nbsp;<?php echo $attend['total_hr'];?>&nbsp;ชั่วโมง</td> <td rowspan="3" style="width: 5%;">ร้อยละ</td> </tr> <tr> <td colspan="20" style="width: 60%;padding: 5px;border-left:none;">สัปดาห์ที่</td> </tr> <tr> <td style="border-left: none;width: 3%;">1</td> <td style="width: 3%;">2</td> <td style="width: 3%;">3</td> <td style="width: 3%;">4</td> <td style="width: 3%;">5</td> <td style="width: 3%;">6</td> <td style="width: 3%;">7</td> <td style="width: 3%;">8</td> <td style="width: 3%;">9</td> <td style="width: 3%;">10</td> <td style="width: 3%;">11</td> <td style="width: 3%;">12</td> <td style="width: 3%;">13</td> <td style="width: 3%;">14</td> <td style="width: 3%;">15</td> <td style="width: 3%;">16</td> <td style="width: 3%;">17</td> <td style="width: 3%;">18</td> <td style="width: 3%;">19</td> <td style="width: 3%;">20</td> </tr> <?php }else{ ?> <tr class="text-middle"> <td rowspan="3" style="width: 4%;vertical-align: middle;">เลขที่</td> <td rowspan="3" style="width: 14%;vertical-align: middle;">ชื่อ-สกุล</td> <td colspan="40" style="width: 76%;padding: 5px;"><?php echo $attend['num_day']; ?> ชั่วโมง/สัปดาห์</td> <td rowspan="3" style="width: 3%;"><div style="rotate:90;">รวม&nbsp;<?php echo $attend['total_hr'];?>&nbsp;ชั่วโมง</div></td> <td rowspan="3" style="width: 3%;"><div style="rotate:90;">ร้อยละ</div></td> </tr> <tr> <td colspan="40" style="width: 60%;padding: 5px;border-left:none;">สัปดาห์ที่</td> </tr> <tr> <td style="border-left: none;width: 3%;">1</td> <td style="width: 2%;">2</td> <td style="width: 2%;">3</td> <td style="width: 2%;">4</td> <td style="width: 2%;">5</td> <td style="width: 2%;">6</td> <td style="width: 2%;">7</td> <td style="width: 2%;">8</td> <td style="width: 2%;">9</td> <td style="width: 2%;">10</td> <td style="width: 2%;">11</td> <td style="width: 2%;">12</td> <td style="width: 2%;">13</td> <td style="width: 2%;">14</td> <td style="width: 2%;">15</td> <td style="width: 2%;">16</td> <td style="width: 2%;">17</td> <td style="width: 2%;">18</td> <td style="width: 2%;">19</td> <td style="width: 2%;">20</td> <td style="width: 2%;">21</td> <td style="width: 2%;">22</td> <td style="width: 2%;">23</td> <td style="width: 2%;">24</td> <td style="width: 2%;">25</td> <td style="width: 2%;">26</td> <td style="width: 2%;">27</td> <td style="width: 2%;">28</td> <td style="width: 2%;">29</td> <td style="width: 2%;">30</td> <td style="width: 2%;">31</td> <td style="width: 2%;">32</td> <td style="width: 2%;">33</td> <td style="width: 2%;">34</td> <td style="width: 2%;">35</td> <td style="width: 2%;">36</td> <td style="width: 2%;">37</td> <td style="width: 2%;">38</td> <td style="width: 2%;">39</td> <td style="width: 2%;">40</td> </tr> <?php } ?> <!--<tr> <?php echo $attend['num_day']; ?> </tr>--> </thead> <tbody > <?php echo $attend['detail_std']; ?> </tbody> </table> <!-- <table style="width: 80%;margin-left: 50px;margin-top: 20px;" > <tr> <td style="border: none;">หมายเหตุ :</td> <td style="border: none;">1</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">มา</td> <td style="border: none;">มีค่าเท่ากับ</td> <td style="border: none;">1</td> <td style="width: 16%;border: none;">คะแนน</td> <td style="border: none;">แปรผล</td> <td style="border: none;">ร</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">รอแก้ผลการเรียน</td> </tr> <tr> <td style="border: none;" rowspan="6"></td> </tr> <tr> <td style="border: none;">ล</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ลากิจ</td> <td style="border: none;">มีค่าเท่ากับ</td> <td style="border: none;">0</td> <td style="border: none;">คะแนน</td> <td style="border: none;"></td> <td style="border: none;">มส</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ไม่มีสิทธิ์สอบ</td> </tr> <tr> <td style="border: none;">ป</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ลาป่วย</td> <td style="border: none;">มีค่าเท่ากับ</td> <td style="border: none;">0</td> <td style="border: none;">คะแนน</td> </tr> <tr> <td style="border: none;">ข</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ขาด</td> <td style="border: none;">มีค่าเท่ากับ</td> <td style="border: none;">0</td> <td style="border: none;">คะแนน</td> </tr> <tr> <td style="border: none;">น</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">หนีเรียน</td> <td style="border: none;">มีค่าเท่ากับ</td> <td style="border: none;">0</td> <td style="border: none;">คะแนน</td> </tr> </table>--> </page> <page orientation="portrait"> <?php if($status==1){ ?> <p style="font-size:22px ;margin-left: 30px;margin-top: 10px;">การประเมินผลการเรียน</p> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="3" style="vertical-align: middle;width: 5%;">เลขที่</td> <td rowspan="3" style="vertical-align: middle;width: 20%;">ชื่อ-สกุล</td> <td colspan="<?php echo $objective_list['chk_loop']-1; ?>" style="width: 50%">ตัวชี้วัดข้อที่</td> <td rowspan="2" style="width: 7%;">สอบ<br>กลางภาค</td> <td rowspan="2" style="width: 7%;">สอบ<br>ปลายภาค</td> <td rowspan="2" style="width: 7%;">คะแนน<br>รวม</td> <td rowspan="2" style="width: 5%;">GPA</td> </tr> <tr> <?php echo $objective_list['ob_title_table_col']; ?> </tr> <tr> <?php echo $objective_list['score_title_table_col']; ?> <td><?php echo $objective_list['mid_exam']; ?></td> <td><?php echo $objective_list['final_exam']; ?></td> <td><?php echo $objective_list['sum_score_main']+$objective_list['mid_exam']+$objective_list['final_exam']; ?></td> <td>4.0</td> </tr> </thead> <tbody > <?php echo $objective_list['detail_std']; ?> </tbody> </table> <p style="margin-left: 30px;margin-top: 20px;">ตัวชี้วัด</p> <table style="width: 80%;margin-left: 50px;margin-top: -10px;" > <?php echo $objective_list['objective_conclude_detail']; ?> </table> <?php }else{ ?> <p style="font-size:22px ;margin-left: 30px;margin-top: 10px;">สรุปผลการเรียน</p> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead> <tr> <td rowspan="2" style="width: 20%;">เลขที่</td> <td rowspan="2" style="width: 50%;">ชื่อ-สกุล</td> <td colspan="2" style="width: 30%;">สรุปผลการเรียน</td> </tr> <tr> <td style="border-left: none;">ผ่าน</td> <td>ไม่ผ่าน</td> </tr> </thead> <tbody> <?php echo $dev_summary['std_list']; ?> </tbody> </table> <?php } ?> </page> <page orientation="portrait"> <?php if($status==1){ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="10" style="width: 60%;padding: 5px;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style=" vertical-align: middle;width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="10" style="padding: 5px;border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td style="width: 7%;"><?php echo $num_all_std.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 7%;">4.0</td> <td style="width: 7%;">3.5</td> <td style="width: 7%;">3.0</td> <td style="width: 7%;">2.5</td> <td style="width: 7%;">2.0</td> <td style="width: 7%;">1.5</td> <td style="width: 7%;">1.0</td> <td style="width: 7%;">0</td> <td style="width: 7%;">ร</td> <td style="width: 7%;">มส</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_40; ?></td> <td><?php echo $data_35; ?></td> <td><?php echo $data_30; ?></td> <td><?php echo $data_25; ?></td> <td><?php echo $data_20; ?></td> <td><?php echo $data_15; ?></td> <td><?php echo $data_10; ?></td> <td><?php echo $data_00; ?></td> <td><?php echo $data_i; ?></td> <td><?php echo $data_atte; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_40; ?></td> <td><?php echo $get_per_35; ?></td> <td><?php echo $get_per_30; ?></td> <td><?php echo $get_per_25; ?></td> <td><?php echo $get_per_20; ?></td> <td><?php echo $get_per_15; ?></td> <td><?php echo $get_per_10; ?></td> <td><?php echo $get_per_00; ?></td> <td><?php echo $get_per_i; ?></td> <td><?php echo $get_per_atte; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ เขียน</td> <td style=" vertical-align: middle;width: 14%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <?php }else{ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead> <tr> <td rowspan="2" style="width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="2" style="width: 70%;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style="width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="2" style="border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td><?php echo $num_all_std_dev.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 13.8px;">ผ่าน</td> <td>ไม่ผ่าน</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_atte_pass; ?></td> <td><?php echo $data_atte_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $summary_atte_pass_per; ?></td> <td><?php echo $summary_atte_nopass_per; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ เขียน</td> <td style=" vertical-align: middle;width: 14%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <?php } ?> <div style="margin-left: 30px;margin-top: 20px;"> <p>เกณฑ์ระดับคุณภาพ</p> <p style="margin-left: 12px;margin-top: 10px;">ระดับผลการเรียน</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 4</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 3.5</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 3</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 2.5</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 2</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 1.5</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 1</p> <p style="margin-left: 12px;margin-top: -5px;">ระดับ 0</p> </div> <div style="margin-left: 160px;margin-top: -180px;"> <p style="margin-left: 12px;margin-top: 10px;">ความหมาย</p> <p style="margin-left: 12px;margin-top: -5px;">ดีเยี่ยม</p> <p style="margin-left: 12px;margin-top: -5px;">ดีมาก</p> <p style="margin-left: 12px;margin-top: -5px;">ดี</p> <p style="margin-left: 12px;margin-top: -5px;">ค่อนข้างดี</p> <p style="margin-left: 12px;margin-top: -5px;">ปานกลาง</p> <p style="margin-left: 12px;margin-top: -5px;">พอใช้</p> <p style="margin-left: 12px;margin-top: -5px;">ผ่านเกณฑ์ขั้นต่ำ</p> <p style="margin-left: 12px;margin-top: -5px;">ต่ำกว่าเกณฑ์</p> </div> <div style="margin-left:290px;margin-top: -180px;"> <p style="margin-left: 12px;margin-top: 10px;">ช่วงคะแนน</p> <p style="margin-left: 12px;margin-top: -5px;">80-100</p> <p style="margin-left: 12px;margin-top: -5px;">75-79</p> <p style="margin-left: 12px;margin-top: -5px;">70-74</p> <p style="margin-left: 12px;margin-top: -5px;">65-69</p> <p style="margin-left: 12px;margin-top: -5px;">60-64</p> <p style="margin-left: 12px;margin-top: -5px;">55-59</p> <p style="margin-left: 12px;margin-top: -5px;">50-54</p> <p style="margin-left: 12px;margin-top: -5px;">0-49</p> </div> </page> <page orientation="portrait"> <p style="font-size:22px ;margin-left: 30px;margin-top: 10px;">การประเมินคุณลักษณะอันพึงประสงค์และการอ่าน เขียน คิดวิเคราะห์</p> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 11pt;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 6%;">เลขที่</td> <td rowspan="2" style=" vertical-align: middle;width: 20%;">ชื่อ-สกุล</td> <td colspan="10" style="width: 18%;padding: 5px;">คุณลักษณะอันพึงประสงค์</td> <td colspan="7" style="vertical-align: middle;width: 22%;">การอ่าน เขียน คิดวิเคราะห์</td> </tr> <tr> <td style="width: 4%;border-left: none;height: 60px;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;1</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;2</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;3</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;4</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;5</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;6</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;7</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">ข้อที่&nbsp;&nbsp;8</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">คะแนนรวม</div></td> <td style="width: 4%;"><div style="rotate: 90;margin-top: 10px;">คะแนนเฉลี่ย</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;1</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;2</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;3</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;4</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;5</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">คะแนนรวม</div></td> <td style="width: 5%;"><div style="rotate: 90;margin-top: 10px;">คะแนนเฉลี่ย</div></td> </tr> </thead> <tbody> <?php echo $std_desirable; ?> </tbody> </table> <table style="width: 80%;margin-left: 50px;margin-top: 20px;" > <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;">ตัวชี้วัดคุณลักษณะอันพึงประสงค์</p> <p style="line-height: 0.9">1.รักชาติ ศาสน์ กษัตริย์</p> <p style="line-height: 0.9">2.ซื่อสัตย์สุจริต</p> <p style="line-height: 0.9">3.มีวินัย</p> <p style="line-height: 0.9">4.ใฝ่เรียนรู้</p> <p style="line-height: 0.9">5.อยู่อย่างพอเพียง</p> <p style="line-height: 0.9">6.มุ่งมั่นในการทำงาน</p> <p style="line-height: 0.9">7.รักความเป็นไทย</p> <p style="line-height: 0.9">8.มีจิตสาธารณะ</p> </td> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;margin-top: -89px;">เกณฑ์ระดับคุณภาพ</p> <p style="line-height: 0.9">3 ดีเยี่ยม คะแนน 2.5-3.0</p> <p style="line-height: 0.9">2 ดี คะแนน 1.5-2.4</p> <p style="line-height: 0.9">1 ผ่าน คะแนน 0.5-1.4</p> <p style="line-height: 0.9">0 ไม่ผ่าน คะแนน 0-0.4</p> </td> </tr> </table> </page> <?php } ?><file_sep>/modules/regis_teacher/upload_one.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $file_path="../../file_managers/exel/"; //$user_id=$_SESSION['ss_user_id']; /*$ext=pathinfo(basename($_FILES['file']['name']),PATHINFO_EXTENSION); $new_file='file_'.uniqid().".".$ext; $up_path=$file_path.$new_file; $oldFileName=$_FILES['file']['name']; $upload=move_uploaded_file($_FILES['file']['tmp_name'], $up_path);*/ $file = $_FILES['file']['tmp_name']; $handle = fopen($file, "r"); fgetcsv($handle); $c = 0; while(($filesop = fgetcsv($handle, 1000, ",")) !== false){ $positionID = trim($filesop[0]); $fname_th = trim($filesop[1]); $lname_th = trim($filesop[2]); $fname_en = trim($filesop[3]); $lname_en = trim($filesop[4]); $lname_en_pass = substr($lname_en, 0, 1); $username=$fname_en.'.'.$lname_en_pass; $birthday_set = trim($filesop[5]); list($day,$month,$year_set) = split('[/]', $birthday_set); $password_set=$day.$month.$year_set; $password=MD5($password_set); $year=$year_set-543; $birth_val=$year.'-'.$month.'-'.$day; $class_data->sql = "INSERT INTO tbl_regis_teacher(positionID,username,password,fname_th,lname_th,fname_en,lname_en,birthday,status) VALUES ('$positionID','$username','$password','$fname_th','$lname_th','$fname_en','$lname_en','$birth_val',1)"; $class_data->query(); $data_res.=' <tr> <td style="text-align:center;">'.$positionID.'</td> <td style="text-align:center;">'.$username.'</td> <td style="text-align:center;">'.$password_set.'</td> <td style="text-align:center;">'.$fname_th.'</td> <td style="text-align:center;">'.$lname_th.'</td> <td style="text-align:center;">'.$birthday_set.'</td> </tr> '; $c = $c + 1; } echo $data_res; ?><file_sep>/modules/authen_user/class_modules.php <?php class ClassData extends Databases { var $role; var $role_id; public function __construct() { $this->role = new ClassRole(); $this->role_id = (int)$_SESSION['ss_user_id']; // You don't have permission to access } /*************************************** PROCESS DB ****************************************/ public function get_data_list($arr_search_val,$pages_current,$sort_column,$sort_by){ $edit_user_ath = $this->role->ath_user_reletion_tasks('edit_user_ath',$this->role_id); // สามารถแก้ไขหมวดหมู่สินค้าได้ ## SQL CONDITION ## $sql_condition = " atu.user_id > 0 "; $data_name = $arr_search_val['data_name']; $data_status = $arr_search_val['data_status']; if (isset($data_name)) { $sql_condition .= " AND ( atu.first_name LIKE '%{$data_name}%' OR atu.first_name LIKE '%{$data_name}%' OR atu.last_name LIKE '%{$data_name}%' ) "; } if (isset($data_status)) { $sql_condition .= " AND ( atu.status LIKE '%{$data_status}%' ) "; } ## SQL CONDITION ## ## PAGINATION ## $this->sql = " SELECT count(user_id) as data_id_total FROM ath_users as atu WHERE {$sql_condition} "; $this->select(); $this->setRows(); $dataidtotal = (int)$this->rows[0]['data_id_total']; $pagination = new pagination(); $pages = (int)$pages_current; $rowsperpage = 20; $arrpage = $pagination->calculate_pages($dataidtotal, $rowsperpage, $pages); $sequence = ($arrpage['current'] == 1) ? 1 : ($arrpage['current'] * $rowsperpage)-1 ; ## PAGINATION ## ## DATA TBLE ## $data_response = array(); $data_response['data_list'] = ""; if($dataidtotal > 0){ $arr_status = array('Save Draft','Published'); $sql_order_by = " {$sort_column} {$sort_by} "; $sql = "SELECT atu.* , rol.role_name FROM ath_users as atu LEFT JOIN ath_roles as rol ON atu.role_id = rol.role_id WHERE {$sql_condition} ORDER BY {$sql_order_by} {$arrpage['limit']} "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $user_id = $this->rows[$key]['user_id']; $prefix_name = $this->rows[$key]['prefix_name']; $first_name = $this->rows[$key]['first_name']; $last_name = $this->rows[$key]['last_name']; $role_name = $this->rows[$key]['role_name']; $status = $this->rows[$key]['status']; $edit_hyperlink = ($edit_user_ath) ? "index.php?op=authen_user-from&id={$user_id}" : 'index.php?op=messages-error403'; $data_response['data_list'] .= "<tr> <td class=\"v-align-middle\"> <div class=\"checkbox check-success\"> <input type=\"checkbox\" value=\"{$user_id}\" name=\"checkbox_delete[]\" id=\"checkbox{$user_id}\" class=\"checkbox_data\"> <label for=\"checkbox{$user_id}\">&nbsp;</label> </div> </td> <td class=\"v-align-middle semi-bold\"><a href=\"{$edit_hyperlink}\">{$prefix_name} {$first_name} {$last_name}</a> </td> <td class=\"v-align-middle semi-bold\"><a href=\"{$edit_hyperlink}\">{$role_name}</a> </td> <td class=\"v-align-middle\">{$arr_status[$status]}</td> </tr>"; $data_response['data_list'] .= "<a class=\"btn btn-inverse btn_edit \" data-id=\"{$user_id}\" href=\"javascript:;\"><i class=\"fa fa-edit\"></i></a>" ; $data_response['data_list'] .= "<a class=\"btn btn-danger bt_delete\" data-id=\"{$user_id}\" href=\"javascript:;\"><i class=\"fa fa-trash-o\"></i></a>"; $data_response['data_list'] .= "</td></tr>"; $sequence++; }} ## DATA TBLE ## $data_response['data_pagination'] .= "<li><a href=\"javascript:;\" data-id=\"{$arrpage['previous']}\" class=\"chg_pagination\">&laquo;</a></li>"; for($p=0; $p<count($arrpage['pages']); $p++){ $activepages = ($arrpage['pages'][$p]==$arrpage['current']) ? "active" : ""; $data_response['data_pagination'] .= "<li class=\"{$activepages}\"><a href=\"javascript:;\" data-id=\"{$arrpage['pages'][$p]}\" class=\"chg_pagination\">{$arrpage['pages'][$p]}</a></li>"; } $data_response['data_pagination'] .= " <li><a href=\"javascript:;\" data-id=\"{$arrpage['next']}\" class=\"chg_pagination\">&raquo;</a></li>"; return json_encode($data_response); // return $data_response; } public function get_data_from($user_id){ $data_response = array(); $this->sql = "SELECT * FROM ath_users WHERE user_id={$user_id} " ; $this->select(); $this->setRows(); $data_response['role_id'] = $this->rows[0]['role_id']; $data_response['username'] = $this->rows[0]['username']; $data_response['first_name'] = $this->rows[0]['first_name']; $data_response['last_name'] = $this->rows[0]['last_name']; $data_response['status'] = $this->rows[0]['status']; return json_encode($data_response); } public function get_data($user_id){ $this->sql = "SELECT * FROM ath_users WHERE user_id={$user_id} " ; $this->select(); return $this->getRows(); } public function get_data_uniquevalue($field_name,$sql_where){ $this->sql = "SELECT {$field_name} FROM ath_users WHERE {$sql_where} " ; $this->select(); $this->setRows(); return trim($this->rows[0][$field_name]); } public function insert_data($insert){ $this->sql = "INSERT INTO ath_users(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $new_id = $this->insertID(); $this->sql = "UPDATE tbl_users_gallery SET usersID = $new_id , status = $new_id WHERE usersID = 0 AND status = 0 "; $this->query(); return $new_id; } public function update_data($update,$user_id){ $this->sql = "UPDATE ath_users SET ".implode(",",$update)." WHERE user_id='".$user_id."'"; $this->query(); } public function get_data_delete($data_val){ $arr_id = explode(",", $data_val); for ($i=0; $i < count($arr_id) ; $i++) { $targetfile = "../../../file_managers/userprofile/"; $this->sql = " SELECT FileName FROM tbl_users_gallery WHERE usersID = {$arr_id[$i]}"; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $FileName = $this->rows[$key]['FileName']; if(@file_exists($targetfile."thumbnails/{$FileName}")){ @unlink($targetfile."thumbnails/{$FileName}"); } if(@file_exists($targetfile."photo/{$FileName}")){ @unlink($targetfile."photo/{$FileName}"); } } $this->sql ="DELETE FROM tbl_users_gallery WHERE usersID = {$arr_id[$i]}"; $this->query(); $this->sql ="DELETE FROM ath_users WHERE user_id={$arr_id[$i]}"; $this->query(); } } public function fetchRole() { $this->sql = " SELECT count(role_id) as data_id_total FROM ath_roles WHERE status = 1 ORDER BY role_id DESC "; $this->select(); $this->setRows(); $num_options = (int)$this->rows[0]['data_id_total']; if ($num_options > 0) { $this->sql = "SELECT role_id,role_name FROM ath_roles WHERE status = 1 ORDER BY role_id DESC"; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $options .="<option value=\"{$value['role_id']}\">{$value['role_name']}</option>\n"; } } return $options; } public function update_ath_tasks($ath_tasks,$user_id){ /// DELETE OLD VALUE $this->sql = "DELETE FROM ath_user_reletion_tasks WHERE task_id NOT IN ({$ath_tasks}) AND user_id='".$user_id."'"; $this->query(); // TASKS MANAGEMENT ////////////// $arr_ath_tasks = explode(',', $ath_tasks); for ($i=0; $i < count($arr_ath_tasks); $i++) { $task_id = $arr_ath_tasks[$i]; if (self::num_user_reletion_tasks($task_id,$user_id) == 0) { $insert = array(); $insert["task_id"]= "'".trim($task_id)."'"; $insert["user_id"]= "'".trim($user_id)."'"; $this->sql = "INSERT INTO ath_user_reletion_tasks(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); } } } public function get_tasks_list($user_id,$data_id){ $sql = "SELECT * FROM ath_main_function WHERE status = 1 ORDER BY sequence DESC, fun_id ASC "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $fun_id = $value['fun_id']; $fun_name = $value['fun_name']; $tasks_list .= '<div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="collapsed" data-parent="#accordion" data-toggle="collapse" href="#collapse'.$fun_id.'">'.$fun_name.'</a> </h4> </div> <div class="panel-collapse collapse in" id="collapse'.$fun_id.'"> <div class="panel-body">'; $sql = "SELECT * FROM ath_tasks WHERE fun_id = {$fun_id} AND status=1 ORDER BY sequence DESC, fun_id ASC "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $task_key => $task_val) { $task_id = $task_val['task_id']; $task_description = $task_val['task_description']; $num_task_id = (int)self::num_user_reletion_tasks($task_id,$data_id); $checked_val = ($num_task_id == 0 ) ? "" : "checked"; $tasks_list .= '<div class="checkbox check-info"> <input type="checkbox" class="checkbox_data ath_fun_'.$fun_id.'" value="'.$task_id.'" id="ath_tasks_'.$task_id.'" name="checkbox_ath_tasks[]" '.$checked_val.' > <label for="ath_tasks_'.$task_id.'">'.$task_description.'</label> </div>'; } $tasks_list .= '</div> </div> </div>'; } $data_response['tasks_list'] = $tasks_list; return json_encode($data_response); } public function num_user_reletion_tasks($task_id,$user_id){ $this->sql = " SELECT count(rel_id) as data_id_total FROM ath_user_reletion_tasks WHERE task_id={$task_id} AND user_id={$user_id} "; $this->select(); $this->setRows(); return (int)$this->rows[0]['data_id_total']; } public function get_role_reletion_tasks($role_id){ //ath_role_reletion_tasks $data_response = array(); $sql = "SELECT task_id FROM ath_role_reletion_tasks WHERE role_id = {$role_id} "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $task_key => $task_val) { $data_response['task_id'][] = $task_val['task_id']; } return json_encode($data_response); } public function ex_add_thumb($insert){ $this->sql = "INSERT INTO tbl_users_gallery(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $photo_id = $this->insertID(); $this->sql = "UPDATE tbl_users_gallery SET sequence=$photo_id WHERE DataID='".$photo_id."'"; $this->query(); return $photo_id; } public function get_thumb($data_id){ $sql_condition = "WHERE usersID = {$data_id} AND Type = 0 "; $sql_order_by = "sequence ASC "; $sql = "SELECT DataID,FileName FROM tbl_users_gallery {$sql_condition} "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID = $value['DataID']; $FileName = $value['FileName'];//unchkhtmlspecialchars $file_name = (@file_exists("../../../file_managers/userprofile/thumbnails/{$FileName}")) ? $FileName : "thumbnail.jpg"; $data_response .= " <center> <div class=\"col-lg-12 col-md-10\"> <p class=\"small no-margin\"><img src=\"../file_managers/userprofile/thumbnails/{$FileName}?".time()."\" style=\"width:auto;\" class=\"img-rounded m-r-25 m-b-10\"></p> <div class=\"btn-group btn-group-xs text-center\"> <a href=\"javascript:;\" data-id=\"{$DataID}\" class=\" btn btn-danger btn_remove_thumb\">Remove</a> </div> <hr/> </div> </center>"; $sequence++; } return $data_response; } public function remove_thumb($data_id){ $targetfile = "../../../file_managers/userprofile/"; $this->sql = " SELECT FileName FROM tbl_users_gallery WHERE DataID = {$data_id} LIMIT 0,1 "; $this->select(); $this->setRows(); $FileName = $this->rows[0]['FileName']; if(@file_exists($targetfile."thumbnails/{$FileName}")){ @unlink($targetfile."thumbnails/{$FileName}"); } $this->sql ="DELETE FROM tbl_users_gallery WHERE DataID={$data_id} "; $this->query(); return "y"; } /*************************************** PROCESS DB ****************************************/ } ?><file_sep>/modules/report/person_p_form.php <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/custom.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); ?> <page orientation="portrait"> <p class="text-bold" style="margin-left: 710px;font-size: 22px;margin-top: 25px;">ปพ.6</p> <img style="margin :10px 0px 10px 320px;display:block;width: 120px;height: 120px;"src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 22px;margin-top: -5px;"> <p class="text-bold" style="margin-top: -8px;">รายงานการพัฒนาคุณภาพผู้เรียนเป็นรายบุคคล</p> <p class="text-bold " style="margin-top: -8px;">โรงเรียนเทศบาลวัดสระทอง</p> </div> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 22px;margin-left:10px;border: 1px solid black;margin-top: 20px;"> <thead> <tr> <td style="border: none;"><span class="text-bold">ชื่อ - สกุล</span> เด็กชายสมหมาย สุขสบาย</td> <td style="border: none;"><span class="text-bold">ประถมศึกษาปีที่</span> 1/1</td> <td style="border: none;"><span class="text-bold">เลขที่</span> 1</td> <td style="border: none;"><span class="text-bold">เลขประจำตัวนักเรียน</span> 00010</td> </tr> </thead> <tr> <td style="padding-left: 35px;border: none;"><span class="text-bold">เลขประจำตัวประชาชน</span> 1234567890123</td> <td style="border: none;"><span class="text-bold">ภาคเรียนที่</span> 1</td> <td style="border: none;"><span class="text-bold">ปีการศึกษา</span> 2560</td> </tr> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 35px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td rowspan="4" style="width: 4%;height: 65px;">ที่</td> <td colspan="7" style="width: 40%;">การพัฒนาคุณภาพผู้เรียน</td> <td rowspan="4" style="width: 8%;"><div style="rotate:90;margin-left: -12px;">หมายเหตุ</div></td> </tr> <tr style="background-color: #e0e0e0;"> <td rowspan="3" style="border-left:none; width: 25%;">รายวิชา</td> <td rowspan="3" style="width:13%;">รหัสวิชา</td> <td rowspan="3" style="width:8%;">น้ำหนัก</td> <td colspan="3">คะแนน</td> <td rowspan="3" style="width: 7%;">GPA</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="border-left:none;width: 10%; ">ภาคเรียนที่1</td> <td style="width: 10%;">ภาคเรียนที่2</td> <td style="width: 10%;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="border-left:none; ">50</td> <td>50</td> <td>100</td> </tr> </thead> <tbody> <tr> <td>1</td> <td>ภาษาไทย</td> <td>ท11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>2</td> <td>คณิตศาสตร์</td> <td>ค11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>3</td> <td>วิทยาศาสตร์</td> <td>ว11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>4</td> <td>วิทยาศาสตร์เพิ่มเติม</td> <td>ว11002</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>5</td> <td>สังคมศึกษา ศาสนาและวัฒนธรรม</td> <td>ส11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>6</td> <td>สุขศึกษา</td> <td>พ11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>7</td> <td>ภาษาอังกฤษ</td> <td>อ11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>8</td> <td>การงานอาชีพและเทคโนโลยี</td> <td>ง11001</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td>9</td> <td>คอมพิวเตอร์</td> <td>ง11010</td> <td>1</td> <td>30</td> <td>30</td> <td>60</td> <td>3.14</td> <td></td> </tr> <tr> <td colspan="3">รวม</td> <td>10</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr style="background-color: #e0e0e0;font-weight: bold;"> <td ></td> <td colspan="2">กิจกรรมพัฒนาผู้เรียน</td> <td colspan="2">รหัสวิชา</td> <td>น้ำหนัก</td> <td colspan="2">ผลการประเมิน</td> <td></td> </tr> <tr> <td>1</td> <td colspan="2">แนะแนว</td> <td colspan="2">ก11001</td> <td>-</td> <td colspan="2">ผ่าน</td> <td></td> </tr> <tr> <td>2</td> <td colspan="2">ลูกเสือ เนตรนารี</td> <td colspan="2">ก11002</td> <td>-</td> <td colspan="2">ผ่าน</td> <td></td> </tr> <tr> <td>3</td> <td colspan="2">ชุมนุมคอมพิวเตอร์</td> <td colspan="2">ก11003</td> <td>-</td> <td colspan="2">ผ่าน</td> <td></td> </tr> <tr> <td>4</td> <td colspan="2">กิจกรรมเพื่อสังคม</td> <td colspan="2">ก11004</td> <td>-</td> <td colspan="2">ผ่าน</td> <td></td> </tr> <tr style="font-weight: bold;"> <td colspan="5">รวม</td> <td></td> <td colspan="2">ผ่าน</td> <td></td> </tr> </tbody> </table> </page> <page orientation="portrait"> <p class="text-bold" style="margin-left: 710px;font-size: 22px;margin-top: 25px;">ปพ.6</p> <br> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 10px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td colspan="3" style="width: 4%;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 6%">ที่</td> <td style="width: 65%;">คุณลักษณะอันพึงประสงค์</td> <td style="width: 24%;">ผลการประเมิน</td> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: left;">รักชาติ ศาสน์ กษัตริย์</td> <td>3</td> </tr> <tr> <td>2</td> <td style="text-align: left;">ซื่อสัตย์สุจริต</td> <td>3</td> </tr> <tr> <td>3</td> <td style="text-align: left;">มีวินัย</td> <td>3</td> </tr> <tr> <td>4</td> <td style="text-align: left;">ใฝ่เรียนรู้</td> <td>3</td> </tr> <tr> <td>5</td> <td style="text-align: left;">อยู่อย่างพอเพียง</td> <td>3</td> </tr> <tr> <td>6</td> <td style="text-align: left;">มุ่งมั่นในการทำงาน</td> <td>3</td> </tr> <tr> <td>7</td> <td style="text-align: left;">รักความเป็นไทย</td> <td>3</td> </tr> <tr> <td>8</td> <td style="text-align: left;">มีจิตสาธารณะ</td> <td>3</td> </tr> <tr style="font-weight: bold;"> <td colspan="2">สรุปผลการประเมิน</td> <td>3</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 35px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td colspan="3" style="width: 4%;">ผลการประเมินการอ่าน&nbsp;เขียน&nbsp;คิดวิเคราะห์</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 6%">ที่</td> <td style="width: 65%;">การอ่าน&nbsp;เขียน&nbsp;คิดวิเคราะห์</td> <td style="width: 24%;">ผลการประเมิน</td> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: left;">การอ่าน</td> <td>3</td> </tr> <tr> <td>2</td> <td style="text-align: left;">การเขียน</td> <td>3</td> </tr> <tr> <td>3</td> <td style="text-align: left;">การคิด วิเคราะห์</td> <td>3</td> </tr> <tr style="font-weight: bold;"> <td colspan="2">สรุปผลการประเมิน</td> <td>3</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 35px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td colspan="6" style="width: 4%;">สรุปผลการประเมิน</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 6%">ผลการเรียนเฉลี่ย</td> <td style="width: 6%">ผลการเรียนเฉลี่ย สะสม</td> <td style="width: 6%;">ลำดับที่<br>ในห้องเรียน</td> <td style="width: 6%;">กิจกรรมพัฒนา ผู้เรียน</td> <td style="width: 6%;">คุณลักษณะอันพึง ประสงค์</td> <td style="width: 6%;">อ่าน&nbsp;เขียน คิดวิเคราะห์</td> </tr> </thead> <tbody> <tr> <td style="width: 16%">4.00</td> <td style="width: 16%">4.00</td> <td style="width: 16%">1</td> <td style="width: 16%">ผ่าน</td> <td style="width: 16%">3</td> <td style="width: 16%">3</td> </tr> </tbody> </table> <div style="margin-left: 120px;margin-top: 40px;font-size: 16px;"> <p>.................................................................ครูประจำชั้น </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:160px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 420px;margin-top: -74px;font-size: 16px;"> <p>.................................................................ผู้ปกครอง </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:170px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 420px;margin-top: 55px;font-size: 16px;"> <p>.................................................................ผู้อำนวยการ</p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> </page> <file_sep>/index_local.php <?php /* * Web-Based Instruction PHP Programming :: ND Technology Co.,Ltd. (Thailand) * Web-Design :: ND Technology Co.,Ltd. (Thailand ) * Copyright (C) 2007-2015 * Contact :: <EMAIL> * This is the integration file for PHP (versions 5) */ @ob_start(); @session_start(); if( !$_SESSION['ss_user_id'] ){ header('location:login.php'); } require_once('init.php'); function cURLData($url, $data){ $postData = http_build_query($data); $ch = curl_init(); curl_setopt_array( $ch, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData, CURLOPT_FOLLOWLOCATION => true )); $response = curl_exec($ch); curl_close ($ch); //close curl handle return $response; } $template_dir = 'templates/'; $index_templat = file_get_contents(HOME_PATH.$template_dir.'index.html'); $index_templat = str_replace('{TITLE_PAGE}', TITLE_PAGE, $index_templat); //SLIDER_PAGE $inc_data = file_get_contents(HOME_PATH."includes/inc.slider_page.php"); $index_templat = str_replace("{SLIDER_PAGE}", $inc_data, $index_templat); //HEADER_PAGE $inc_data = file_get_contents(HOME_PATH."includes/inc.header.php"); $BACKOFFICE_ACCOUNT_NAME = "{$_SESSION['ss_prefix_name']} {$_SESSION['ss_first_name']} {$_SESSION['ss_last_name']}"; $inc_data = str_replace("{BACKOFFICE_ACCOUNT_NAME}", $BACKOFFICE_ACCOUNT_NAME, $inc_data); $index_templat = str_replace("{HEADER_PAGE}", $inc_data, $index_templat); //FOOTER_PAGE $inc_data = file_get_contents(HOME_PATH."includes/inc.footer_page.php"); $index_templat = str_replace("{FOOTER_PAGE}", $inc_data, $index_templat); //BODY_PAGE if(!empty($_GET['op'])){ $OPURL = trim($_GET['op']); $GETOP = explode("-",$OPURL); $OPEN_PAGE = "modules/".$GETOP[0]; $CONFIG_PAGE = "{$OPEN_PAGE}/{$GETOP[1]}.php"; $CONFIG_JS_PAGE = "{$OPEN_PAGE}/{$GETOP[1]}.js"; $CONFIG_CSS_PAGE = "{$OPEN_PAGE}/{$GETOP[1]}.css"; if (empty($GETOP[1]) || !file_exists($CONFIG_PAGE)) { header('location:index.php?op=messages-error404'); } }else{ $OPEN_PAGE = "modules/dashboard"; $CONFIG_PAGE = $OPEN_PAGE."/index.php"; $CONFIG_JS_PAGE = $OPEN_PAGE."/index.js"; $CONFIG_CSS_PAGE = $OPEN_PAGE."/index.css"; } $POSTDATA = array(); foreach ($_GET as $key => $value) { $POSTDATA[$key] = $value; } foreach ($_POST as $key => $value) { $POSTDATA[$key] = $value; } $inc_data = cURLData(BASE_URL.'9cabling/backoffice/'.$CONFIG_PAGE,$POSTDATA); $index_templat = str_replace("{BODY_PAGE}", $inc_data, $index_templat); //OTHER_JS_PAGE $CONFIG_JS_PAGE = (file_exists($CONFIG_JS_PAGE)) ? '<script src="'.$CONFIG_JS_PAGE.'" type="text/javascript"></script>' : ''; $CONFIG_CSS_PAGE = (file_exists($CONFIG_CSS_PAGE)) ? '<link href="'.$CONFIG_CSS_PAGE.'" rel="stylesheet" type="text/css" />' : ''; $index_templat = str_replace("{OTHER_CSS_PAGE}", $CONFIG_CSS_PAGE, $index_templat); $index_templat = str_replace("{OTHER_JS_PAGE}", $CONFIG_JS_PAGE, $index_templat); echo $index_templat; ?> <file_sep>/modules/maneger_student/edit.php <?php include('modules/maneger_student/class_modules.php'); $class_data = new ClassData(); $data_id=$_GET['id']; $extra_data=$class_data->get_extra_data($data_id); ?> <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="circle-bg-violet"> <img class="head-img-circle" src="assets/images/4.png"> </div> <div class="text-head-title"> <p>แก้ไขข้อมูลนักเรียน</p> </div> <div class="text-head-desc"> <p>ใช้สำหรับการแก้ไขข้อมูลนักเรียน โรงเรียนเทศบาลวัดสระทอง</p> </div> <div class="row pd-50 pt-80 stage-set" > <div class="col-sm-12"> <form id="frm_data"> <div class="bg-grey"> <div class="row"> <div class="col-sm-12"> <p class="text-title-in-grey text-violet ml-50 mb-20">ข้อมูลนักเรียน</p> </div> <div class="mb-15 col-sm-6"> <p class="text-bold text-search set-text-teacher-1" >รหัสนักเรียน</p> <div class="input-group form-add-teacher"> <input id="std_ID" name="std_ID" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-15 col-sm-6"> <p class="text-bold text-search set-text-teacher-2">รหัสประจำตัวประชาชน</p> <div class="input-group form-add-teacher"> <input id="card_ID" name="card_ID" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-10 col-sm-12"> <p class="text-bold text-search set-text-teacher-3" >ชั้น</p> <select disabled="disabled" id="class_level" name="class_level" class="form-control form-add-class-2"> <option id="calss_p1" value="p1">ป.1</option> <option id="calss_p2" value="p2">ป.2</option> <option id="calss_p3" value="p3">ป.3</option> <option id="calss_p4" value="p4">ป.4</option> <option id="calss_p5" value="p5">ป.5</option> <option id="calss_p6" value="p6">ป.6</option> <option id="calss_m1" value="m1">ม.1</option> <option id="calss_m2" value="m2">ม.2</option> <option id="calss_m3" value="m3">ม.3</option> <option id="calss_m4" value="m4">ม.4</option> <option id="calss_m5" value="m5">ม.5</option> <option id="calss_m6" value="m6">ม.6</option> </select> <p class="text-bold text-search set-text-teacher-4" style="left: 30%;" >ห้อง</p> <select disabled="disabled" id="room" name="room" class="form-control form-add-class-3" style="margin-left: 10%"> <option id="room_1" value="1">1</option> <option id="room_2" value="2">2</option> <option id="room_3" value="3">3</option> <option id="room_4" value="4">4</option> <option id="room_5" value="5">5</option> <option id="room_6" value="6">6</option> <option id="room_7" value="7">7</option> <option id="room_8" value="8">8</option> <option id="room_9" value="9">9</option> <option id="room_10" value="10">10</option> </select> </div> <div class="mb-5 col-sm-12"> <p class="text-bold text-search set-text-teacher-3" >คำนำหน้าชื่อ</p> <select id="name_title" name="name_title" class="form-control form-add-class-2-2"> <option id="name_title_dekchai" value="dekchai">เด็กชาย</option> <option id="name_title_dekying" value="dekying">เด็กหญิง</option> <option id="name_title_nai" value="nai">นาย</option> <option id="name_title_nangsaw" value="nangsaw">นางสาว</option> </select> </div> <div class="mb-10 col-sm-6"> <p class="text-bold text-search set-text-teacher-1" >ชื่อ</p> <div class="input-group form-add-teacher"> <input id="fname" name="fname" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-10 col-sm-6"> <p class="text-bold text-search set-text-teacher-2">สกุล</p> <div class="input-group form-add-teacher"> <input id="lname" name="lname" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-10 col-sm-6"> <p class="text-bold text-search set-text-teacher-1" >วัน/เดือน/ปีเกิด</p> <select name="years" id="years_set" class="form-control border-violet born-box-years"> <?php for ($i=2560; $i >=2490 ; $i--) { ?> <option <?php if ($extra_data['year']==$i) { echo "selected"; } ?> value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php } ?> </select> <select name="mouth" onchange="get_day(this.value)" class="form-control border-violet born-box-month"> <option selected disabled>เดือนเกิด</option> <option value="1" <?php if($extra_data['month']==1){echo "selected";} ?>>ม.ค.</option> <option value="2" <?php if($extra_data['month']==2){echo "selected";} ?>>ก.พ.</option> <option value="3" <?php if($extra_data['month']==3){echo "selected";} ?>>มี.ค.</option> <option value="4" <?php if($extra_data['month']==4){echo "selected";} ?>>เม.ย.</option> <option value="5" <?php if($extra_data['month']==5){echo "selected";} ?>>พ.ค.</option> <option value="6" <?php if($extra_data['month']==6){echo "selected";} ?>>มิ.ย.</option> <option value="7" <?php if($extra_data['month']==7){echo "selected";} ?>>ก.ค.</option> <option value="8" <?php if($extra_data['month']==8){echo "selected";} ?>>ส.ค.</option> <option value="9" <?php if($extra_data['month']==9){echo "selected";} ?>>ก.ย.</option> <option value="10" <?php if($extra_data['month']==10){echo "selected";} ?>>ต.ค.</option> <option value="11" <?php if($extra_data['month']==11){echo "selected";} ?>>พ.ย.</option> <option value="12" <?php if($extra_data['month']==12){echo "selected";} ?>>ธ.ค.</option> </select> <select name="day" id="day_set" class="form-control border-violet born-box-day"> <option selected disabled>วันเกิด</option> <?php echo $extra_data['day']; ?> </select> </div> <div class="col-sm-6 mt-5"> <p class="text-bold text-search set-text-teacher-2" >หมู่โลหิต</p> <select id="blood_group" name="blood_group" class="form-control form-add-class-4"> <option id="blood_group_A" value="A">A</option> <option id="blood_group_B" value="B">B</option> <option id="blood_group_AB" value="AB">AB</option> <option id="blood_group_O" value="O">O</option> </select> </div> <div class="mb-30 col-sm-12"> <p class="text-bold text-search set-text-teacher-address" >ที่อยู่</p> <div class="textarea-address"> <textarea id="address" name="address" class="form-control border-violet left " rows="3"></textarea> </div> </div> <div class="mb-30 col-sm-12"> <p class="text-bold text-search set-text-teacher-3" >สถานะ</p> <select id="status_alive" name="status_alive" class="form-control form-add-class-2-2" style="width: 140px;"> <option value="1">กำลังศึกษา</option> <option value="2">สำเร็จการศึกษา</option> <option value="3">ย้ายสถานศึกษา</option> <option value="4">ลาออก</option> <option value="5">เสียชีวิต</option> </select> </div> <div class="col-sm-12"> <p class="text-title-in-grey text-violet ml-50 mb-20">ข้อมูลผู้ปกครอง</p> </div> <div class="mb-5 col-sm-12"> <p class="text-bold text-search set-text-teacher-3" >คำนำหน้าชื่อ</p> <select id="parent_name_title" name="parent_name_title" class="form-control form-add-class-2-2"> <option id="parent_name_title_nai" value="nai">นาย</option> <option id="parent_name_title_nang" value="nang">นาง</option> <option id="parent_name_title_nangsaw" value="nangsaw">นางสาว</option> </select> </div> <div class="mb-10 col-sm-6"> <p class="text-bold text-search set-text-teacher-1" >ชื่อ</p> <div class="input-group form-add-teacher"> <input id="parent_fname" name="parent_fname" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-10 col-sm-6"> <p class="text-bold text-search set-text-teacher-2">สกุล</p> <div class="input-group form-add-teacher"> <input id="parent_lname" name="parent_lname" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-10 col-sm-6"> <p class="text-bold text-search set-text-teacher-1" >โทรศัพท์</p> <div class="input-group form-add-teacher"> <input id="tell" name="tell" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </div> <div class="mb-30 col-sm-12"> <p class="text-bold text-search set-text-teacher-address" >ที่อยู่</p> <div class="textarea-address"> <textarea id="parent_address" name="parent_address" class="form-control border-violet left address-box" rows="3"></textarea> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <div onclick="get_data_form()" class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalEdit" class="btn-violet"> บันทึก </div> </div> </div> </div> </form> </div> </div> </div> </div><file_sep>/modules/mobile_api/newsDetailSub.php <?php @session_start(); require_once('config.php'); require_once('src/database.php'); include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $condition = false; $num= $class_data->rows[0]['num']; $json = json_decode(file_get_contents('php://input'), true); $newsSendId=$json['newsSendId']; $token=$json['token']; $token_set='4939d40bd21d4b987edc18a1911a6b94'; if (MD5($token)==$token_set) { $products_arr=array(); $products_arr["records"]=array(); $class_data->sql = "SELECT DataID,file_name FROM tbl_news_gallery_sub WHERE newsID=$newsSendId"; $class_data->select(); $class_data->setRows(); foreach($class_data->rows as $key => $value) { $DataID= $value['DataID']; $file_name= $value['file_name']; $img_url='/file_managers/news_sub/'.$file_name; $data_res['status']=1; $product_item=array( "key" => $DataID, "img_url_sub" => $img_url, ); array_push($products_arr["records"], $product_item); } } echo json_encode($products_arr); ?> <file_sep>/modules/mobile_api/host/config.php <?php @header( 'Pragma: no-cache' ); @header( 'Content-Type:text/html; charset=utf-8'); date_default_timezone_set('Asia/Bangkok'); error_reporting(0); $connectstr_dbhost = ''; $connectstr_dbname = ''; $connectstr_dbusername = ''; $connectstr_dbpassword = ''; foreach ($_SERVER as $key => $value) { if (strpos($key, "MYSQLCONNSTR_localdb") !== 0) { continue; } $connectstr_dbhost = preg_replace("/^.*Data Source=(.+?);.*$/", "\\1", $value); $connectstr_dbname = preg_replace("/^.*Database=(.+?);.*$/", "\\1", $value); $connectstr_dbusername = preg_replace("/^.*User Id=(.+?);.*$/", "\\1", $value); $connectstr_dbpassword = preg_replace("/^.*Password=(.+?)$/", "\\1", $value); } // ** MySQL settings - You can get this info from your web host ** // /** MySQL hostname : this contains the port number in this format host:port . Port is not 3306 when using this feature*/ define('DB_SERVER', $connectstr_dbhost); /** MySQL database username */ define('DB_USER', $connectstr_dbusername); /** MySQL database password */ define('DB_PASS', $connectstr_dbpassword); /** The name of the database for WordPress */ define('DB_DATABASE', 'sratong_eva'); ?> <file_sep>/modules/profile/backup/edit.php <?php include('modules/profile/class_modules.php'); $class_data = new ClassData(); $extra_data=$class_data->get_extra_data(); ?> <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="row"> <div class="col-sm-5"> <form id="frm_data_up" method="post" enctype="multipart/form-data"> <input id="uploadBtn" type="file" name="file_up" style="display: none;" /> </form> <div class="profile-set" id="uploadBtn_select"> <span class="glyphicon glyphicon-picture span-profile" aria-hidden="true"></span> <div id="get_profile_img"> </div> </div> </div> <div class="col-sm-7 mt-40" > <center> <a href="index.php?op=profile-index"> <div class="btn-profile-header-first text-black"> ข้อมูลส่วนตัว </div> </a> <a href="index.php?op=profile-edit"> <div class="btn-profile-header-sec soft-violet text-black"> แก้ไข </div> </a> </center> </div> </div> <div class="row stage-se mt-10"> <div class="col-sm-5"> <h3 class="text-bold center-col" id="full_name_th"></h3> <h4 class="text-bold center-col">กลุ่มสาระ <label id="department_pro"></label></h4> </div> <div class="line-divide-col"></div> <div class="col-sm-7"> <div class="profile-detail-box mt-20 fs-16 ml-20"> <form id="frm_data"> <table class="table table-borderless"> <tbody style="border: none;"> <tr> <th>เลขประจำตำแหน่ง</th> <td> <div id="profile-edit-box_chk" class="profile-edit-box"> <input type="text" id="positionID" name="positionID" > </div> </td> </tr> <tr> <th width="35%">ชื่อ</th> <td> <div class="profile-edit-box"> <input type="text" id="fname_th" name="fname_th"> </div> </td> </tr> <tr> <th width="35%">นามสกุล</th> <td> <div class="profile-edit-box"> <input type="text" id="lname_th" name="lname_th"> </div> </td> </tr> <tr> <th width="35%">Firstname</th> <td> <div class="profile-edit-box"> <input type="text" id="fname_en" name="fname_en" > </div> </td> </tr> <tr> <th width="35%">Lastname</th> <td> <div class="profile-edit-box"> <input type="text" id="lname_en" name="lname_en" > </div> </td> </tr> <tr> <th>การศึกษา</th> <td> <div class="profile-edit-box"> <textarea rows="3" id="study_history" name="study_history"> </textarea> </div> </td> </tr> <tr> <th>วัน/เดือน/ปีเกิด</th> <td> <div class="profile-edit-box"> <div class="row"> <div class="col-md-3 col-sm-3"> <select id="day_set" name="day" class="form-control"> <option selected disabled>วันเกิด</option> <?php echo $extra_data['day']; ?> </select> </div> <div class="col-md-3 col-sm-3"> <select onchange="get_day(this.value)" name="month" id="month" class="form-control"> <option selected disabled>เดือนเกิด</option> <option value="1" <?php if($extra_data['month']==1){echo "selected";} ?>>ม.ค.</option> <option value="2" <?php if($extra_data['month']==2){echo "selected";} ?>>ก.พ.</option> <option value="3" <?php if($extra_data['month']==3){echo "selected";} ?>>มี.ค.</option> <option value="4" <?php if($extra_data['month']==4){echo "selected";} ?>>เม.ย.</option> <option value="5" <?php if($extra_data['month']==5){echo "selected";} ?>>พ.ค.</option> <option value="6" <?php if($extra_data['month']==6){echo "selected";} ?>>มิ.ย.</option> <option value="7" <?php if($extra_data['month']==7){echo "selected";} ?>>ก.ค.</option> <option value="8" <?php if($extra_data['month']==8){echo "selected";} ?>>ส.ค.</option> <option value="9" <?php if($extra_data['month']==9){echo "selected";} ?>>ก.ย.</option> <option value="10" <?php if($extra_data['month']==10){echo "selected";} ?>>ต.ค.</option> <option value="11" <?php if($extra_data['month']==11){echo "selected";} ?>>พ.ย.</option> <option value="12" <?php if($extra_data['month']==12){echo "selected";} ?>>ธ.ค.</option> </select> </div> <div class="col-md-4 col-sm-4"> <select name="years" class="form-control"> <?php for ($i=2560; $i >=2490 ; $i--) { ?> <option <?php if ($extra_data['year']==$i) { echo "selected"; } ?> value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php } ?> </select> </div> </div> </div> </td> </tr> <tr> <th>เพศ</th> <td> <div class="radio radio-inline"> <label><input type="radio" name="gender" value="male" <?php if($extra_data['gender']=="male"){echo "checked";} ?>>ชาย</label> </div> <div class="radio radio-inline"> <label><input type="radio" name="gender" value="female" <?php if($extra_data['gender']=="female"){echo "checked";} ?>>หญิง</label> </div> </td> </tr> <tr> <th>หมู่โลหิต</th> <td> <div class="profile-edit-box"> <div class="row"> <div class="col-md-4 col-sm-4"> <select id="blood_group" name="blood_group" class="form-control"> <option value="" <?php if($extra_data['blood_group']==""){echo "selected";} ?>>เลือก</option> <option value="A" <?php if($extra_data['blood_group']=="A"){echo "selected";} ?>>A</option> <option value="B" <?php if($extra_data['blood_group']=="B"){echo "selected";} ?>>B</option> <option value="AB" <?php if($extra_data['blood_group']=="AB"){echo "selected";} ?>>AB</option> <option value="O" <?php if($extra_data['blood_group']=="O"){echo "selected";} ?>>O</option> </select> </div> </div> </div> </td> </tr> <tr> <th>ที่อยู่</th> <td> <div class="profile-edit-box"> <textarea rows="3" id="address" name="address"></textarea> </div> </td> </tr> <tr> <th>ตำแหน่ง</th> <td> <div class="profile-edit-box"> <input type="text" id="position_name" name="position_name" > </div> </td> </tr> <tr> <th>กลุ่มสาระ</th> <td> <div class="profile-edit-box"> <div class="row"> <div class="col-md-8 col-sm-8"> <select name="department" class="form-control"> <option value="" <?php if($extra_data['department']==""){echo "selected";} ?>>เลือก</option> <option value="1" <?php if($extra_data['department']=="1"){echo "selected";} ?>>ภาษาไทย</option> <option value="2" <?php if($extra_data['department']=="2"){echo "selected";} ?>>คณิตศาสตร์</option> <option value="3" <?php if($extra_data['department']=="3"){echo "selected";} ?>>วิทยาศาสตร์</option> <option value="4" <?php if($extra_data['department']=="4"){echo "selected";} ?>>สังคมศึกษา ศาสนาและวัฒนธรรม </option> <option value="5" <?php if($extra_data['department']=="5"){echo "selected";} ?>>สุขศึกษาและพลศึกษา </option> <option value="6" <?php if($extra_data['department']=="6"){echo "selected";} ?>>ศิลปะ </option> <option value="7" <?php if($extra_data['department']=="7"){echo "selected";} ?>>การงานอาชีพและเทคโนโลยี</option> <option value="8" <?php if($extra_data['department']=="8"){echo "selected";} ?>>ภาษาต่างประเทศ</option> </select> </div> </div> </div> </td> </tr> <tr> <th>ฝ่ายงาน</th> <td> <div class="profile-edit-box"> <input type="text" id="work" name="work" placeholder="*เช่น ฝ่ายวิชาการ ฝ่ายบุคคล" > </div> </td> </tr> <tr> <th>เพิ่มเติม</th> <td> <div class="profile-edit-box"> <textarea rows="3" id="more_detail" name="more_detail"></textarea> </div> </td> </tr> <tr> <th>โทรศัพท์</th> <td> <div class="profile-edit-box"> <input type="text" name="tell" id="tell" > </div> </td> </tr> <tr> <th>อีเมล</th> <td> <div class="profile-edit-box"> <input type="text" name="email" id="email" > </div> </td> </tr> </tbody> </table> <div class="btn-confirm-regis-profile pd-40"> <div class="btn-grey close-modal-alert" data-dismiss="modal"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalEdit" class="btn-violet"> ยืนยัน </div> </div> </form> </div> </div> </div> </div> </div><file_sep>/modules/report_std_personal/class_modules_m.php <?php class ClassData extends Databases { public function get_pw6_m($std_ID,$term,$year){ $this->sql =" SELECT tbl_pp6.name_title,tbl_pp6.fname,tbl_pp6.lname,tbl_pp6.class_level,tbl_pp6.room,tbl_pp6.DataID as pp6_ID,tbl_pp6.term,tbl_pp6.year,tbl_sub_pp6.name as course_name,tbl_sub_pp6.courseID as courseID,tbl_sub_pp6.department as department,tbl_sub_pp6.unit as unit,tbl_sub_pp6.status as status_course,tbl_sub_pp6.status_form as status_form,tbl_sub_pp6.score_mid as score_mid,tbl_sub_pp6.score_final as score_final,tbl_sub_pp6.score_total as score_total,tbl_sub_pp6.score_desirable as score_desirable,tbl_sub_pp6.score_rtw as score_rtw,tbl_sub_pp6.score_attend as score_attend FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_pp6.std_ID='$std_ID' AND term='$term' AND year='$year' "; $this->select(); $this->setRows(); $card_ID=$this->rows[0]['card_ID']; $name_title_data=$this->rows[0]['name_title']; $fname=$this->rows[0]['fname']; $lname=$this->rows[0]['lname']; $class_level_data=$this->rows[0]['class_level']; $room=$this->rows[0]['room']; $term_data=$this->rows[0]['term']; $year_data=$this->rows[0]['year']; $class_level=$this->get_class_level_number($class_level_data); $name_title=$this->get_name_title($name_title_data); $data_response['std_ID']=$std_ID; $data_response['card_ID']=$card_ID; $data_response['std_name']=$name_title.$fname.' '.$lname; $data_response['class_level_room']=$class_level.'/'.$room; $data_response['term']=$term_data; $data_response['year']=$year_data; $unit_count_main=0; $unit_count_add=0; $score_mid_count=0; $score_final_count=0; $score_total_count=0; $score_desirable_count=0; $score_rtw_count=0; $unit_not_cout_main=0; $unit_not_cout_add=0; $attend_not_pass_count=0; $result_row=0; $count=0; $count_all=0; $num_main=1; $num_add=1; $num_dev=1; foreach($this->rows as $key => $value) { $course_name = $value['course_name']; $courseID = $value['courseID']; $unit = $value['unit']; $score_mid = $value['score_mid']; $score_final = $value['score_final']; $score_total = $value['score_total']; $status_course=$value['status_course']; $status_form=$value['status_form']; $score_desirable = number_format($value['score_desirable'],0); $score_rtw = number_format($value['score_rtw'],0); $score_attend = $value['score_attend']; $department_data=$value['department']; //$department=$this->get_department($department_data); if ($status_course==1) { if ($status_form==11) { if($score_total==-1){ $grade_set='ร'; $score_total=$score_mid+$score_final; $unit_not_cout_main=$unit_not_cout_main+$unit; }else{ $grade_set=$this->get_grade($score_total); $score_total_count=$score_total_count+$score_total; $score_mid_count=$score_mid_count+$score_mid; $score_final_count=$score_final_count+$score_final; $score_desirable_count=$score_desirable_count+$score_desirable; $score_rtw_count=$score_rtw_count+$score_rtw; } $data_response['sub_main_list'].=' <tr> <td>'.$num_main.'</td> <td style="text-align: left;">'.$course_name.'</td> <td>'.$courseID.'</td> <td>'.$unit.'</td> <td>'.$score_total.'</td> <td>'.$grade_set.'</td> <td>'.$score_desirable.'</td> <td>'.$score_rtw.'</td> <td></td> </tr> '; $unit_count_main=$unit_count_main+$unit; $num_main++; }else{ if($score_total==-1){ $grade_set='ร'; $score_total=$score_mid+$score_final; $unit_not_cout_add=$unit_not_cout_add+$unit; }else{ $grade_set=$this->get_grade($score_total); $score_total_count=$score_total_count+$score_total; $score_mid_count=$score_mid_count+$score_mid; $score_final_count=$score_final_count+$score_final; $score_desirable_count=$score_desirable_count+$score_desirable; $score_rtw_count=$score_rtw_count+$score_rtw; } $data_response['sub_add_list'].=' <tr> <td>'.$num_add.'</td> <td style="text-align: left;">'.$course_name.'</td> <td>'.$courseID.'</td> <td>'.$unit.'</td> <td>'.$score_total.'</td> <td>'.$grade_set.'</td> <td>'.$score_desirable.'</td> <td>'.$score_rtw.'</td> <td></td> </tr> '; $unit_count_add=$unit_count_add+$unit; $num_add++; } $result_row=$result_row+($grade_set*$unit); $count++; }else{ if ($score_attend==1) { $attend_text='ผ่าน'; }else{ $attend_text='ไม่ผ่าน'; $attend_not_pass_count++; } $data_response['sub_dev_list'].=' <tr> <td>'.$num_dev.'</td> <td style=";text-align: left;">'.$course_name.'</td> <td>'.$courseID.'</td> <td>-</td> <td>-</td> <td style=";text-align: center;">'.$attend_text.'</td> <td>'.$score_desirable.'</td> <td>'.$score_rtw.'</td> <td></td> </tr> '; $score_desirable_count_dev=$score_desirable_count_dev+$score_desirable; $score_rtw_count_dev=$score_rtw_count_dev+$score_rtw; $num_dev++; } $unit_all=number_format($unit_count_main+$unit_count_add,1); $count_all++; } $data_response['sub_sum_list']=' <tr style="text-align: center;font-weight:bold;"> <td colspan="3">รวม</td> <td>'.$unit_all.'</td> <td>'.$score_total_count.'</td> <td>'.number_format($result_row/($unit_count_main+$unit_count_add),2).'</td> <td>'.$score_desirable_count.'</td> <td>'.$score_rtw_count.'</td> <td></td> </tr> '; $find_score_average=$score_total_count/$count; $find_desirable_average=number_format(($score_desirable_count+$score_desirable_count_dev)/$count_all,0); $find_rtw_average=number_format(($score_rtw_count+$score_rtw_count_dev)/$count_all,0); /* $data_response['sub_average_list']=' <tr style="text-align: center;font-weight:bold;"> <td colspan="6">เฉลี่ย</td> <td>'.$find_score_average.'</td> <td></td> <td>'.$find_desirable_average.'</td> <td>'.$find_rtw_average.'</td> <td></td> </tr> ';*/ $unit_posible_main=number_format($unit_count_main-$unit_not_cout_main,1); $unit_posible_add=number_format($unit_count_add-$unit_not_cout_add,1); $rtw_text=$this->get_rtw_text($find_rtw_average); $desirable_text=$this->get_desirable_text($find_desirable_average); if ($attend_not_pass_count>0) { $attend_text_set='ไม่ผ่าน'; }else{ $attend_text_set='ผ่าน'; } $find_position=$this->find_position($year_data,$term,$class_level_data,$room); arsort($find_position); /*$arrayValuePosition=$this->arrayValuePosition($std_ID,$find_position); $new_position=$arrayValuePosition+1;*/ $arrayValuePosition=$this->arrayValuePositionNew($find_position,$std_ID); $data_response['sub_conclution_list']=' <tbody style="text-align: center;"> <tr style="background-color: #ddddddb3;font-weight: bold;"> <th rowspan="2" style="text-align: center;">สรุปผลการประเมิน</th> <th colspan="2" style="text-align: center;">ผลการเรียน</th> </tr> <tr style="background-color: #ddddddb3;font-weight: bold;"> <th style="text-align: center;width:14%;">ที่เรียน</th> <th style="text-align: center;width:14%;">ที่ได้</th> </tr> <tr> <td style="text-align: left;">จำนวนหน่วยกิตวิชาพื้นฐาน</td> <td>'.number_format($unit_count_main,1).'</td> <td>'.number_format($unit_posible_main,1).'</td> </tr> <tr> <td style="text-align: left;">จำนวนหน่วยกิตวิชาเพิ่มเติม</td> <td>'.number_format($unit_count_add,1).'</td> <td>'.number_format($unit_posible_add,1).'</td> </tr> <tr> <td style="text-align: left;">รวมจำนวนหน่วยกิต</td> <td>'.number_format($unit_count_main+$unit_count_add,1).'</td> <td>'.number_format($unit_posible_main+$unit_posible_add,1).'</td> </tr> <tr> <td style="text-align: left;">ระดับผลการเรียนเฉลี่ย</td> <td colspan="2">'.number_format($result_row/($unit_count_main+$unit_count_add),2).'</td> </tr> <tr> <td style="text-align: left;">ลำดับที่ในห้องเรียน</td> <td colspan="2">'.$arrayValuePosition.'</td> </tr> <tr> <td style="text-align: left;">คุณลักษณะอันพึงประสงค์</td> <td colspan="2">'.$desirable_text.'</td> </tr> <tr> <td style="text-align: left;">อ่าน เขียน คิดวิเคราะห์</td> <td colspan="2">'.$rtw_text.'</td> </tr> <tr> <td style="text-align: left;">ผลการประเมินกิจกรรมพัฒนาผู้เรียน</td> <td colspan="2">'.$attend_text_set.'</td> </tr> </tbody> '; return $data_response; } public function arrayValuePositionNew($find_position,$std_ID){ $result = array(); $pos = $real_pos = 0; $prev_score = -1; foreach ($find_position as $exam_n => $score) { $real_pos += 1;// Natural position. $pos = ($prev_score != $score) ? $real_pos : $pos;// If I have same score, I have same position in ranking, otherwise, natural position. $result[$exam_n] = array( "score" => $score, "position" => $pos, "exam_no" => $exam_n ); $prev_score = $score;// update last score. } return $result[$std_ID]["position"]; } public function arrayValuePosition($value, $array){ return array_search($value, array_keys($array)); } public function get_data_big_std($std_pp6_id,$pp6_id){ $this->sql ="SELECT unit,score_total FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); $find_row_sum=0; foreach($this->rows as $key => $value) { $unit=$value['unit']; $score_total=$value['score_total']; $grade= $this->get_grade($score_total); $find_row_sum=$find_row_sum+($unit*$grade); } $this->sql ="SELECT SUM(unit) as unit_sum FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $unit_sum=$this->rows[0]['unit_sum']; return $find_row_sum/$unit_sum; } public function find_position($year_data,$term,$class_level_data,$room){ $data_response = array(); $this->sql ="SELECT distinct(tbl_pp6.std_ID) as std_pp6_id,tbl_pp6.DataID as pp6_id FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_pp6.year='$year_data' AND tbl_pp6.term='$term' AND tbl_pp6.room='$room' AND tbl_pp6.class_level='$class_level_data' AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $find_gpa_sum=0; $score_final_count=0; foreach($this->rows as $key => $value) { $std_pp6_id=$value['std_pp6_id']; $pp6_id=$value['pp6_id']; $data_big_std= $this->get_data_big_std($std_pp6_id,$pp6_id); $test[$std_pp6_id] = $data_big_std; /* $pick_poi= $this->get_pick_poi($registed_courseID,$stdID,$term_data,$year); $grade_text=$this->get_grade_text($score_exam,$pick_poi); $unit=$this->get_unit($registed_courseID); $find_gpa=$grade_text*$unit; $find_gpa_sum=$find_gpa_sum+$find_gpa;*/ //$tt.=$stdID.'='.$insert.','; } //$total= $final_poi+$mid_poi; return $test; } public function get_rtw_text($find_rtw_average){ switch ($find_rtw_average) { case 0: $rtw='ไม่ผ่าน'; break; case 1: $rtw='ผ่าน'; break; case 2: $rtw='ดี'; break; case 3: $rtw='ดีเยี่ยม'; break; default: $rtw=''; } return $rtw; } public function get_desirable_text($find_desirable_average){ switch ($find_desirable_average) { case 0: $desirable='ไม่ผ่าน'; break; case 1: $desirable='ผ่าน'; break; case 2: $desirable='ดี'; break; case 3: $desirable='ดีเยี่ยม'; break; default: $desirable=''; } return $desirable; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพและเทคโนโลยี'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; default: $department=''; } return $department; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_pp6 "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_std_list($class_search,$room_search,$name_id_search,$search_status,$term,$year){ $data_response = array(); $sql_condition = ""; if ($search_status=="class_room") { $sql_condition = " AND ( class_level LIKE '%{$class_search}%') AND ( room LIKE '%{$room_search}%')"; }elseif ($search_status=="name_id") { $sql_condition = " AND (std_ID LIKE '%{$name_id_search}%') OR ( fname LIKE '%{$name_id_search}%') OR ( lname LIKE '%{$name_id_search}%')"; } $this->sql =" SELECT * FROM tbl_pp6 WHERE term='$term' AND year='$year' $sql_condition "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $std_ID= $value['std_ID']; $name_title_data= $value['name_title']; $fname= $value['fname']; $lname= $value['lname']; $class_level_data= $value['class_level']; $class_level=$this->get_class_level($class_level_data); $name_title=$this->get_name_title($name_title_data); $room= $value['room']; $pp6_ID= $value['pp6_ID']; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6') { $data_link='modules/report_std_personal/report_form_p.php?std_ID='.$std_ID.'&year='.$year.'&term='.$term.''; }else{ $data_link='modules/report_std_personal/report_form_m.php?std_ID='.$std_ID.'&year='.$year.'&term='.$term.''; } $data_response.=' <tr> <td style="text-align: center;"> <input class="checkbox_data" type="checkbox" value="'.$pp6_ID.'" name="checkbox_print[]" id="'.$pp6_ID.'"> </td> <td style="text-align: center;">'.$std_ID.'</td> <td>'.$name_title.$fname.'</td> <td>'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> <a target="_blank" href="'.$data_link.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } echo json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_class_level_number($class_level_data){ if ($class_level_data=="p1") { $class_level="1"; }elseif($class_level_data=="p2"){ $class_level="2"; }elseif($class_level_data=="p3"){ $class_level="3"; }elseif($class_level_data=="p4"){ $class_level="4"; }elseif($class_level_data=="p5"){ $class_level="5"; }elseif($class_level_data=="p6"){ $class_level="6"; }elseif($class_level_data=="m1"){ $class_level="1"; }elseif($class_level_data=="m2"){ $class_level="2"; }elseif($class_level_data=="m3"){ $class_level="3"; }elseif($class_level_data=="m4"){ $class_level="4"; }elseif($class_level_data=="m5"){ $class_level="5"; }elseif($class_level_data=="m6"){ $class_level="6"; } return $class_level; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/conclusion/class_modules/learing_resualt_level.php <?php class ClassData extends Databases { public function get_loop_data($class_level,$year,$term){ $this->sql ="SELECT DISTINCT(department) AS department,courseID FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) ORDER BY pp6_ID ASC "; $this->select(); $this->setRows(); $order=1; $amount_std_all=0; $grade_amount_40=0; $grade_amount_35=0; $grade_amount_30=0; $grade_amount_25=0; $grade_amount_20=0; $grade_amount_15=0; $grade_amount_10=0; $grade_amount_00=0; $grade_amount_higher_3=0; $grade_amount_higher_3_percentage=0; foreach($this->rows as $key => $value) { $department_set=$value['department']; $courseID=$value['courseID']; $department=$this->get_department($department_set); $amount_std=$this->get_amount_std($department_set,$class_level,$year,$term); $grade_amount=$this->get_grade_amount($department_set,$class_level,$year,$term); $grade_higher_3=$grade_amount['data_40']+$grade_amount['data_35']+$grade_amount['data_30']; $grade_higher_3_percentage=number_format(($grade_higher_3*100)/$amount_std,2); $data_response.=' <tr> <td>'.$order.'</td> <td>'.$courseID.'</td> <td style="text-align:left;padding-left:15px;">'.$department.'</td> <td>'.$amount_std.'</td> <td>'.$grade_amount['data_40'].'</td> <td>'.$grade_amount['data_35'].'</td> <td>'.$grade_amount['data_30'].'</td> <td>'.$grade_amount['data_25'].'</td> <td>'.$grade_amount['data_20'].'</td> <td>'.$grade_amount['data_15'].'</td> <td>'.$grade_amount['data_10'].'</td> <td>'.$grade_amount['data_00'].'</td> <td>'.$grade_higher_3.'</td> <td>'.$grade_higher_3_percentage.'</td> <td></td> </tr> '; $order++; $amount_std_all=$amount_std_all+$amount_std; $grade_amount_40=$grade_amount_40+$grade_amount['data_40']; $grade_amount_35=$grade_amount_35+$grade_amount['data_35']; $grade_amount_30=$grade_amount_30+$grade_amount['data_30']; $grade_amount_25=$grade_amount_25+$grade_amount['data_25']; $grade_amount_20=$grade_amount_20+$grade_amount['data_20']; $grade_amount_15=$grade_amount_15+$grade_amount['data_15']; $grade_amount_10=$grade_amount_10+$grade_amount['data_10']; $grade_amount_00=$grade_amount_00+$grade_amount['data_00']; $grade_amount_higher_3=$grade_amount_higher_3+$grade_higher_3; $grade_amount_higher_3_percentage=$grade_amount_higher_3_percentage+$grade_higher_3_percentage; } $order--; $data_response.=' <tr> <td colspan="3" style="font-weight:bold">รวม</td> <td>'.$amount_std_all.'</td> <td>'.$grade_amount_40.'</td> <td>'.$grade_amount_35.'</td> <td>'.$grade_amount_30.'</td> <td>'.$grade_amount_25.'</td> <td>'.$grade_amount_20.'</td> <td>'.$grade_amount_15.'</td> <td>'.$grade_amount_10.'</td> <td>'.$grade_amount_00.'</td> <td>'.$grade_amount_higher_3.'</td> <td>'.number_format($grade_amount_higher_3_percentage/$order,2).'</td> <td></td> </tr> <tr> <td colspan="3" style="font-weight:bold">ร้อยละ</td> <td>100.00</td> <td>'.number_format(($grade_amount_40*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_35*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_30*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_25*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_20*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_15*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_10*100)/$amount_std_all,2).'</td> <td>'.number_format(($grade_amount_00*100)/$amount_std_all,2).'</td> <td></td> <td></td> <td></td> </tr> <tr> <td colspan="4" style="font-weight:bold">ระดับผลการเรียน 3.0 ขึ้นไป คิดเป็นร้อยละ</td> <td colspan="3">'.number_format((($grade_amount_40+$grade_amount_35+$grade_amount_30)*100)/$amount_std_all,2).'</td> <td colspan="5">'.number_format((($grade_amount_25+$grade_amount_20+$grade_amount_15+$grade_amount_10+$grade_amount_00)*100)/$amount_std_all,2).'</td> <td></td> <td></td> <td></td> </tr> '; return $data_response; } public function get_grade_amount($department_set,$class_level,$year,$term){ $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) "; $this->select(); $this->setRows(); $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; foreach($this->rows as $key => $value) { $score_total=$value['score_total']; if ($score_total!=-1) { $grade=$this->get_grade($score_total); if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } }elseif($score_total==-1){ $data_00++; } } $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; return $data_response; } public function get_amount_std($department_set,$class_level,$year,$term){ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_level_data($class_level,$year,$term,$image_logo,$footer_text_cen_normal){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_front_text='ประถมศึกษาปีที่'; }else{ $class_front_text='มัธยมศึกษาปีที่'; } $loop_data=$this->get_loop_data($class_level,$year,$term); $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:16px"> <img class="logo-print-size-level" src="'.$image_logo.'"> <p >รายงานสรุปการพัฒนาคุณภาพผู้เรียนตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 20px;">ระดับชั้น <span style="font-weight: normal;">'.$class_front_text.' '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">ภาคเรียนที่ <span style="font-weight: normal;">'.$term.'</span> </span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 14px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >ที่</div> </th> <th rowspan="2" class="rotate" style="width: 10%;height: 0px;text-align: center;"> <div >รหัสวิชา</div> </th> <th rowspan="2" style="width: 25%;vertical-align: middle;text-align: center;"> สาระการเรียนรู้ </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >จำนวน นักเรียน</div> </th> <th colspan="8" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >ระดับผลการเรียน</div> </th> <th colspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >เกรด 3.0 ขึ้นไป</div> </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >หมายเหตุ</div> </th> </tr> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 4 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 3.5 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 3 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 2.5 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 2 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 1.5 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 1 </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> 0,ร </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> รวม </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> ร้อยละ </th> </tr> </thead> <tbody > '.$loop_data.' </tbody> </table> <div style="margin-top:40px;"> '.$footer_text_cen_normal.' </div> </page> </div> '; return $data_response; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_registed_course ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพฯ'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; case 9: $department='หน้าที่พลเมือง'; break; case 10: $department='ศิลปะพื้นบ้าน'; break; case 11: $department='ศักยภาพ'; break; case 12: $department='ภาษาจีน'; break; default: $department=''; } return $department; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } }<file_sep>/modules/regis_course_teaching/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "update_exam_mid_object"){ $data_id_first=$_GET['data_id_first']; $objective_conclude_id=$_GET['objective_conclude_id']; echo $class_data->update_exam_mid_object($data_id_first,$objective_conclude_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "update_exam_final_object"){ $data_id_first=$_GET['data_id_first']; $objective_conclude_id=$_GET['objective_conclude_id']; echo $class_data->update_exam_final_object($data_id_first,$objective_conclude_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_exam_object"){ $data_id_first=$_GET['data_id_first']; echo $class_data->get_exam_object($data_id_first); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_term_year_now"){ echo $class_data->get_term_year_now(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_teaching_student_only"){ $data_id=$_GET['data_id']; $data_room=$_GET['data_room']; echo $class_data->get_teaching_student_only($data_id,$data_room); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_course_teaching_student"){ $data_id=$_GET['data_id']; echo $class_data->get_course_teaching_student($data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_propotion_objective"){ $data_id_first=$_GET['data_id_first']; echo $class_data->get_propotion_objective($data_id_first); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_objective_place_plus"){ $data_responds=' <tr> <td width="4%">ข้อที่</td> <td width="7%"> <div class="input-group"> <input name="no_order_new[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value=""> </div> </td> <td width="12%" style="padding-left: 30px;">ตัวชี้วัด</td> <td width="40%" > <div class="input-group" style="width: 100%;margin-left: -20px;"> <input name="detail_new[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value=""> </div> </td> <td width="25%"> <select id="" name="object_list_data_new[]" class="form-control search-course-depart" style="width: 100%;"> <option value="1">ก่อนกลางภาค</option> <option value="2">หลังกลางภาค</option> </select> </td> <td width="5%" style="padding-left: 30px;">คะแนน</td> <td width="15%" style="padding-left: 5px;"> <div class="input-group"> <input name="score_data_new[]" type="text" class="form-control form-set-search" aria-describedby="basic-addon1" value="" > </div> </td> <td style="padding-left: 15px;"> <div id="btn_plus_objective" style="margin-top: -6px;" class="btn-search"> <span class="text-icon">+</span> </div> </td> </tr> '; echo json_encode($data_responds); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "plus_objective"){ $class_level_status=$_GET['class_level_status']; $no_order_new=$_GET['no_order_new']; $detail_new=$_GET['detail_new']; $object_list_data_new=$_GET['object_list_data_new']; $score_data_new=$_GET['score_data_new']; $user_id=$_SESSION['ss_user_id']; if ($class_level_status=='p') { $text_option_1='ก่อนวัดผลกลางปี'; $text_option_2='หลังวัดผลกลางปี'; }else{ $text_option_1='ก่อนกลางภาค'; $text_option_2='หลังกลางภาค'; } for ($i=0; $i < count($no_order_new) ; $i++) { if ($object_list_data_new[$i]==1) { $object_list=' <option selected value="1">'.$text_option_1.'</option> <option value="2">'.$text_option_2.'</option> '; }elseif($object_list_data_new[$i]==2){ $object_list=' <option value="1">'.$text_option_1.'</option> <option selected value="2">'.$text_option_2.'</option> '; } $data_responds.=' <tr> <td width="4%">ข้อที่</td> <td width="7%"> <div class="input-group"> <input name="no_order_new[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value="'.$no_order_new[$i].'"> </div> </td> <td width="12%" style="padding-left: 30px;">ตัวชี้วัด</td> <td width="40%" > <div class="input-group" style="width: 100%;margin-left: -20px;"> <input name="detail_new[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value="'.$detail_new[$i].'"> </div> </td> <td width="25%"> <select id="" name="object_list_data_new[]" class="form-control search-course-depart" style="width: 100%;"> '.$object_list.' </select> </td> <td width="5%" style="padding-left: 30px;">คะแนน</td> <td width="15%" style="padding-left: 5px;"> <div class="input-group"> <input name="score_data_new[]" type="text" class="form-control form-set-search" aria-describedby="basic-addon1" value="'.$score_data_new[$i].'" > </div> </td> <td style="padding-left: 15px;height: 35px;"> </td> </tr> '; } $data_responds.=' <tr> <td width="4%">ข้อที่</td> <td width="7%"> <div class="input-group"> <input name="no_order_new[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value=""> </div> </td> <td width="12%" style="padding-left: 30px;">ตัวชี้วัด</td> <td width="40%" > <div class="input-group" style="width: 100%;margin-left: -20px;"> <input name="detail_new[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value=""> </div> </td> <td width="25%"> <select id="" name="object_list_data_new[]" class="form-control search-course-depart" style="width: 100%;"> <option value="1">'.$text_option_1.'</option> <option value="2">'.$text_option_2.'</option> </select> </td> <td width="5%" style="padding-left: 30px;">คะแนน</td> <td width="15%" style="padding-left: 5px;"> <div class="input-group"> <input name="score_data_new[]" type="text" class="form-control form-set-search" aria-describedby="basic-addon1" value="" > </div> </td> <td style="padding-left: 15px;"> <div id="btn_plus_objective" style="margin-top: -6px;" class="btn-search"> <span class="text-icon">+</span> </div> </td> </tr> '; echo json_encode($data_responds); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "add_data_proportion"){ $course_id=$_POST['course_id']; $arr_sql["courseID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($course_id)))."'"; $arr_sql["cumulative_before_mid"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['cumulative_before_mid'])))."'"; $arr_sql["cumulative_after_mid"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['cumulative_after_mid'])))."'"; $arr_sql["mid_exam"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['mid_exam'])))."'"; $arr_sql["final_exam"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['final_exam'])))."'"; echo $class_data->insert_data_proportion($arr_sql,$course_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "add_objective_conclude"){ $course_id=$_POST['course_id']; $no_order_new=$_POST['no_order_new']; $detail_new=$_POST['detail_new']; $object_list_data_new=$_POST['object_list_data_new']; $score_data_new=$_POST['score_data_new']; for ($i=0; $i < count($no_order_new) ; $i++) { if ($no_order_new[$i]=="" || $detail_new[$i]=="") { }else{ $class_data->sql ="INSERT INTO tbl_objective_conclude(courseID,no_order,detail,proportion_status,score) VALUES($course_id,$no_order_new[$i],'$detail_new[$i]',$object_list_data_new[$i],$score_data_new[$i])"; echo $class_data->query(); } } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "chk_cumulative_over"){ $course_id=$_GET['course_id']; $score_data =$_GET['score_data']; $object_list_data=$_GET['object_list_data']; $value_score_data = explode("-", $score_data); $value_object_list_data = explode("-", $object_list_data); $score_before_sql=0; $score_after_sql=0; for ($i=0; $i <count($value_score_data) ; $i++) { if ($value_object_list_data[$i]==1) { $score_before_sql=$score_before_sql+$value_score_data[$i]; }elseif($value_object_list_data[$i]==2){ $score_after_sql=$score_after_sql+$value_score_data[$i]; } } $score_data_new=$_GET['score_data_new']; $object_list_data_new=$_GET['object_list_data_new']; $cumulative_before_mid=$_GET['cumulative_before_mid']; $cumulative_after_mid=$_GET['cumulative_after_mid']; $score_data_before_new=0; $score_data_after_new=0; for ($i=0; $i < count($score_data_new) ; $i++) { if ($object_list_data_new[$i]==1) { $score_data_before_new=$score_data_before_new+$score_data_new[$i]; }elseif($object_list_data_new[$i]==2){ $score_data_after_new=$score_data_after_new+$score_data_new[$i]; } } $score_before=$score_before_sql+$score_data_before_new; $score_after=$score_after_sql+$score_data_after_new; if ($score_before<=$cumulative_before_mid) { $data_responds['score_before']="pass"; }else{ $data_responds['score_before']="nopass"; } if ($score_after<=$cumulative_after_mid) { $data_responds['score_after']="pass"; }else{ $data_responds['score_after']="nopass"; } echo json_encode($data_responds); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "update_objective_conclude"){ $course_id=$_POST['course_id']; $objective_data_all_id=$_POST['objective_data_all_id']; $no_order=$_POST['no_order']; $detail=$_POST['detail']; $object_list_data=$_POST['object_list_data']; $score_data=$_POST['score_data']; $arr_id = explode("-", $objective_data_all_id); $class_data->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$course_id "; $class_data->select(); $class_data->setRows(); foreach($class_data->rows as $key => $value) { $DataID=$value['DataID']; for ($i=0; $i < count($arr_id) ; $i++) { if ($DataID==$arr_id[$i]) { $sql="UPDATE tbl_objective_conclude SET no_order=$no_order[$i],detail='$detail[$i]',proportion_status=$object_list_data[$i],score=$score_data[$i] WHERE DataID={$arr_id[$i]}"; $class_data->sql =$sql; $class_data->query(); } } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "add_teaching"){ $course_id=$_POST['course_id']; $term_search=$_POST['term_search']; $year_search=$_POST['year_search']; echo $class_data->insert_data_teaching($course_id,$term_search,$year_search); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove_std"){ $data_val = $_POST['data_val']; echo $class_data->data_remove_std($data_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove_objective"){ $data_val = $_POST['data_val']; echo $class_data->data_remove_objective($data_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_registed_course_teaching"){ echo $class_data->get_registed_course_teaching(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_std_list_new"){ $id_std_search=$_GET['id_std_search']; $search_class_modal=$_GET['search_class_modal']; $search_room_modal=$_GET['search_room_modal']; $course_id=$_GET['course_id']; $term_search=$_GET['term_search']; $year_search=$_GET['year_search']; echo $class_data->get_std_list($id_std_search,$search_class_modal,$search_room_modal,$course_id,$term_search,$year_search); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_add_std"){ $data_val = $_POST['data_val']; $course_id = $_POST['course_id']; $term_search = $_POST['term_search']; $year_search = $_POST['year_search']; echo $class_data->data_add_std($data_val,$course_id,$term_search,$year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_std_list"){ $id_std_search=$_GET['id_std_search']; $search_class_modal=$_GET['search_class_modal']; $search_room_modal=$_GET['search_room_modal']; $course_id=$_GET['course_id']; echo $class_data->get_std_list($id_std_search,$search_class_modal,$search_room_modal,$course_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_name_to_add_std"){ $data_id_first=$_GET['data_id_first']; $registed_course_id=$_GET['registed_course_id']; $term_search=$_GET['term_search']; $year_search=$_GET['year_search']; echo $class_data->get_name_to_add_std($data_id_first,$registed_course_id,$term_search,$year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_class"){ $department_search=$_GET['department_search']; $class_level_search=$_GET['class_level_search']; $term_search=$_GET['term_search']; $year_search=$_GET['year_search']; echo $class_data->search_course_class($department_search,$class_level_search,$term_search,$year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "hide_class_std"){ $data_id_first=$_GET['data_id_first']; echo $class_data->hide_class_std($data_id_first); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_room_list"){ $data_id_first=$_GET['data_id_first']; $room_active=$_GET['room_active']; echo $class_data->get_room_list($data_id_first,$room_active); } <file_sep>/modules/conclusion/class_modules.php <?php class ClassData extends Databases { public function get_data_list_department($class_level,$term_data,$year_data,$department_search){ if ($class_level=='p') { $class_label='ประถมศึกษา'; }else{ $class_label='มัธศึกษา'; } if ($term_data=='1,2') { $term='ปลายปี'; }else{ $term=$term_data; } $department_text=$this->get_department($department_search); if ($class_level=='m' && $term_data!='1,2') { $data_response.=' <tr class="text-table-center"> <td>'.$department_text.'</td> <td>'.$class_label.'</td> <td>'.$term.'</td> <td>'.$year_data.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_department.php?class_level='.$class_level.'&term='.$term_data.'&year='.$year_data.'&department='.$department_search.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; }elseif ($class_level=='p' && $term_data=='1,2') { $data_response.=' <tr class="text-table-center"> <td>'.$department_text.'</td> <td>'.$class_label.'</td> <td>'.$term.'</td> <td>'.$year_data.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_department.php?class_level='.$class_level.'&term='.$term_data.'&year='.$year_data.'&department='.$department_search.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } return json_encode($data_response); } public function get_data_list_rtw($class_level,$term_data,$year_data){ $this->sql ="SELECT DISTINCT(class_level) as class_level,year,term FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term_data' AND year='$year_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $term=$value['term']; if ($term=='1,2') { $term='ปลายปี'; } $year=$value['year']; $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_rtw.php?class_level='.$class_level.'&term='.$term_data.'&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } return json_encode($data_response); } public function get_data_list_desirable($class_level,$term_data,$year_data){ $this->sql ="SELECT DISTINCT(class_level) as class_level,year,term FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term_data' AND year='$year_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $term=$value['term']; if ($term=='1,2') { $term='ปลายปี'; } $year=$value['year']; $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_desirable.php?class_level='.$class_level.'&term='.$term_data.'&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } return json_encode($data_response); } public function get_data_list_level($class_level,$term_data,$year_data){ $this->sql ="SELECT DISTINCT(class_level) as class_level,year,term FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term_data' AND year='$year_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $term=$value['term']; if ($term=='1,2') { $term='ปลายปี'; } $year=$value['year']; $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_level.php?class_level='.$class_level.'&term='.$term_data.'&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } return json_encode($data_response); } public function get_data_list_learning($class_level,$room_data,$term_data,$year_data){ if ($term_data=='mid') { $this->sql ="SELECT DISTINCT(room) as room,class_level,year FROM tbl_pp6_mid WHERE class_level='$class_level' AND room='$room_data' AND term='1,2' AND year='$year_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $term= 'กลางปี'; $year= $value['year']; $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$room.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_mid.php?class_level='.$class_level.'&room='.$room.'&term=mid&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } }else{ $this->sql ="SELECT DISTINCT(room) as room,class_level,term,year FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room_data' AND term='$term_data' AND year='$year_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $year= $value['year']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term='ปลายปี'; $link='modules/conclusion/form/learning_result_final_p.php?class_level='.$class_level.'&room='.$room.'&term=1,2&year='.$year.''; }else{ $term= $value['term']; $link='modules/conclusion/form/learning_result_final_m.php?class_level='.$class_level.'&room='.$room.'&term='.$term.'&year='.$year.''; } $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$room.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="'.$link.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } } return json_encode($data_response); } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_registed_course ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพฯ'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; case 9: $department='หน้าที่พลเมือง'; break; case 10: $department='ศิลปะพื้นบ้าน'; break; case 11: $department='ศักยภาพ'; break; case 12: $department='ภาษาจีน'; break; default: $department=''; } return $department; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/login/login.js function resetForm(form_id) { $('#'+form_id)[0].reset(); } $(function(){ $('#submit__data').click(function(e){ e.preventDefault(); AccessLogin(); return false; }); $(window).keypress(function(e) { if(e.keyCode == 13) { AccessLogin(); return false; } }); }); function AccessLogin(){ $('#alert__panel').hide(); if(!$('#username').val()){ $('#username').focus(); return false; } if(!$('#password').val()){ $('#password').focus(); return false; } var formData = $( "#form__data" ).serializeArray(); // formData.push({ "name": "acc_action", "value": "sale_orders_list" }); // console.log($.param(formData)); $.post("modules/login/process.php?t="+ new Date().getTime(), formData, function(data, textStatus, xhr) { console.log(data); }); $.ajax({ type: "POST", dataType: "json", url: "modules/login/process.php?t="+ new Date().getTime(), //Relative or absolute path to response.php file data: formData, success: function(data) { //console.log(data.success); //alert(data.pass_birth) //alert(data.success) if (data.success == '1') { if (data.status=='1') { window.location = 'index.php'; }else{ window.location = 'index.php?op=chk_grade-index'; } }else{ $('#alert__panel').show(); $('#alert__panel').html(data.error); // resetForm('form__data'); } } }); // $.ajax({ // url: "modules/login/process.php?t="+ new Date().getTime(), // dataType: "json", // type: 'POST', // data: formData, // error: function(data){ // console.log('An error has occurred'); // $('#alert__panel').html('An error has occurred'); // }, // success: function (data) { // console.log(data.success); // if (data.success == '1') { // // window.location.assign('index.php'); // }else{ // $('#alert__panel').show(); // $('#alert__panel').html(data.error); // // resetForm('form__data'); // } // } // }); }<file_sep>/modules/report/person_m_form.php <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/custom.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); ?> <page orientation="portrait"> <p class="text-bold" style="margin-left: 710px;font-size: 22px;margin-top: 25px;">ปพ.6</p> <img style="margin :10px 0px 10px 320px;display:block;width: 120px;height: 120px;"src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 22px;margin-top: -5px;"> <p class="text-bold" style="margin-top: -8px;">รายงานการพัฒนาคุณภาพผู้เรียนเป็นรายบุคคล</p> <p class="text-bold " style="margin-top: -8px;">โรงเรียนเทศบาลวัดสระทอง</p> </div> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 22px;margin-left:10px;border: 1px solid black;margin-top: 20px;"> <thead> <tr> <td style="border: none;"><span class="text-bold">ชื่อ - สกุล</span> เด็กชายสมหมาย สุขสบาย</td> <td style="border: none;"><span class="text-bold">มัธยมศึกษาปีที่</span> 1/1</td> <td style="border: none;"><span class="text-bold">เลขที่</span> 1</td> <td style="border: none;"><span class="text-bold">เลขประจำตัวนักเรียน</span> 00010</td> </tr> </thead> <tr> <td style="padding-left: 35px;border: none;"><span class="text-bold">เลขประจำตัวประชาชน</span> 1234567890123</td> <td style="border: none;"><span class="text-bold">ภาคเรียนที่</span> 1</td> <td style="border: none;"><span class="text-bold">ปีการศึกษา</span> 2560</td> </tr> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 35px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td rowspan="2" style="width: 6%;">ที่</td> <td colspan="5" style="width: 40%;">ภาคเรียนที่1</td> <td rowspan="2" style="width: 8%;"><div style="rotate:90;margin-left: -12px;">หมายเหตุ</div></td> </tr> <tr style="background-color: #e0e0e0;"> <td style="border-left: none;width: 25%;">รายวิชา</td> <td style="width: 14%;">รหัสวิชา</td> <td style="width: 14%;">หน่วยกิต</td> <td style="width: 14%;">คะแนน</td> <td style="width: 14%;">GPA</td> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: left;">ภาษาไทย</td> <td>ท11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">คณิตศาสตร์</td> <td>ค11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">คณิตศาสตร์เพิ่มเติม</td> <td>ค11002</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">วิทยาศาสตร์</td> <td>ว11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">วิทยาศาสตร์เพิ่มเติม</td> <td>ว11002</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">สังคมศึกษา ศาสนาและวัฒนธรรม</td> <td>ส11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">สุขศึกษา</td> <td>พ11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">ภาษาอังกฤษ</td> <td>อ11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td style="text-align: left;">การงานอาชีพและเทคโนโลยี</td> <td>ง11001</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr> <td>1</td> <td>คอมพิวเตอร์</td> <td>ง11010</td> <td>1</td> <td>90</td> <td>4.00</td> <td></td> </tr> <tr style="font-weight: bold;"> <td colspan="3">รวม</td> <td>10</td> <td>920</td> <td>4.00</td> <td></td> </tr> <tr style="background-color:#e0e0e0; "> <td></td> <td >กิจกรรมพัฒนาผู้เรียน</td> <td>รหัสวิชา</td> <td>หน่วยกิต</td> <td>คะแนน</td> <td>ผลการประเมิน</td> <td></td> </tr> <tr> <td>1</td> <td >แนะแนว</td> <td>ก11001</td> <td>-</td> <td>-</td> <td>ผ่าน</td> <td></td> </tr> <tr> <td>2</td> <td >ลูกเสือ เนตรนาร</td> <td>ก11002</td> <td>-</td> <td>-</td> <td>ผ่าน</td> <td></td> </tr> <tr> <td>3</td> <td >ชุมนุมคอมพิวเตอร์</td> <td>ก11003</td> <td>-</td> <td>-</td> <td>ผ่าน</td> <td></td> </tr> <tr> <td>4</td> <td >กิจกรรมเพื่อสังคม</td> <td>ก11004</td> <td>-</td> <td>-</td> <td>ผ่าน</td> <td></td> </tr> <tr style="font-weight: bold;"> <td colspan="3">รวม</td> <td>-</td> <td>-</td> <td>ผ่าน</td> <td></td> </tr> </tbody> </table> </page> <page orientation="portrait"> <p class="text-bold" style="margin-left: 710px;font-size: 22px;margin-top: 25px;">ปพ.6</p> <br> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 10px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td colspan="3" style="width: 4%;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 6%">ที่</td> <td style="width: 65%;">คุณลักษณะอันพึงประสงค์</td> <td style="width: 24%;">ผลการประเมิน</td> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: left;">รักชาติ ศาสน์ กษัตริย์</td> <td>3</td> </tr> <tr> <td>2</td> <td style="text-align: left;">ซื่อสัตย์สุจริต</td> <td>3</td> </tr> <tr> <td>3</td> <td style="text-align: left;">มีวินัย</td> <td>3</td> </tr> <tr> <td>4</td> <td style="text-align: left;">ใฝ่เรียนรู้</td> <td>3</td> </tr> <tr> <td>5</td> <td style="text-align: left;">อยู่อย่างพอเพียง</td> <td>3</td> </tr> <tr> <td>6</td> <td style="text-align: left;">มุ่งมั่นในการทำงาน</td> <td>3</td> </tr> <tr> <td>7</td> <td style="text-align: left;">รักความเป็นไทย</td> <td>3</td> </tr> <tr> <td>8</td> <td style="text-align: left;">มีจิตสาธารณะ</td> <td>3</td> </tr> <tr style="font-weight: bold;"> <td colspan="2">สรุปผลการประเมิน</td> <td>3</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 35px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td colspan="3" style="width: 4%;">ผลการประเมินการอ่าน&nbsp;เขียน&nbsp;คิดวิเคราะห์</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 6%">ที่</td> <td style="width: 65%;">การอ่าน&nbsp;เขียน&nbsp;คิดวิเคราะห์</td> <td style="width: 24%;">ผลการประเมิน</td> </tr> </thead> <tbody> <tr> <td>1</td> <td style="text-align: left;">การอ่าน</td> <td>3</td> </tr> <tr> <td>2</td> <td style="text-align: left;">การเขียน</td> <td>3</td> </tr> <tr> <td>3</td> <td style="text-align: left;">การคิด วิเคราะห์</td> <td>3</td> </tr> <tr style="font-weight: bold;"> <td colspan="2">สรุปผลการประเมิน</td> <td>3</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 18px;margin-left:50px;border: 1px solid black;margin-top: 35px;"> <thead style="font-weight: bold;"> <tr style="background-color: #e0e0e0;"> <td colspan="6" style="width: 4%;">สรุปผลการประเมิน</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 6%">ผลการเรียนเฉลี่ย</td> <td style="width: 6%">ผลการเรียนเฉลี่ย สะสม</td> <td style="width: 6%;">ลำดับที่<br>ในห้องเรียน</td> <td style="width: 6%;">กิจกรรมพัฒนา ผู้เรียน</td> <td style="width: 6%;">คุณลักษณะอันพึง ประสงค์</td> <td style="width: 6%;">อ่าน&nbsp;เขียน คิดวิเคราะห์</td> </tr> </thead> <tbody> <tr> <td style="width: 16%">4.00</td> <td style="width: 16%">4.00</td> <td style="width: 16%">1</td> <td style="width: 16%">ผ่าน</td> <td style="width: 16%">3</td> <td style="width: 16%">3</td> </tr> </tbody> </table> <div style="margin-left: 120px;margin-top: 40px;font-size: 16px;"> <p>.................................................................ครูประจำชั้น </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:160px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 420px;margin-top: -74px;font-size: 16px;"> <p>.................................................................ผู้ปกครอง </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:170px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 420px;margin-top: 55px;font-size: 16px;"> <p>.................................................................ผู้อำนวยการ</p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> </page> <file_sep>/js/event.js $(document).delegate('.btn-lang', 'click', function(event) { var lang = $(this).attr('data-id'); var formData = new Array(); formData.push({ "name": "action", "value": "change_lang" }); formData.push({ "name": "lang", "value": lang }); $.post('modules/lang/process.php', formData, function(data, textStatus, xhr) { window.location.reload(); }); });<file_sep>/modules/mobile_api/host/login.php <?php @session_start(); require_once('config.php'); require_once('src/database.php'); include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $condition = false; $num= $class_data->rows[0]['num']; $json = json_decode(file_get_contents('php://input'), true); $txt_username=$json['username']; $txt_password=$json['<PASSWORD>']; $chk_int=is_numeric($json['username']); $chk_pass=strlen($txt_password); if (!empty($txt_username) && !empty($txt_password)) { if ($chk_int==true ) { if ($chk_pass==8) { $day=substr($txt_password, 0, 2); $month=substr($txt_password, 2, 2); $year=substr($txt_password, 4,4); $year_set=$year-543; $pass_birth=$year_set.'-'.$month.'-'.$day; //$response['pass_birth'] = $pass_birth; $sql = " SELECT count(std_ID) as data_total FROM tbl_student WHERE std_ID = '{$txt_username}' AND birthday = '$pass_birth'"; $class_data->sql = $sql; $class_data->select(); $class_data->setRows(); $dataidtotal = (int)$class_data->rows[0]['data_total']; $condition = ($dataidtotal > 0) ? true : false; } } } if ($condition == true) { $day=substr($txt_password, 0, 2); $month=substr($txt_password, 2, 2); $year=substr($txt_password, 4,4); $year_set=$year-543; $pass_birth=$year_set.'-'.$month.'-'.$day; $sql = " SELECT std_ID,name_title,fname,lname,room,class_level FROM tbl_student WHERE std_ID = '{$txt_username}' AND birthday = '$pass_birth'"; $class_data->sql = $sql; $class_data->select(); $class_data->setRows(); $data_res['status']=1; $data_res['std_ID']=$class_data->rows[0]['std_ID']; $name_title_data=$class_data->rows[0]['name_title']; if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } $fname=$class_data->rows[0]['fname']; $lname=$class_data->rows[0]['lname']; $data_res['name']=$name_title.$fname.' '.$lname; $class_level_data=$class_data->rows[0]['class_level']; if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } $data_res['class_level']=$class_level; $data_res['room']=$class_data->rows[0]['room']; }else{ $data_res['status']=0; } echo json_encode($data_res); ?> <file_sep>/modules/login/process.php <?php @ob_start(); @session_start(); // require_once('../../config.php'); require_once('../../init.php'); ##CLASS_DB_CONNECT## $db = new Databases(); ##CLASS_DB_CONNECT## $response = array(); $condition = false; $txt_username = $_REQUEST['username']; $txt_password = $_REQUEST['password']; $chk_int=is_numeric($_REQUEST['username']); if (!empty($txt_username) && !empty($txt_password)) { if ($chk_int==true) { $day=substr($txt_password, 0, 2); $month=substr($txt_password, 2, 2); $year=substr($txt_password, 4,4); $year_set=$year-543; $pass_birth=$year_set.'-'.$month.'-'.$day; //$response['pass_birth'] = $pass_birth; $sql = " SELECT count(std_ID) as data_total FROM tbl_student WHERE std_ID = '{$txt_username}' AND birthday = '$pass_birth'"; }else{ $sql = " SELECT count(positionID) as data_total FROM tbl_regis_teacher WHERE username = '{$txt_username}' AND password = MD5('{$txt_password}') AND status_alive=1"; } $db->sql = $sql; $db->select(); $db->setRows(); $dataidtotal = (int)$db->rows[0]['data_total']; $condition = ($dataidtotal > 0) ? true : false; } if ($condition == true) { if ($chk_int==true) { $day=substr($txt_password, 0, 2); $month=substr($txt_password, 2, 2); $year=substr($txt_password, 4,4); $year_set=$year-543; $pass_birth=$year_set.'-'.$month.'-'.$day; $sql = " SELECT std_ID,fname,lname FROM tbl_student WHERE std_ID = '{$txt_username}' AND birthday = '$pass_birth' "; $db->sql = $sql; $db->select(); $db->setRows(); $_SESSION['ss_user_id'] = $db->rows[0]['std_ID']; $_SESSION['ss_fname'] = $db->rows[0]['fname']; $_SESSION['ss_lname'] = $db->rows[0]['lname']; $_SESSION['ss_status_std'] = 1; $response['status'] = '0'; }else{ $sql = " SELECT DataID,positionID,fname_th,lname_th,email,status,status_rang FROM tbl_regis_teacher WHERE username = '{$txt_username}' AND password = MD5('{<PASSWORD>}') AND status_alive=1"; $db->sql = $sql; $db->select(); $db->setRows(); $_SESSION['ss_user_id'] = $db->rows[0]['DataID']; $_SESSION['ss_username'] = $db->rows[0]['positionID']; $_SESSION['ss_fname_th'] = $db->rows[0]['fname_th']; $_SESSION['ss_lname_th'] = $db->rows[0]['lname_th']; $_SESSION['ss_email'] = $db->rows[0]['email']; $_SESSION['ss_status'] = $db->rows[0]['status']; $_SESSION['ss_status_rang'] = $db->rows[0]['status_rang']; $response['status'] = '1'; } $response['success'] = '1'; $response['error'] = ''; }else{ $response['success'] = '0'; $response['error'] = " <strong>Username or Password incorrect</strong>"; } echo json_encode($response); ?><file_sep>/src/#class.userauthen.php <?php // API authen class UserAuthen { public $DB; public $BY; public function __construct() { $this->DB = new Databases(); $this->BY = ($_SESSION['ssADMIN_ID'])? $_SESSION['ssADMIN_ID']: null; } public function __escape($inputVar) { return mysql_real_escape_string(addslashes(htmlentities($inputVar, ENT_QUOTES))); } public function login( $user=null, $pass=null ) { $where = ' where '; $where .= ' a.username = "'.self::__escape($user).'" and a.password = "'.self::__escape($pass).'" and a.status=1 '; $this->DB->sql = 'select a.*,b.role_name from ath_users as a left join ath_roles as b on (a.role_id=b.role_id) '. $where .' limit 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ return $result[0]; } return null; } public function task( $task_key=null, $user_id=null ) { $tasks = self::ath_tasks($task_key); $user_id = (!$user_id)? $this->BY: $user_id; $where = ' where '; $where .= ' task_id = "'.self::__escape($tasks['task_id']).'" and user_id = "'.self::__escape($user_id).'" '; $this->DB->sql = 'select * from ath_user_reletion_tasks '. $where .' limit 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ return true; } else{ return false; } } public function menu_authen() { $this->DB->sql = 'SELECT fun_id FROM ath_tasks as a LEFT JOIN ath_user_reletion_tasks as b on(a.task_id=b.task_id) WHERE b.user_id='.$this->BY.' GROUP BY a.fun_id '; $this->DB->select(); $result = $this->DB->getRows(); foreach( $result as $rs ){ $data[] = $rs['fun_id']; } return $data; /* $result = self::ath_main_function(); if(!$result){ return false; } // Result foreach( $result as $rs ){ $data[$rs['fun_id']] = $rs['fun_name']; } return $data; */ } public function view_tasks() { $result = self::ath_tasks(); if(!$result){ return false; } // Result foreach( $result as $rs ){ $data[$rs['task_key']] = $rs['task_description']; } return $data; } /* public function logout( $url=null ) { // unset unset($_SESSION); // location if($url){ header('location:'.$url); } return true; } */ public function update_last_login($id) { if($id){ /* $update = array(); $update['mdate'] = DATETIME; $where = array(); $where['user_id'] = $id; */ $this->DB->sql = 'UPDATE ath_users set mdate="'.DATETIME.'" where user_id='.$id; $this->DB->update(); //$this->DB->update( 'ath_users', $update, $where); } } // ================================================================================== /* protected */ protected function ath_main_function() { $this->DB->sql = 'select * from ath_main_function where status=1 '; $this->DB->select(); $result = $this->DB->getRows(); return $result; } protected function ath_tasks($key=null) { $where = null; if($key){ $where = ' where '; $where .= ' task_key = "'.self::__escape($key).'" '; } $this->DB->sql = 'select * from ath_tasks '. $where; $this->DB->select(); $result = $this->DB->getRows(); if($key){ return $result[0]; } else{ return $result; } } } <file_sep>/modules/conclusion/class_modules/back/learing_resualt_final_m.php <?php class ClassData extends Databases { public function get_head($class_level,$room,$year,$term){ $this->sql ="SELECT DISTINCT(sub_ID),courseID FROM tbl_sub_pp6 WHERE pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room' AND term='$term' AND year='$year' ) ORDER BY sub_ID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $courseID= $value['courseID']; $data_response['head_list'].=' <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> '.$courseID.' </div> </th> '; $data_response['sum_100_list'].=' <th style="text-align: center;">100</th> '; } $data_response['head_list'].=' <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;margin-right:-12px;margin-left:-12px"> คุณลักษณฯ </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;margin-right:-12px;margin-left:-12px"> อ่าน เขียนฯ </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> GPA </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> อันดับที่ </div> </th> '; return $data_response; } public function get_list_conclusion($pp6_id){ $data_response = array(); $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE pp6_ID=$pp6_id "; $this->select(); $this->setRows(); $score_by_unit_row=0; $unit_count=0; $score_desirable_count=0; $score_rtw_count=0; $count_all=0; $status=0; $count_dev_course=0; foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $score_total= $value['score_total']; $unit= $value['unit']; $status_course= $value['status']; $score_attend= $value['score_attend']; $score_desirable = number_format($value['score_desirable'],0); $score_rtw = number_format($value['score_rtw'],0); if ($status_course==1) { if($score_total==-1){ $grade_set='ร'; }else{ $grade_set=$this->get_grade($score_total); $score_by_unit_row=$score_by_unit_row+($grade_set*$unit); $score_desirable_count=$score_desirable_count+$score_desirable; $score_rtw_count=$score_rtw_count+$score_rtw; } $unit_count=$unit_count+$unit; $count_all++; }elseif($status_course==2){ $count_dev_course++; if ($score_attend==-1) { $status++; } } } $find_percentage=number_format($score_by_unit_row/$unit_count,2); $find_desirable_average=number_format($score_desirable_count/$count_all,0); $find_rtw_average=number_format($score_rtw_count/$count_all,0); $data_response['percentage']=$find_percentage; $data_response['desirable_average']=$find_desirable_average; $data_response['rtw_average']=$find_rtw_average; $data_response['status']=$status; $data_response['count_dev_course']=$count_dev_course; return $data_response; } public function get_conclusion($class_level,$room,$year,$term,$image_logo,$footer_text_detail,$footer_text_cen){ $data_response = array(); $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_pp6 WHERE term='$term' AND year='$year' AND room='$room' AND class_level='$class_level' "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; $this->sql ="SELECT * FROM tbl_pp6 WHERE term='$term' AND year='$year' AND room='$room' AND class_level='$class_level' "; $this->select(); $this->setRows(); $data_000_100=0; $data_101_150=0; $data_151_200=0; $data_201_250=0; $data_251_300=0; $data_301_350=0; $data_351_400=0; $eva_not_pass=0; $desirable_3=0; $desirable_2=0; $desirable_1=0; $desirable_0=0; $average_3=0; $average_2=0; $average_1=0; $average_0=0; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $list_conclusion=$this->get_list_conclusion($DataID); if ($list_conclusion['percentage']<=1) { $data_000_100++; }elseif($list_conclusion['percentage']<=1.50){ $data_101_150++; }elseif($list_conclusion['percentage']<=2){ $data_151_200++; }elseif($list_conclusion['percentage']<=2.50){ $data_201_250++; }elseif($list_conclusion['percentage']<=3){ $data_251_300++; }elseif($list_conclusion['percentage']<=3.50){ $data_301_350++; }elseif($list_conclusion['percentage']<=4){ $data_351_400++; } if ($list_conclusion['status']>0) { $eva_not_pass++; } if ($list_conclusion['desirable_average']==3) { $desirable_3++; }elseif($list_conclusion['desirable_average']==2){ $desirable_2++; }elseif($list_conclusion['desirable_average']==1){ $desirable_1++; }elseif($list_conclusion['desirable_average']==0){ $desirable_0++; } if ($list_conclusion['rtw_average']==3) { $average_3++; }elseif($list_conclusion['rtw_average']==2){ $average_2++; }elseif($list_conclusion['rtw_average']==1){ $average_1++; }elseif($list_conclusion['rtw_average']==0){ $average_0++; } } $percen_000_100=number_format(($data_000_100*100)/$num_row,2); $percen_101_150=number_format(($data_101_150*100)/$num_row,2); $percen_151_200=number_format(($data_151_200*100)/$num_row,2); $percen_201_250=number_format(($data_201_250*100)/$num_row,2); $percen_251_300=number_format(($data_251_300*100)/$num_row,2); $percen_301_350=number_format(($data_301_350*100)/$num_row,2); $percen_351_400=number_format(($data_351_400*100)/$num_row,2); $percen_desirable_3=number_format(($desirable_3*100)/$num_row,2); $percen_desirable_2=number_format(($desirable_2*100)/$num_row,2); $percen_desirable_1=number_format(($desirable_1*100)/$num_row,2); $percen_desirable_0=number_format(($desirable_0*100)/$num_row,2); $percen_average_3=number_format(($average_3*100)/$num_row,2); $percen_average_2=number_format(($average_2*100)/$num_row,2); $percen_average_1=number_format(($average_1*100)/$num_row,2); $percen_average_0=number_format(($average_0*100)/$num_row,2); $eva_ok_pass=$num_row-$eva_not_pass; $percen_eva_not_pass=number_format(($eva_not_pass*100)/$num_row,2); $percen_eva_ok_pass=number_format(($eva_ok_pass*100)/$num_row,2); if ($count_dev_course==0) { $eva_not_pass='-'; $eva_ok_pass='-'; $percen_eva_not_pass='-'; $percen_eva_ok_pass='-'; } $data_response=' <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th colspan="12" class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >สรุปการประเมินผลการเรียน</div> </th> </tr> <tr class="text-middle"> <th style="width: 16%;height: 0px;text-align: center;"> ผลการเรียน (GPA) </th> <th style="width: 8%;height: 0px;text-align: center;"> 3.51-4.00 </th> <th style="width: 8%;height: 0px;text-align: center;"> 3.01-3.50 </th> <th style="width: 8%;height: 0px;text-align: center;"> 2.51-3.00 </th> <th style="width: 8%;height: 0px;text-align: center;"> 2.01-2.50 </th> <th style="width: 8%;height: 0px;text-align: center;"> 1.51-2.00 </th> <th style="width: 8%;height: 0px;text-align: center;"> 1.01-1.50 </th> <th style="width: 8%;height: 0px;text-align: center;"> 0.00-1.00 </th> <th style="width: 7%;height: 0px;text-align: center;"> รวม </th> <th style="width: 7%;height: 0px;text-align: center;"> ผ </th> <th style="width: 7%;height: 0px;text-align: center;"> มผ </th> <th style="width: 7%;height: 0px;text-align: center;"> รวม </th> </tr> </thead> <tbody > <tr class="text-middle"> <td style="width: 16%;height: 0px;text-align: center;"> จำนวน </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_351_400.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_301_350.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_251_300.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_201_250.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_151_200.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_101_150.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$data_000_100.' </td> <td style="width: 7%;height: 0px;text-align: center;"> 22 </td> <td style="width: 7%;height: 0px;text-align: center;"> '.$eva_ok_pass.' </td> <td style="width: 7%;height: 0px;text-align: center;"> '.$eva_not_pass.' </td> <td style="width: 7%;height: 0px;text-align: center;"> '.$num_row.' </td> </tr> <tr class="text-middle"> <td style="width: 16%;height: 0px;text-align: center;"> ร้อยละ </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_351_400.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_301_350.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_251_300.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_201_250.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_151_200.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_101_150.' </td> <td style="width: 8%;height: 0px;text-align: center;"> '.$percen_000_100.' </td> <td style="width: 7%;height: 0px;text-align: center;"> 100 </td> <td style="width: 7%;height: 0px;text-align: center;"> '.$percen_eva_ok_pass.' </td> <td style="width: 7%;height: 0px;text-align: center;"> '.$percen_eva_not_pass.' </td> <td style="width: 7%;height: 0px;text-align: center;"> 100.00 </td> </tr> </tbody> </table> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;"> <thead style="border-top: none;"> <tr class="text-middle" style="border-top:none;"> <th colspan="6" class="rotate" style="height: 0px;text-align: center;border-top:none;"> <div >คุณลักษณะอันพึงประสงค์</div> </th> <th colspan="5" class="rotate" style="height: 0px;text-align: center;border-top:none;"> <div >อ่าน เขียน คิดวิเคราะห์</div> </th> </tr> <tr class="text-middle;"> <th style="width: 12.8%;height: 0px;text-align: center;"> ผลการประเมิน </th> <th style="width: 6.5%;height: 0px;text-align: center;"> 3 </th> <th style="width: 6.5%;height: 0px;text-align: center;"> 2 </th> <th style="width: 6.5%;height: 0px;text-align: center;"> 1 </th> <th style="width: 6.5%;height: 0px;text-align: center;"> 0 </th> <th style="width: 6.6%;height: 0px;text-align: center;"> รวม </th> <th style="width: 7%;height: 0px;text-align: center;"> 3 </th> <th style="width: 7%;height: 0px;text-align: center;"> 2 </th> <th style="width: 7%;height: 0px;text-align: center;"> 1 </th> <th style="width: 7%;height: 0px;text-align: center;"> 0 </th> <th style="width: 7%;height: 0px;text-align: center;"> รวม </th> </tr> </thead> <tbody > <tr class="text-middle"> <td > จำนวน </td> <td > '.$desirable_3.' </td> <td > '.$desirable_2.' </td> <td > '.$desirable_1.' </td> <td > '.$desirable_0.' </td> <td > '.$num_row.' </td> <td > '.$average_3.' </td> <td > '.$average_2.' </td> <td > '.$average_1.' </td> <td > '.$average_0.' </td> <td > '.$num_row.' </td> </tr> <tr class="text-middle"> <td > ร้อยละ </td> <td > '.$percen_desirable_3.' </td> <td > '.$percen_desirable_2.' </td> <td > '.$percen_desirable_1.' </td> <td > '.$percen_desirable_0.' </td> <td > 100.00 </td> <td > '.$percen_average_3.' </td> <td > '.$percen_average_2.' </td> <td > '.$percen_average_1.' </td> <td > '.$percen_average_0.' </td> <td > 100.00 </td> </tr> </tbody> </table> '; return $data_response; } public function get_course_list($pp6_id,$i,$year_data,$term,$room,$class_level_data,$std_ID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE pp6_ID=$pp6_id ORDER BY sub_ID ASC "; $this->select(); $this->setRows(); $score_by_unit_row=0; $unit_count=0; $score_desirable_count=0; $score_rtw_count=0; $count_all=0; $status=0; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $score_total= $value['score_total']; $unit= $value['unit']; $status_course= $value['status']; $score_attend= $value['score_attend']; $score_desirable = number_format($value['score_desirable'],0); $score_rtw = number_format($value['score_rtw'],0); if ($status_course==1) { if($score_total==-1){ $grade_set='ร'; $status++; }else{ $grade_set=$this->get_grade($score_total); $score_by_unit_row=$score_by_unit_row+($grade_set*$unit); $score_desirable_count=$score_desirable_count+$score_desirable; $score_rtw_count=$score_rtw_count+$score_rtw; } if ($i==1) { $data_response['row_list'].=' <td style="width: 1%;">'.$grade_set.'</td> '; }elseif($i>1){ $data_response['row_list'].=' <td style="width: 2.5%;">'.$grade_set.'</td> '; }elseif($i==-1){ $data_response['row_list'].=' <td>'.$grade_set.'</td> '; } $unit_count=$unit_count+$unit; }elseif($status_course==2){ if ($score_attend==1) { $grade_set='ผ'; }else{ $grade_set='มผ'; $attend_not_pass_count++; } if ($i==1) { $data_response['row_list'].=' <td style="width: 1%;">'.$grade_set.'</td> '; }elseif($i>1){ $data_response['row_list'].=' <td style="width: 2.5%;">'.$grade_set.'</td> '; }elseif($i==-1){ $data_response['row_list'].=' <td>'.$grade_set.'</td> '; } $score_desirable_count=$score_desirable_count+$score_desirable; $score_rtw_count=$score_rtw_count+$score_rtw; } $count_all++; } $find_desirable_average=number_format($score_desirable_count/$count_all,0); $find_rtw_average=number_format($score_rtw_count/$count_all,0); $find_percentage=number_format($score_by_unit_row/$unit_count,2); $find_position=$this->find_position($year_data,$term,$class_level_data,$room); arsort($find_position); $arrayValuePosition=$this->arrayValuePositionNew($find_position,$std_ID); if ($i==1) { $data_response['row_list'].=' <td style="width: 1%;">'.$find_desirable_average.'</td> <td style="width: 1%;">'.$find_rtw_average.'</td> <td style="width: 1%;">'.$find_percentage.'</td> <td style="width: 1%;">'.$arrayValuePosition.'</td> '; }elseif($i>1){ $data_response['row_list'].=' <td style="width: 2%;">'.$find_desirable_average.'</td> <td style="width: 2%;">'.$find_rtw_average.'</td> <td style="width: 2%;">'.$find_percentage.'</td> <td style="width: 2%;">'.$arrayValuePosition.'</td> '; }elseif($i==-1){ $data_response['row_list'].=' <td>'.$find_desirable_average.'</td> <td>'.$find_rtw_average.'</td> <td>'.$find_percentage.'</td> <td>'.$arrayValuePosition.'</td> '; } $data_response['grade']=$find_percentage; $data_response['status']=$status; $data_response['ddd']=2; return $data_response; } public function find_position($year_data,$term,$class_level_data,$room){ $data_response = array(); $this->sql ="SELECT distinct(tbl_pp6.std_ID) as std_pp6_id,tbl_pp6.DataID as pp6_id FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_pp6.year='$year_data' AND tbl_pp6.term='$term' AND tbl_pp6.room='$room' AND tbl_pp6.class_level='$class_level_data' AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $find_gpa_sum=0; $score_final_count=0; foreach($this->rows as $key => $value) { $std_pp6_id=$value['std_pp6_id']; $pp6_id=$value['pp6_id']; $data_big_std= $this->get_data_big_std($std_pp6_id,$pp6_id); $test[$std_pp6_id] = $data_big_std; } return $test; } public function get_data_big_std($std_pp6_id,$pp6_id){ $this->sql ="SELECT unit,score_total FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); $find_row_sum=0; foreach($this->rows as $key => $value) { $unit=$value['unit']; $score_total=$value['score_total']; $grade= $this->get_grade($score_total); $find_row_sum=$find_row_sum+($unit*$grade); } $this->sql ="SELECT SUM(unit) as unit_sum FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $unit_sum=$this->rows[0]['unit_sum']; return $find_row_sum/$unit_sum; } public function arrayValuePositionNew($find_position,$std_ID){ $result = array(); $pos = $real_pos = 0; $prev_score = -1; foreach ($find_position as $exam_n => $score) { $real_pos += 1;// Natural position. $pos = ($prev_score != $score) ? $real_pos : $pos;// If I have same score, I have same position in ranking, otherwise, natural position. $result[$exam_n] = array( "score" => $score, "position" => $pos, "exam_no" => $exam_n ); $prev_score = $score;// update last score. } return $result[$std_ID]["position"]; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_count_std($class_level,$room,$year,$term){ $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room' AND term='$term' AND year='$year' "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_final_data_m($class_level,$room,$year,$term,$image_logo,$footer_text_detail,$footer_text_cen){ $conclusion=$this->get_conclusion($class_level,$room,$year,$term,$image_logo,$footer_text_detail,$footer_text_cen); $mid_head=$this->get_head($class_level,$room,$year,$term); $count_std=$this->get_count_std($class_level,$room,$year,$term); if ($count_std<=30) { $set_loop_html=2; }else{ $set_loop_html=3; } if ($set_loop_html==1) { $loop_data=$this->get_loop_data($class_level,$room,$year,$term); $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 10px;font-size:18px"> <img class="logo-print-size" src="'.$image_logo.'"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 20px;">ระดับชั้น <span style="font-weight: normal;">มัธยมศึกษาปีที่ '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">ห้อง <span style="font-weight: normal;">'.$room.'</span> </span> <span style="margin-right: 20px;">ภาคเรียนที่ <span style="font-weight: normal;">'.$term.'</span> </span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> <p style="margin-top: 20px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th style="width: 30%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> </thead> <tbody > '.$loop_data['loop_all'].' </tbody> </table> </page> </div> <div style="page-break-after:always;"> <page > '.$footer_text_detail.' </page> </div> '; }else{ if ($set_loop_html==2) { for ($i=1; $i <=$set_loop_html ; $i++) { $loop_data=$this->get_loop_data($class_level,$room,$year,$term,$i,$set_loop_html); if ($i==1) { $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:18px"> <img class="logo-print-size" src="'.$image_logo.'"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 20px;">ระดับชั้น <span style="font-weight: normal;">มัธยมศึกษาปีที่ '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">ห้อง <span style="font-weight: normal;">'.$room.'</span> </span> <span style="margin-right: 20px;">ภาคเรียนที่ <span style="font-weight: normal;">'.$term.'</span> </span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> <p style="margin-top: 20px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th style="width: 30%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> </thead> <tbody > '.$loop_data['loop_all'].' </tbody> </table> </page> </div> '; }else{ $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <tbody > '.$loop_data['loop_all'].' </tbody> </table> '.$footer_text_detail.' '.$conclusion.' '.$footer_text_cen.' </page> </div> '; } } }else{ for ($i=1; $i <=$set_loop_html ; $i++) { $loop_data=$this->get_loop_data($class_level,$room,$year,$term,$i,$set_loop_html); if ($i==1) { $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:18px"> <img class="logo-print-size" src="'.$image_logo.'"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 20px;">ระดับชั้น <span style="font-weight: normal;">มัธยมศึกษาปีที่ '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">ห้อง <span style="font-weight: normal;">'.$room.'</span> </span> <span style="margin-right: 20px;">ภาคเรียนที่ <span style="font-weight: normal;">'.$term.'</span> </span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> <p style="margin-top: 20px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th style="width: 30%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> </thead> <tbody > '.$loop_data['loop_all'].' </tbody> </table> '.$footer_text_detail.' '.$conclusion.' '.$footer_text_cen.' </page> </div> '; }elseif($i==2){ $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <tbody > '.$loop_data['loop_all'].' </tbody> </table> '.$footer_text_detail.' '.$conclusion.' '.$footer_text_cen.' </page> </div> '; }elseif($i==3){ $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <tbody > '.$loop_data['loop_all'].' </tbody> </table> '.$footer_text_detail.' '.$conclusion.' '.$footer_text_cen.' </page> </div> '; } } } } return $data_response; } public function get_loop_data($class_level,$room,$year,$term,$i,$set_loop_html){ $data_response = array(); if ($i!='') { if ($set_loop_html<3) { if ($i==1) { $find_start=0; $find_end=20; }elseif($i==2){ $find_start=20; $find_end=20; } }else{ if ($i==1) { $find_start=0; $find_end=18; }elseif($i==2){ $find_start=18; $find_end=25; }else{ $find_start=43; $find_end=25; } } $this->sql ="SELECT * FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room' AND term='$term' AND year='$year' ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END LIMIT $find_start,$find_end "; $this->select(); $this->setRows(); $number=$find_start+1; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $std_ID= $value['std_ID']; $name_title_set= $value['name_title']; $name_title=$this->get_name_title($name_title_set); $fname=$value['fname']; $lname=$value['lname']; $class_level=$value['class_level']; $name=$name_title.$fname.' '.$lname; $course_list=$this->get_course_list($DataID,$i,$year,$term,$room,$class_level,$std_ID); $data_response['loop_all'].=' <tr> <td style="width: 3%;">'.$number.'</td> <td style="width: 5%;">'.$std_ID.'</td> <td style="text-align:left;padding-left:10px;width: 28%;">'.$name.'</td> '.$course_list['row_list'].' </tr> '; $number++; } }else{ $this->sql ="SELECT * FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room' AND term='$term' AND year='$year' ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $number=1; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $std_ID= $value['std_ID']; $name_title_set= $value['name_title']; $name_title=$this->get_name_title($name_title_set); $fname=$value['fname']; $lname=$value['lname']; $class_level=$value['class_level']; $name=$name_title.$fname.' '.$lname; $course_list=$this->get_course_list($DataID,-1,$year,$term,$room,$class_level,$std_ID); $data_response['loop_all'].=' <tr> <td>'.$number.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:10px;">'.$name.'</td> '.$course_list['row_list'].' </tr> '; $number++; } } return $data_response; } public function get_data_list($class_level,$room_data,$term_data,$year_data){ if ($term_data=='mid') { $this->sql ="SELECT DISTINCT(room) as room,class_level,year FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $term= 'กลางปี'; $year= $value['year']; $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$room.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result.php?class_level='.$class_level.'&room='.$room.'&term=mid&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } }else{ $this->sql ="SELECT DISTINCT(room) as room,class_level,term,year FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term='ปลายปี'; }else{ $term= $value['term']; } $year= $value['year']; $data_response.=' <tr class="text-table-center"> <td><input id="checkbox_all" type="checkbox"></td> <td>'.$class_label.'</td> <td>'.$room.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_final.php?class_level='.$class_level.'&room='.$room.'&term=mid&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } } return json_encode($data_response); } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_registed_course ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/summary/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_POST['acc_action']) and $_POST['acc_action'] == "export_data_mid"){ $data_val = $_POST['data_val']; $data_term_set = $_POST['data_term_set']; echo $class_data->export_data_mid($data_val,$data_term_set); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "export_data"){ $data_val = $_POST['data_val']; $data_term_set = $_POST['data_term_set']; echo $class_data->export_data($data_val,$data_term_set); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year_text"){ echo $class_data->get_year_text(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_dev_summary"){ $coures_id_list_val=$_GET['coures_id_list_val']; $room_search=$_GET['room_search']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_dev_summary($coures_id_list_val,$room_search,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_grade_summary"){ $coures_id_list_val=$_GET['coures_id_list_val']; $room_search=$_GET['room_search']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_grade_summary($coures_id_list_val,$room_search,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_detail"){ $coures_id_list=$_GET['coures_id_list']; $room_search=$_GET['room_search']; echo $class_data->search_course_detail($coures_id_list,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_class_level"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_class_level($coures_id_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_mid"){ echo $class_data->get_mid(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list"){ $ss_status=$_SESSION['ss_status']; if ($ss_status==2) { $data_term_search=$_GET['data_term_search']; $data_year_search=$_GET['data_year_search']; echo $class_data->get_coures_id_list_admin($data_term_search,$data_year_search); }else{ echo $class_data->get_coures_id_list(); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list_added"){ echo $class_data->get_coures_id_list_added(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "un_export"){ $data_id=$_GET['data_id']; $data_term=$_GET['data_term']; $data_year=$_GET['data_year']; $data_room=$_GET['data_room']; $data_class=$_GET['data_class']; echo $class_data->un_export($data_id,$data_term,$data_year,$data_room,$data_class); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list_edit"){ $data_term_search=$_GET['data_term_search']; $data_year_search=$_GET['data_year_search']; echo $class_data->get_coures_id_list_edit($data_term_search,$data_year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); }<file_sep>/modules/add_delete_course/class_modules.php <?php class ClassData extends Databases { public function get_department($department_data){ if ($department_data=="1") { $department='dep_1'; }elseif($department_data=="2"){ $department='dep_2'; }elseif($department_data=="3"){ $department='dep_3'; }elseif($department_data=="31"){ $department='dep_31'; }elseif($department_data=="4"){ $department='dep_4'; }elseif($department_data=="41"){ $department='dep_41'; }elseif($department_data=="42"){ $department='dep_42'; }elseif($department_data=="43"){ $department='dep_43'; }elseif($department_data=="5"){ $department='dep_5'; }elseif($department_data=="6"){ $department='dep_6'; }elseif($department_data=="7"){ $department='dep_7'; }elseif($department_data=="71"){ $department='dep_71'; }elseif($department_data=="8"){ $department='dep_8'; }elseif($department_data=="9"){ $department='dep_9'; }elseif($department_data=="10"){ $department='dep_10'; }elseif($department_data=="11"){ $department='dep_11'; }elseif($department_data=="12"){ $department='dep_12'; } return $department; } public function get_unit($unit_data){ if ($unit_data=="0.5") { $unit='05'; }elseif($unit_data=="1.0"){ $unit='10'; }elseif($unit_data=="1.5"){ $unit='15'; }elseif($unit_data=="2.0"){ $unit='20'; }elseif($unit_data=="2.5"){ $unit='25'; }elseif($unit_data=="3.0"){ $unit='30'; }elseif($unit_data=="3.5"){ $unit='35'; }elseif($unit_data=="4.0"){ $unit='40'; }elseif($unit_data=="4.5"){ $unit='45'; }elseif($unit_data=="5.0"){ $unit='50'; }elseif($unit_data=="5.5"){ $unit='55'; }elseif($unit_data=="6.0"){ $unit='60'; } return $unit; } public function getdata_edit($data_id){ $data_response = array(); $sql = "SELECT * FROM tbl_add_delete_course WHERE DataID=$data_id "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['data_id_course']=$this->rows[0]['DataID']; $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['class_level']=$this->rows[0]['class_level']; $unit_data=$this->rows[0]['unit']; $data_response['unit']=$this->get_unit($unit_data); $department_data=$this->rows[0]['department']; $data_response['department']=$this->get_department($department_data); $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $data_response['status_form']=$this->rows[0]['status_form']; return json_encode($data_response); } public function update_data($update,$data_id_course){ $this->sql = "UPDATE tbl_add_delete_course SET ".implode(",",$update)." WHERE DataID='".$data_id_course."'"; $this->query(); } public function get_data_delete($data_val){ $arr_id = explode(",", $data_val); $num=0; for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="DELETE FROM tbl_add_delete_course WHERE DataID = {$arr_id[$i]}"; $this->query(); $num=$num+$i; } return $num; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_data($arr_search_val){ $data_response = array(); $sql_condition = " DataID > 0 "; $status = $arr_search_val['status']; $courseID_search = $arr_search_val['courseID_search']; $department_search = $arr_search_val['department_search']; $class_level_search = $arr_search_val['class_level_search']; if ($status!=1) { if (isset($courseID_search) && $courseID_search != "") { $sql_condition .= " AND ( courseID LIKE '%{$courseID_search}%') "; } if (isset($department_search) && $department_search != "") { $sql_condition .= " AND ( department = '$department_search') "; } if (isset($class_level_search) && $class_level_search != "") { $sql_condition .= " AND ( class_level = '$class_level_search') "; } }else{ if (isset($courseID_search) && $courseID_search != "") { $sql_condition .= " AND ( courseID LIKE '%{$courseID_search}%') "; } } $sql = "SELECT count(*) as num_row_count FROM tbl_add_delete_course WHERE $sql_condition ORDER BY DataID DESC "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row_count=$this->rows[0]['num_row_count']; $sql = "SELECT * FROM tbl_add_delete_course WHERE $sql_condition ORDER BY DataID DESC "; $this->sql = $sql; $this->select(); $this->setRows(); if ($num_row_count!=0) { foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $courseID= $value['courseID']; $name= $value['name']; $class_level_data= $value['class_level']; $class_level=$this->get_class_level($class_level_data); $unit= $value['unit']; if ($unit==0.0 || $unit==9.9 ) { $unit="-"; }else{ $unit=$unit; } $hr_learn= $value['hr_learn']; $data_response['table_list'].=' <tr> <td style="text-align:center;"> <input class="checkbox_data" type="checkbox" value="'.$DataID.'" name="checkbox_delete[]" id="checkbox'.$DataID.'"> </td> <td style="text-align:left;padding-left:7%;">'.$courseID.'</td> <td style="text-align:left;padding-left:7%;">'.$name.'</td> <td style="text-align:center;">'.$unit.'</td> <td style="text-align:center;">'.$hr_learn.'</td> <td style="text-align:center;">'.$class_level.'</td> <td style="text-align:center;"> <span data-id="'.$DataID.'" class="glyphicon glyphicon glyphicon-edit edit-icon-table btn_getdata_edit" aria-hidden="true" data-toggle="modal" data-target="#modalEdit"></span> </td> </tr> '; } }else{ $data_response['table_list'].=''; } return json_encode($data_response); } public function insert_data($insert){ $this->sql = "INSERT INTO tbl_add_delete_course(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $new_id = $this->insertID(); } }<file_sep>/modules/maneger_student/index.js var opPage = 'maneger_student'; $(document).ready(function() { btn_data_year_search_student(); }); $(document).delegate('#btn_name_id_search', 'click', function(event) { get_data(); }); $(document).delegate('#btn_data_year_search_student', 'click', function(event) { btn_data_year_search_student(); }); function btn_data_year_search_student() { var formData = $( "#frm_data_search_student" ).serializeArray(); formData.push({ "name": "acc_action", "value": "data_year_search_student" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list").html(data.table_list); }); } function get_data() { var formData = $( "#frm_search" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list").html(data.table_list); }); } $('input').on('keydown', function(event) { var x = event.which; if (x === 13) { get_data(); event.preventDefault(); } }); $(document).delegate('.bt_delete', 'click', function(event) { var data_id = $(this).attr('data-id'); $(document).delegate('#btn_to_delete', 'click', function(event) { $.post('modules/' + opPage + '/process.php', { 'acc_action' : 'data_remove', 'data_val' : data_id }, function(response) { data_id=''; $(".modal").modal("hide"); get_data() ; }); }); }); <file_sep>/modules/conclusion/class_modules/learning_result_department.php <?php class ClassData extends Databases { public function get_class_room_list($courseID,$class_level,$class_set,$department_set,$year,$term,$room){ $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND courseID='$courseID' AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level$class_set' AND term='$term' AND year='$year' AND room='$room' ) "; $this->select(); $this->setRows(); $data_l=0; $data_ms=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_rtw_nopass=0; $data_rtw_pass=0; $data_rtw_good=0; $data_rtw_verygood=0; $std_amount=0; foreach($this->rows as $key => $value) { $score_total=$value['score_total']; $score_attend=$value['score_attend']; $score_desirable=$value['score_desirable']; $score_rtw=$value['score_rtw']; if ($score_total!=-1) { $grade=$this->get_grade($score_total); if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } }elseif($score_total==-1){ $data_l++; } if ($score_attend==-1) { $data_ms++; } if ($score_desirable<1) { $data_desirable_nopass++; }elseif($score_desirable<1.5){ $data_desirable_pass++; }elseif($score_desirable<2.5){ $data_desirable_good++; }elseif($score_desirable>=2.5){ $data_desirable_verygood++; } if ($score_rtw<1) { $data_rtw_nopass++; }elseif($score_rtw<1.5){ $data_rtw_pass++; }elseif($score_rtw<2.5){ $data_rtw_good++; }elseif($score_rtw>=2.5){ $data_rtw_verygood++; } $std_amount++; } $data_response['data_l']=$data_l; $data_response['data_ms']=$data_ms; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_rtw_nopass']=$data_rtw_nopass; $data_response['data_rtw_pass']=$data_rtw_pass; $data_response['data_rtw_good']=$data_rtw_good; $data_response['data_rtw_verygood']=$data_rtw_verygood; $data_response['std_amount']=$std_amount; return $data_response; } public function get_loop_data($class_level,$year,$term,$department,$i,$class_set){ $class_level_text=$class_level=='p'?'ป.':'ม.'; $this->sql =" SELECT DISTINCT(tbl_sub_pp6.courseID),room FROM tbl_sub_pp6,tbl_pp6 WHERE tbl_sub_pp6.pp6_ID=tbl_pp6.DataID AND tbl_sub_pp6.status=1 AND tbl_sub_pp6.department='$department' AND tbl_pp6.class_level='$class_level$class_set' AND tbl_pp6.term='$term' AND tbl_pp6.year='$year' "; $this->select(); $this->setRows(); $amount_data_40=0; $amount_data_35=0; $amount_data_30=0; $amount_data_25=0; $amount_data_20=0; $amount_data_15=0; $amount_data_10=0; $amount_data_00=0; $amount_data_l=0; $amount_data_ms=0; $amount_desirable_verygood=0; $amount_desirable_good=0; $amount_desirable_pass=0; $amount_desirable_nopass=0; $amount_rtw_verygood=0; $amount_rtw_good=0; $amount_rtw_pass=0; $amount_rtw_nopass=0; $all_std_amount=0; $order=1; foreach($this->rows as $key => $value) { $courseID=$value['courseID']; $room=$value['room']; $class_room_list=$this->get_class_room_list($courseID,$class_level,$class_set,$department,$year,$term,$room); $data_response.=' <tr> <td>'.$order.'</td> <td>'.$class_level_text.$class_set.'/'.$room.'</td> <td style="text-align:left;padding-left:10px;">'.$courseID.'</td> <td>'.$class_room_list['data_40'].'</td> <td>'.$class_room_list['data_35'].'</td> <td>'.$class_room_list['data_30'].'</td> <td>'.$class_room_list['data_25'].'</td> <td>'.$class_room_list['data_20'].'</td> <td>'.$class_room_list['data_15'].'</td> <td>'.$class_room_list['data_10'].'</td> <td>'.$class_room_list['data_00'].'</td> <td>'.$class_room_list['data_l'].'</td> <td>'.$class_room_list['data_ms'].'</td> <td>'.$class_room_list['data_desirable_verygood'].'</td> <td>'.$class_room_list['data_desirable_good'].'</td> <td>'.$class_room_list['data_desirable_pass'].'</td> <td>'.$class_room_list['data_desirable_nopass'].'</td> <td>'.$class_room_list['data_rtw_verygood'].'</td> <td>'.$class_room_list['data_rtw_good'].'</td> <td>'.$class_room_list['data_rtw_pass'].'</td> <td>'.$class_room_list['data_rtw_nopass'].'</td> <td>'.$class_room_list['std_amount'].'</td> </tr> '; $amount_data_40=$amount_data_40+$class_room_list['data_40']; $amount_data_35=$amount_data_35+$class_room_list['data_35']; $amount_data_30=$amount_data_30+$class_room_list['data_30']; $amount_data_25=$amount_data_25+$class_room_list['data_25']; $amount_data_20=$amount_data_20+$class_room_list['data_20']; $amount_data_15=$amount_data_15+$class_room_list['data_15']; $amount_data_10=$amount_data_10+$class_room_list['data_10']; $amount_data_00=$amount_data_00+$class_room_list['data_00']; $amount_data_l=$amount_data_l+$class_room_list['data_l']; $amount_data_ms=$amount_data_ms+$class_room_list['data_ms']; $amount_desirable_verygood=$amount_desirable_verygood+$class_room_list['data_desirable_verygood']; $amount_desirable_good=$amount_desirable_good+$class_room_list['data_desirable_good']; $amount_desirable_pass=$amount_desirable_pass+$class_room_list['data_desirable_pass']; $amount_desirable_nopass=$amount_desirable_nopass+$class_room_list['data_desirable_nopass']; $amount_rtw_verygood=$amount_rtw_verygood+$class_room_list['data_rtw_verygood']; $amount_rtw_good=$amount_rtw_good+$class_room_list['data_rtw_good']; $amount_rtw_pass=$amount_rtw_pass+$class_room_list['data_rtw_pass']; $amount_rtw_nopass=$amount_rtw_nopass+$class_room_list['data_rtw_nopass']; $all_std_amount=$all_std_amount+$class_room_list['std_amount']; $order++; } $data_response.=' <tr> <td colspan="3">รวม</td> <td>'.$amount_data_40.'</td> <td>'.$amount_data_35.'</td> <td>'.$amount_data_30.'</td> <td>'.$amount_data_25.'</td> <td>'.$amount_data_20.'</td> <td>'.$amount_data_15.'</td> <td>'.$amount_data_10.'</td> <td>'.$amount_data_00.'</td> <td>'.$amount_data_l.'</td> <td>'.$amount_data_ms.'</td> <td>'.$amount_desirable_verygood.'</td> <td>'.$amount_desirable_good.'</td> <td>'.$amount_desirable_pass.'</td> <td>'.$amount_desirable_nopass.'</td> <td>'.$amount_rtw_verygood.'</td> <td>'.$amount_rtw_good.'</td> <td>'.$amount_rtw_pass.'</td> <td>'.$amount_rtw_nopass.'</td> <td>'.$all_std_amount.'</td> </tr> <tr> <td colspan="3">ร้อยละ</td> <td>'.number_format(($amount_data_40*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_35*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_30*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_25*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_20*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_15*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_10*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_00*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_l*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_data_ms*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_desirable_verygood*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_desirable_good*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_desirable_pass*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_desirable_nopass*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_rtw_verygood*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_rtw_good*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_rtw_pass*100)/$all_std_amount,2).'</td> <td>'.number_format(($amount_rtw_nopass*100)/$all_std_amount,2).'</td> <td>100.0</td> </tr> '; return $data_response; } public function get_rtw($department_set,$class_level,$year,$term){ $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) "; $this->select(); $this->setRows(); $data_rtw_nopass=0; $data_rtw_pass=0; $data_rtw_good=0; $data_rtw_verygood=0; foreach($this->rows as $key => $value) { $score_rtw=$value['score_rtw']; if ($score_rtw<1) { $data_rtw_nopass++; }elseif($score_rtw<1.5){ $data_rtw_pass++; }elseif($score_rtw<2.5){ $data_rtw_good++; }elseif($score_rtw>=2.5){ $data_rtw_verygood++; } } $data_response['data_rtw_nopass']=$data_rtw_nopass; $data_response['data_rtw_pass']=$data_rtw_pass; $data_response['data_rtw_good']=$data_rtw_good; $data_response['data_rtw_verygood']=$data_rtw_verygood; return $data_response; } public function get_amount_std($department_set,$class_level,$year,$term){ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_department_data($class_level,$year,$term,$image_logo,$footer_text_cen_normal,$header_table,$department){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_front_text='ประถมศึกษาปีที่'; }else{ $class_front_text='มัธยมศึกษาปีที่'; } $department_text=$this->get_department($department); $class_set=1; for ($i=1; $i <=3; $i++) { $table_list=''; if ($i==1) { for ($j=1; $j <=2 ; $j++) { $loop_data=$this->get_loop_data($class_level,$year,$term,$department,$i,$class_set); $table_list.=' <table cellspacing="0" style=" text-align: center; font-size: 14px;width:100%;margin-top: 20px;"> '.$header_table.' <tbody > '.$loop_data.' </tbody> </table> '; $class_set++; } $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:16px"> <img class="logo-print-size-level" src="'.$image_logo.'"> <p >รายงานการประเมินผลการเรียนกลุ่มสาระการเรียนรู้ '.$department_text.'</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 20px;">ภาคเรียนที่ <span style="font-weight: normal;">'.$term.'</span> </span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> </div> '.$table_list.' </page> </div> '; }else{ $footer=''; if ($i==3) { $footer=$footer_text_cen_normal; } for ($j=1; $j <=2 ; $j++) { $loop_data=$this->get_loop_data($class_level,$year,$term,$department,$i,$class_set); $table_list.=' <table cellspacing="0" style=" text-align: center; font-size: 14px;width:100%;margin-top: 20px;"> '.$header_table.' <tbody > '.$loop_data.' </tbody> </table> '; $class_set++; } $data_response['std_list'].=' <div style="page-break-after:always;"> <page > '.$table_list.' <div style="margin-top:40px;"> '.$footer.' </div> </page> </div> '; } } return $data_response; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_registed_course ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพฯ'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; case 9: $department='หน้าที่พลเมือง'; break; case 10: $department='ศิลปะพื้นบ้าน'; break; case 11: $department='ศักยภาพ'; break; case 12: $department='ภาษาจีน'; break; default: $department=''; } return $department; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } }<file_sep>/modules/conclusion/index.js var opPage = 'conclusion'; $(document).ready(function() { get_year(); }); function get_year(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_year" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".year_data").html(data); get_data_list_learning(); get_data_list_level(); get_data_list_desirable(); get_data_list_rtw(); get_data_list_department(); }) } function get_data_list_learning(){ var formData = $( "#frm_search_learning_result" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_list_learning" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_learning_result_list").html(data); }) } function get_data_list_level(){ var formData = $( "#frm_search_level_result" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_list_level" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_level_result_list").html(data); }) } function get_data_list_desirable(){ var formData = $( "#frm_search_desirable_result" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_list_desirable" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_desirable_result_list").html(data); }) } function get_data_list_rtw(){ var formData = $( "#frm_search_rtw_result" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_list_rtw" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_rtw_result_list").html(data); }) } function get_data_list_department(){ var formData = $( "#frm_search_department_result" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_list_department" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_department_result_list").html(data); }) } $(document).delegate('#btn_department_result', 'click', function(event) { get_data_list_department(); }) $(document).delegate('#btn_rtw_result', 'click', function(event) { get_data_list_rtw(); }) $(document).delegate('#btn_desirable_result', 'click', function(event) { get_data_list_desirable(); }) $(document).delegate('#btn_level_result', 'click', function(event) { get_data_list_level(); }) $(document).delegate('#btn_learning_result', 'click', function(event) { get_data_list_learning(); })<file_sep>/modules/graduate/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "edit_status"){ $class_room_modal_id=$_GET['class_room_modal_id']; $status_val=$_GET['status_val']; echo $class_data->edit_status($class_room_modal_id,$status_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "getdata_edit"){ $data_id=$_GET['data_id']; echo $class_data->getdata_edit($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_add"){ $data_val = $_POST['data_val']; echo $class_data->data_add($data_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_std_list"){ $class_level=$_GET['class_level']; $room=$_GET['room']; $year=$_GET['year']; echo $class_data->get_std_list($class_level,$room,$year); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); } ?><file_sep>/modules/report/sara_form.php <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/custom.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); ?> <page orientation="portrait"> <img style="margin :10px 0px 10px 335px;display:block;width: 80px;height: 80px;"src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 22px;margin-top: -5px;"> <p class="text-bold " style="margin-top: -8px;">รายงานสรุปการพัฒนาคุณภาพผู้เรียนตามรายกลุ่มสาระ</p> <p class="text-bold " style="margin-top: -8px;">โรงเรียนเทศบาลวัดสระทอง</p> <p style="margin-top: -8px;"> <span class="text-bold">ระดับชั้น </span> มัธยมศึกษาปีที่ 1 <span class="text-bold">ภาคเรียนที่</span> 1 <span class="text-bold">ปีการศึกษา </span>2560</p> </div> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 25px;border: 1px solid black;margin-top: 20px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 10%;font-weight: bold;">รหัสวิชา</td> <td rowspan="2" style=" vertical-align: middle;width: 19%;font-weight: bold;">สาระการเรียนรู้</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;height: 60px;font-weight: bold;"><div style="rotate:90;margin-left: -4px;margin-top: -30px">จำนวน นักเรียน</div></td> <td colspan="8" style="width: 40%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="2" style="width: 12%;padding: 5px;font-weight: bold;">เกรด 3.0 ขึ้นไป</td> <td rowspan="2" style="vertical-align: middle;width: 8%;"><div style="rotate:90;margin-left: -8px;font-weight: bold;">หมายเหตุ</div></td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3%;border-left: none;">4.0</td> <td style="width: 3%;">3.5</td> <td style="width: 3%;">3.0</td> <td style="width: 3%;">2.5</td> <td style="width: 3%;">2.0</td> <td style="width: 3%;">1.5</td> <td style="width: 3%;">1.0</td> <td style="width: 3%;">0,ร</td> <td style="width: 3%;"><div style="rotate:90;margin-top: -28px">รวม</div></td> <td style="width: 3%;"><div style="rotate:90;margin-top: -22px;margin-left: -10px;">ร้อยละ</div></td> </tr> </thead> <tbody> <tr> <td >1</td> <td >ท11001</td> <td >ภาษาไทย</td> <td >162</td> <td >47</td> <td >34 </td> <td >11</td> <td >0</td> <td >2 </td> <td >0</td> <td >0</td> <td >5</td> <td >149</td> <td >91.98</td> <td ></td> </tr> <tr> <td >1</td> <td >ท11001</td> <td >ภาษาไทย</td> <td >162</td> <td >47</td> <td >34 </td> <td >11</td> <td >0</td> <td >2 </td> <td >0</td> <td >0</td> <td >5</td> <td >149</td> <td >91.98</td> <td ></td> </tr> <tr> <td >1</td> <td >ท11001</td> <td >ภาษาไทย</td> <td >162</td> <td >47</td> <td >34 </td> <td >11</td> <td >0</td> <td >2 </td> <td >0</td> <td >0</td> <td >5</td> <td >149</td> <td >91.98</td> <td ></td> </tr> <tr> <td >1</td> <td >ท11001</td> <td >ภาษาไทย</td> <td >162</td> <td >47</td> <td >34 </td> <td >11</td> <td >0</td> <td >2 </td> <td >0</td> <td >0</td> <td >5</td> <td >149</td> <td >91.98</td> <td ></td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >11</td> <td >11</td> <td >162</td> <td >47</td> <td >34 </td> <td >11</td> <td >0</td> <td >2 </td> <td >0</td> <td >0</td> <td >5</td> <td ></td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >11</td> <td >11</td> <td >162</td> <td >47</td> <td >34 </td> <td >11</td> <td >0</td> <td >2 </td> <td >0</td> <td ></td> <td ></td> <td ></td> </tr> <tr> <td colspan="4" class="text-bold">ระดับผลการเรียน 3.0 ขึ้นไป คิดเป็นร้อยละ</td> <td colspan="3">56.11 </td> <td colspan="5">43.89</td> <td ></td> <td ></td> <td ></td> </tr> </tbody> </table> <div style="margin-left: 100px;margin-top: 60px;"> <p>.................................................................หัวหน้างานวัดผล </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 410px;margin-top: -64px;"> <p>.................................................................ผู้อำนวยการ </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> </page><file_sep>/modules/report_std_personal/process.php <?php @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_std_list"){ $class_search=$_GET['class_data']; $room_search=$_GET['room_data']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; $name_id_search=$_GET['name_id_search']; $search_status=$_GET['search_status']; echo $class_data->get_std_list($class_search,$room_search,$name_id_search,$search_status,$term_data,$year_data); } ?><file_sep>/modules/regis_teacher/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_edit"){ $data_id=$_GET['data_id']; echo $class_data->get_data_edit($data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_teacher"){ $status=$_GET['status']; $data_search=$_GET['data_search']; echo $class_data->get_teacher($status,$data_search); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "change_pass"){ $data_val = $_POST['data_val']; echo $class_data->change_pass($data_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_years"){ echo $class_data->get_years(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day_edit"){ $mouth=$_GET['mouth']; echo $class_data->get_day_edit($mouth); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day"){ $mouth=$_GET['mouth']; echo $class_data->get_day($mouth); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "edit_teacher"){ $user_id=$_POST['data_id']; $day=$_POST['day']; $month=$_POST['mouth']; $years=$_POST['years']-543; $birthday=$years.'-'.$month.'-'.$day; $arr_sql[]="positionID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['positionID'])))."'"; $arr_sql[]="fname_th='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname_th'])))."'"; $arr_sql[]="lname_th='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname_th'])))."'"; $arr_sql[]="fname_en='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname_en'])))."'"; $arr_sql[]="lname_en='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname_en'])))."'"; $arr_sql[]="birthday='".chkhtmlspecialchars($InputFilter->clean_script(trim($birthday)))."'"; $arr_sql[]="study_history='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['study_history'])))."'"; $arr_sql[]="gender='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['gender'])))."'"; $arr_sql[]="blood_group='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['blood_group'])))."'"; $arr_sql[]="address='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['address'])))."'"; $arr_sql[]="position_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['position_name'])))."'"; $arr_sql[]="department='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['department'])))."'"; $arr_sql[]="work='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['work'])))."'"; $arr_sql[]="more_detail='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['more_detail'])))."'"; $arr_sql[]="tell='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tell'])))."'"; $arr_sql[]="email='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['email'])))."'"; $arr_sql[]="status_alive='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['status_alive'])))."'"; $class_data->update_data($arr_sql,$user_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $arr_sql = array(); $day=$_POST['day']; $mouth=$_POST['mouth']; $years=$_POST['years']-543; $user_l=substr($_POST['lname_en'], 0, 1); $username=$_POST['fname_en'].'.'.$user_l; $password=$<PASSWORD>'.$<PASSWORD>.$_POST['years']; $birthday=$years.'-'.$mouth.'-'.$day; $arr_sql["positionID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['positionID'])))."'"; $arr_sql["username"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($username)))."'"; $arr_sql["password"]= "'".MD5($password)."'"; $arr_sql["position_name"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['position_name'])))."'"; $arr_sql["fname_th"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname_th'])))."'"; $arr_sql["lname_th"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname_th'])))."'"; $arr_sql["fname_en"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname_en'])))."'"; $arr_sql["lname_en"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname_en'])))."'"; $arr_sql["birthday"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($birthday)))."'"; $arr_sql["blood_group"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['blood_group'])))."'"; $arr_sql["gender"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['gender'])))."'"; $arr_sql["tell"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tell'])))."'"; $arr_sql["email"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['email'])))."'"; $arr_sql["address"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['address'])))."'"; $arr_sql["status_alive"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['status_alive'])))."'"; $arr_sql["cdate"]="now()"; $arr_sql["status"]=1; if ($class_data->insert_data($arr_sql)) { echo "Y"; }else{ echo "N"; } }<file_sep>/modules/conclusion/index.php <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="circle-bg-violet"> <img class="head-img-circle" src="assets/images/report.png"> </div> <div class="text-head-title"> <p>รายงานสรุปผล</p> </div> <div class="row pd-50 pt-100 stage-set" > <div class="col-sm-12 mb-20 "> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"> <a class="text-black fs-13 text-bold" href="#learning_result_tab" aria-controls="learning_result_tab" role="tab" data-toggle="tab">ผลการเรียน</a> </li> <li role="presentation" > <a class="text-black fs-13 text-bold" href="#dev_result_tab" aria-controls="dev_result_tab" role="tab" data-toggle="tab">ผลการพัฒนาคุณภาพผู้เรียน</a> </li> <li role="presentation" > <a class="text-black fs-13 text-bold" href="#desirable_result_tab" aria-controls="desirable_result_tab" role="tab" data-toggle="tab">ผลการพัฒนาคุณลักษณะฯ</a> </li> <li role="presentation"> <a class="text-black fs-13 text-bold" href="#rtw_re_tab" aria-controls="rtw_re_tab" role="tab" data-toggle="tab">ผลการพัฒนาทักษะการอ่านฯ</a> </li> <li role="presentation" > <a class="text-black fs-13 text-bold" href="#department_result_tab" aria-controls="department_result_tab" role="tab" data-toggle="tab">ผลการเรียนตามกลุ่มสาระฯ</a> </li> </ul> </div> <div class="tab-content"> <?php include "include/learning_result_tab.php"?> <?php include "include/dev_result_tab.php"?> <?php include "include/desirable_result_tab.php"?> <?php include "include/rtw_re_tab.php"?> <?php include "include/department_result_tab.php"?> </div> </div> </div> </div> <file_sep>/modules/home/index.php <div class="container set-content" > <?php if ($view_user_ath == 4) {//สายชั้น ?> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/1.png"> <p class="text-card-title">ลงทะเบียนรายวิชา</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=regis_course-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/report.png"> <p class="text-card-title">รายงานสรุปผล</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=conclusion-index">เลือก</a></p> </div> </div> </div> <?php } ?> <?php if ($view_user_ath == 2) { ?> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/2.png"> <p class="text-card-title">เพิ่ม/ลบ/แก้ไขรายวิชา</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=add_delete_course-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/1.png"> <p class="text-card-title">ลงทะเบียนรายวิชา</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=regis_course-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/3.png"> <p class="text-card-title">จัดการข้อมูลครู</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=regis_teacher-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25 "> <div class="card-menu card-border"> <img src="assets/images/4.png"> <p class="text-card-title">ลงทะเบียนนักเรียน</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=regis_student-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/5.png"> <p class="text-card-title">แก้ไข/ลบข้อมูลนักเรียน</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=maneger_student-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/9.png"> <p class="text-card-title">บันทึกการเข้าเรียน</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=attend_class-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/8.png"> <p class="text-card-title">บันทึกคะแนน</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=save_score-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/gra.png" > <p class="text-card-title">สำเร็จการศึกษา</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=graduate-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/class.png"> <p class="text-card-title">เลื่อนชั้น</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=up_class-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/report.png"> <p class="text-card-title">รายงานสรุปผล</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=conclusion-index">เลือก</a></p> </div> </div> </div> <?php } ?> <?php if ($view_user_ath == 1) { ?> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/7.png"> <p class="text-card-title">จัดการรายวิชา</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=regis_course_teaching-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/9.png"> <p class="text-card-title">บันทึกการเข้าเรียน</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=attend_class-index">เลือก</a></p> </div> </div> </div> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/8.png"> <p class="text-card-title">บันทึกคะแนน</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=save_score-index">เลือก</a></p> </div> </div> </div> <?php } ?> <?php if ($view_user_ath == 3) { ?> <div class="col-sm-6 col-md-4 mt-25"> <div class="card-menu card-border"> <img src="assets/images/6.png"> <p class="newactivi-text">ประกาศข่าว/กิจกรรม <br>Mobile Application</p> <div class="line-incard"></div> <div class="btn-select-main"> <p><a class="text-violet" href="index.php?op=news-index">เลือก</a></p> </div> </div> </div> <?php } ?> </div> <file_sep>/modules/chk_grade/class_modules.php <?php class ClassData extends Databases { public function get_course_detail($courseID,$term_data,$year){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=41 AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_data' AND year='$year' ) "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; return $data_response; } public function get_course_id($term_data,$year,$user_id,$pp6_ID){ $this->sql =" SELECT class_level FROM tbl_pp6 WHERE DataID = $pp6_ID "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $this->sql =" SELECT * FROM tbl_sub_pp6 WHERE pp6_ID = $pp6_ID ORDER BY status ASC "; $this->select(); $this->setRows(); $sum_course_score=0; $sum_cproportion_score=0; $find_gpa_sum=0; $find_unit_sum=0; $grade_sum=0; $count_loop=0; foreach($this->rows as $key => $value) { $coures_id_list_val=$value['sub_ID']; $courseID=$value['courseID']; $name=$value['name']; $unit=$value['unit']; $status=$value['status']; if ($status==1) { if($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6'){ $name=$this-> get_department($value['department']); }else{ $name=$name; } $score_total=$value['score_total']; if($score_total==-1){ $score_total=$value['score_mid']+$value['score_final']; $grade='ร'; }else{ $grade=$this->get_grade_text($score_total); } $std_list.=' <tr> <td>'.$courseID.'</td> <td>'.$name.'</td> <td>'.$score_total.'</td> <td>'.$unit.'</td> <td>'.$grade.'</td> </tr> '; }else{ $score_attend=$value['score_attend']; if($score_attend==-1){ $grade='ไม่ผ่าน'; }else{ $grade='ผ่าน'; } $std_list.=' <tr> <td>'.$courseID.'</td> <td>'.$name.'</td> <td style="font-weight:bold">-</td> <td style="font-weight:bold">-</td> <td>'.$grade.'</td> </tr> '; } } $data_response['std_list']=$std_list; return $data_response; } public function get_score_attend_class($std_ID,$coures_id_list_val,$term_data,$year){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_data,$year); $this->sql ="SELECT COUNT(course_teaching_std_id) as sum_no_come FROM tbl_attend_class_std WHERE course_teaching_std_id IN( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID=$std_ID ) AND set_attend_day_id IN( SELECT DataID FROM tbl_set_attend_day WHERE registed_course_teachingID IN( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) ) "; $this->select(); $this->setRows(); $sum_no_come=$this->rows[0]['sum_no_come']; $registed_course_teaching_id=$this->get_registed_course_id($coures_id_list_val,$term_data,$year); $this->sql ="SELECT COUNT(*) as num_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id "; $this->select(); $this->setRows(); $num_day=$this->rows[0]['num_day']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status['class_data']=='p' || $class_level_status['status']==2) { $week_all=40; }else{ $week_all=20; } $total_day=$num_day*$week_all; $total_attend_per=round((($total_day-$sum_no_come)*100)/$total_day); if ($total_attend_per>=80) { $find_80_per='pass'; }else{ $find_80_per='nopass'; } return $find_80_per; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $data_response['status']=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data_response['class_data']='p'; }else{ $data_response['class_data']='m'; } return $data_response; } public function get_registed_course_id($coures_id_list,$term_data,$year){ $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE term='$term_data' AND year='$year' AND courseID=$coures_id_list ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_proportion_title($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); $comulative=$this->rows[0]['comulative']; $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; return $comulative+$mid_exam+$final_exam; } public function get_grade_text($score_exam,$score_pick){ $total=$score_exam+$score_pick; if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_registed_courseID($coures_id_list_val,$term_data,$year){ $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_data' AND year='$year' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_score_pick($std_ID,$coures_id_list_val,$term_data,$year){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_data,$year); $num_of_i=0; $this->sql ="SELECT COUNT(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1 "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($num_of_i>0) { $total='i'; }else{ $total=$score_total_data; } return $total; } public function get_score_exam($std_ID,$coures_id_list_val,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); /*$term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year'];*/ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $mid_status=0; $final_status=0; $this->sql ="SELECT COUNT(score) as num_of_i_mid FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_mid=$this->rows[0]['num_of_i_mid']; if ($num_of_i_mid>0) { $mid_status=-1; } $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $mid_exam_score=$this->rows[0]['score']; $this->sql ="SELECT COUNT(score) as num_of_i_final FROM tbl_final_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_final=$this->rows[0]['num_of_i_final']; if ($num_of_i_final>0) { $final_status=-1; } $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $final_exam_score=$this->rows[0]['score']; if ($mid_status==-1 || $final_status==-1) { $total='i'; }else{ $total=$mid_exam_score+$final_exam_score; } return $total; } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_pick_poi($registed_courseID,$stdID,$term_data,$year){ $this->sql ="SELECT SUM(score) as sum_score FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$stdID' AND objectiveID in( SELECT DataID FROM tbl_objective_conclude ) "; $this->select(); $this->setRows(); return $this->rows[0]['sum_score']; } public function get_unit($registed_courseID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE DataID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['unit']; } public function get_final_poi($registed_courseID,$stdID,$term_data,$year){ $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$stdID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE DataID=$registed_courseID AND term='$term_data' AND year=$year ) ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_mid_poi($registed_courseID,$stdID,$term_data,$year){ $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$stdID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE DataID=$registed_courseID AND term='$term_data' AND year=$year ) ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_data_big_std($stdID,$term_data,$year){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE stdID='$stdID' AND registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE term='$term_data' AND year=$year ) "; $this->select(); $this->setRows(); $find_gpa_sum=0; $find_unit_sum=0; $find_score_no_cal=0; foreach($this->rows as $key => $value) { $registed_courseID=$value['registed_courseID']; $final_poi= $this->get_final_poi($registed_courseID,$stdID,$term_data,$year); $mid_poi= $this->get_mid_poi($registed_courseID,$stdID,$term_data,$year); $score_exam=$final_poi+$mid_poi; $pick_poi= $this->get_pick_poi($registed_courseID,$stdID,$term_data,$year); $grade_text=$this->get_grade_text($score_exam,$pick_poi); $unit=$this->get_unit($registed_courseID); //$total=$final_poi+$mid_poi+$pick_poi; $find_gpa=$grade_text*$unit; $find_gpa_sum=$find_gpa_sum+$find_gpa; $find_unit_sum=$find_unit_sum+$unit; $total_score_no_cal=$final_poi+$mid_poi+$pick_poi; $find_score_no_cal=$find_score_no_cal+$total_score_no_cal; } $gpa=$find_gpa_sum/$find_unit_sum; return $find_score_no_cal; } public function find_position($year_data,$class_level_data,$room){ $data_response = array(); $this->sql ="SELECT distinct(tbl_pp6.std_ID) as std_pp6_id,tbl_pp6.DataID as pp6_id FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_pp6.year='$year_data' AND tbl_pp6.room='$room' AND tbl_pp6.class_level='$class_level_data' AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $find_gpa_sum=0; $score_final_count=0; foreach($this->rows as $key => $value) { $std_pp6_id=$value['std_pp6_id']; $pp6_id=$value['pp6_id']; if($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6'){ $data_big_std= $this->get_data_big_std_p($std_pp6_id,$pp6_id); }else{ $data_big_std= $this->get_data_big_std_m($std_pp6_id,$pp6_id); } $test[$std_pp6_id] = $data_big_std; } return $test; } public function getMax($position){ for ($i=0; $i <count($position) ; $i++) { $data.=$position[$i]; } } public function arrayValuePositionNew($find_position,$std_ID){ $result = array(); $pos = $real_pos = 0; $prev_score = -1; foreach ($find_position as $exam_n => $score) { $real_pos += 1;// Natural position. $pos = ($prev_score != $score) ? $real_pos : $pos;// If I have same score, I have same position in ranking, otherwise, natural position. $result[$exam_n] = array( "score" => $score, "position" => $pos, "exam_no" => $exam_n ); $prev_score = $score;// update last score. } return $result[$std_ID]["position"]; } public function arrayValuePosition($value, $array) { return array_search($value, array_keys($array)); } public function get_data_big_std_p($std_pp6_id,$pp6_id){ $this->sql ="SELECT sum(score_total) as sumed FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); return $this->rows[0]['sumed']; } public function get_data_big_std_m($std_pp6_id,$pp6_id){ $this->sql ="SELECT unit,score_total FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); $find_row_sum=0; foreach($this->rows as $key => $value) { $unit=$value['unit']; $score_total=$value['score_total']; $grade= $this->get_grade_val($score_total); $find_row_sum=$find_row_sum+($unit*$grade); } $this->sql ="SELECT SUM(unit) as unit_sum FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $unit_sum=$this->rows[0]['unit_sum']; return $find_row_sum/$unit_sum; } public function get_grade_val($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_data_room($year,$std_ID){ $this->sql ="SELECT room FROM tbl_std_class_room WHERE std_ID='$std_ID' AND year='$year' "; $this->select(); $this->setRows(); return $this->rows[0]['room']; } public function get_grade(){ $data_response = array(); $user_id=$_SESSION['ss_user_id'] ; $this->sql ="SELECT tbl_student.name_title,tbl_student.fname,tbl_student.lname,tbl_std_class_room.class_level,tbl_std_class_room.room FROM tbl_student , tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_student.std_ID='$user_id' AND tbl_std_class_room.status=1 OR tbl_std_class_room.status=2 "; $this->select(); $this->setRows(); $name_title_data=$this->rows[0]['name_title']; $fname=$this->rows[0]['fname']; $lname=$this->rows[0]['lname']; $class_level_data=$this->rows[0]['class_level']; $room=$this->rows[0]['room']; $name_title=$this->get_name_title($name_title_data); $data_response['std_ID']=$user_id; $data_response['full_name']=$name_title.$fname.' '.$lname; $data_response['class_level']=$this->get_class_level_new($class_level_data); $data_response['room']=$room; $this->sql =" SELECT DISTINCT(term) as term_data,year,class_level,room,DataID as pp6_ID FROM tbl_pp6 WHERE std_ID='$user_id' ORDER BY year ASC,term ASC "; $this->select(); $this->setRows(); $data_response['menu_year_list']='<td width="80px">ปีการศึกษา</td>'; $twst=0; $find_gpa_set=0; $find_unit_sum_set=0; foreach($this->rows as $key => $value) { $pp6_ID=$value['pp6_ID']; $term_data=$value['term_data']; $year=$value['year']; $class_level=$value['class_level']; $room=$value['room']; $find_position=$this->find_position($year,$class_level,$room); arsort($find_position); $arrayValuePosition=$this->arrayValuePositionNew($find_position,$user_id); //$arrayValuePosition=$this->arrayValuePosition($user_id,$find_position); //$new_position=$arrayValuePosition+1; // $searchForId=$this->searchForId('56010516077',$position); $get_course_id= $this->get_course_id($term_data,$year,$user_id,$pp6_ID); //$course_detail=$this->get_course_detail($courseID,$term_data,$year); if($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6'){ $class_level_status_gpa='เฉลี่ย'; $class_level_status_gpx=''; $resaultGpa=$this->get_resaultGpaP($user_id,$term_data,$year); }else{ $class_level_status_gpa='GPA'; $class_level_status_gpx='GPAX'; $resaultGpa=$this->get_resaultGpaM($user_id,$term_data,$year); $resaultGpax=$this->get_resaultGpax($user_id,$term_data,$year); } $resaultSum=$this->get_resaultSum($user_id,$term_data,$year); $data_response['table_list'].=' <div id="'.$term_data.$year.'" class=" ml-50 mr-50 mb-50" > <div class="row"> <div class="col-md-12"> <div style="font-family: thsarabun;font-size:20px;"> <table class="table border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr> <td colspan="5">ภาคการศึกษาที่ '.$term_data.'/'.$year.'</td> </tr> <tr class="table-bg-white-sum"> <td width="24%">รหัสวิชา</td> <td width="34%">รายวิชา</td> <td width="14%">คะแนน</td> <td width="14%">หน่วยกิต</td> <td width="14%">เกรด</td> </tr> </thead> <tbody > '.$get_course_id['std_list'].' </tbody> </table> <table class="table border-set-violet" style="text-align: center;margin-top: -20px;"> <thead class="header-table" > <tr> <td rowspan="2" width="72%" style="padding-top: 22px">รวม</td> <td width="7%">คะแนน</td> <td width="7%">'.$resaultSum.'</td> <td width="7%">'.$class_level_status_gpa.'</td> <td width="7%">'.number_format($resaultGpa,2).'</td> </tr> <tr> <td>อันดับที่</td> <td>'.$arrayValuePosition.'</td> <td>'.$class_level_status_gpx.'</td> <td>'.$resaultGpax.'</td> </tr> </tbody> </table> </div> </div> </div> </div> '; $data_response['menu_year_list'].='<td width="80px"><a href="#'.$term_data.$year.'" class="text-black">'.$term_data.'/'.$year.' </a> |</td>'; } echo json_encode($data_response); } public function get_resaultSum($user_id,$term,$year){ $this->sql ="SELECT SUM(score_total) as score_total FROM tbl_sub_pp6 WHERE score_total!=-1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $score_total=$this->rows[0]['score_total']; if($score_total=='' || $score_total==NULL){ $score_total=0; } return $score_total; } public function get_resaultGpax($user_id,$term,$year){ $this->sql ="SELECT score_total,unit FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year<=$year AND term<=$term ) "; $this->select(); $this->setRows(); $score_row_sum=0; $unit_count=0; foreach($this->rows as $key => $value) { $score_total=$value['score_total']; $unit=$value['unit']; if($score_total!=-1){ $grade=$this->get_grade_text($score_total); $score_row=$grade*$unit; $score_row_sum=$score_row_sum+$score_row; } $unit_count=$unit_count+$unit; } return number_format($score_row_sum/$unit_count,2); } public function get_resaultGpaM($user_id,$term,$year){ $this->sql ="SELECT score_total,unit FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $score_row_sum=0; $unit_count=0; foreach($this->rows as $key => $value) { $score_total=$value['score_total']; $unit=$value['unit']; if($score_total!=-1){ $grade=$this->get_grade_text($score_total); $score_row=$grade*$unit; } $score_row_sum=$score_row_sum+$score_row; $unit_count=$unit_count+$unit; } return number_format($score_row_sum/$unit_count,2); } public function get_resaultGpaP($user_id,$term,$year){ $this->sql ="SELECT SUM(score_total) as score_total FROM tbl_sub_pp6 WHERE score_total!=-1 AND status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $score_total=$this->rows[0]['score_total']; $this->sql ="SELECT COUNT(*) as num_row FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; $resaultGpaFind=$score_total/$num_row; return $resaultGpaFind; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพและเทคโนโลยี'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; default: $department=''; } return $department; } } ?><file_sep>/modules/mobile_api/host/getYearResault.php <?php @session_start(); require_once('config.php'); require_once('src/database.php'); include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $condition = false; $num= $class_data->rows[0]['num']; $json = json_decode(file_get_contents('php://input'), true); $stdId=$json['stdId']; if ($stdId) { echo $class_data->get_header_box($stdId); } ?><file_sep>/modules/regis_course_teaching/index.js var opPage = 'regis_course_teaching'; $(document).ready(function() { get_registed_course_teaching(); get_term_year_now(); }); function dis_object(value) { if (value==2 || value==4) { $(".exam_chk_dis").attr("disabled","disabled"); }else{ $(".exam_chk_dis").removeAttr("disabled"); } } function get_term_year_now() { var year_search=document.getElementById("year_search"); var term_search=document.getElementById("term_search"); term_search.innerHTML=''; year_search.innerHTML=''; var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_term_year_now" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { var term=data.term; var class_level_search=$('#class_level_search').val(); var department_search=$('#department_search').val(); if (class_level_search=='p1' || class_level_search=='p2' || class_level_search=='p3' || class_level_search=='p4' || class_level_search=='p5' || class_level_search=='p6' ) { term_search.innerHTML = '<option id="term_search_id_12" selected="selected" value="1,2">ภาคเรียนที่ 1,2</option>'; }else{ term_search.innerHTML=''; if (term=='1') { term_search.innerHTML += '<option id="term_search_id_1" selected="selected" value="1">ภาคเรียนที่ 1</option>'; term_search.innerHTML += '<option id="term_search_id_2" value="2">ภาคเรียนที่ 2</option>'; }else{ term_search.innerHTML += '<option id="term_search_id_1" value="1">ภาคเรียนที่ 1</option>'; term_search.innerHTML += '<option id="term_search_id_2" selected="selected" value="2">ภาคเรียนที่ 2</option>'; } } var year=data.year; var year_last=year-5;; for (var i = year; i >=year_last; i--) { if (i==year_search) { year_search.innerHTML += '<option selected="selected" value="'+i+'"> ปีการศึกษา'+i+'</option>'; }else{ year_search.innerHTML += '<option value="'+i+'">ปีการศึกษา '+i+'</option>'; } } }) } function add_data_proportion() { var course_id=$('#dropdown_course_id_list').val(); var formData = $( "#frm_data_teaching" ).serializeArray(); formData.push({ "name": "acc_action", "value": "add_data_proportion" }); formData.push({ "name": "course_id", "value": course_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); }) } function update_objective_conclude_pass() { var course_id=$('#dropdown_course_id_list').val(); var objective_data_all_id=$('#objective_data_all_id').val(); var formData = $( "#frm_data_objective" ).serializeArray(); formData.push({ "name": "acc_action", "value": "update_objective_conclude" }); formData.push({ "name": "course_id", "value": course_id }); formData.push({ "name": "objective_data_all_id", "value": objective_data_all_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); }) } function chk_objective_conclude() { var course_id=$('#dropdown_course_id_list').val(); var cumulative_before_mid=$('#cumulative_before_mid').val(); var cumulative_after_mid=$('#cumulative_after_mid').val(); var inputs = document.getElementsByClassName( 'score_data' ), score_data = [].map.call(inputs, function( input ) { return input.value; }).join( '-' ); var inputs = document.getElementsByClassName( 'object_list_data' ), object_list_data = [].map.call(inputs, function( input ) { return input.value; }).join( '-' ); var formData = $( "#frm_data_objective_plus" ).serializeArray(); formData.push({ "name": "acc_action", "value": "chk_cumulative_over" }); formData.push({ "name": "course_id", "value": course_id }); formData.push({ "name": "cumulative_before_mid", "value": cumulative_before_mid }); formData.push({ "name": "cumulative_after_mid", "value": cumulative_after_mid }); formData.push({ "name": "score_data", "value": score_data }); formData.push({ "name": "object_list_data", "value": object_list_data }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { if (data.score_before=="nopass" || data.score_after=="nopass") { get_objective_place_plus(); if (data.score_before=="nopass" && data.score_after=="pass") { $("#alert_cumulative_over_before").show(); $("#alert_cumulative_over_after").hide(); } if(data.score_after=="nopass" && data.score_before=="pass") { $("#alert_cumulative_over_before").hide(); $("#alert_cumulative_over_after").show(); } if(data.score_after=="nopass" && data.score_before=="nopass"){ $("#alert_cumulative_over_before").show(); $("#alert_cumulative_over_after").show(); } }else if(data.score_before=="pass" && data.score_after=="pass"){ $("#alert_cumulative_over_before").hide(); $("#alert_cumulative_over_after").hide(); update_objective_conclude_pass(); add_objective_conclude_pass(); } }) } function get_objective_place_plus() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_objective_place_plus" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#data_objective_place_plus").html(data); }) } function add_objective_conclude_pass() { var course_id=$('#dropdown_course_id_list').val(); var formData = $( "#frm_data_objective_plus" ).serializeArray(); formData.push({ "name": "acc_action", "value": "add_objective_conclude" }); formData.push({ "name": "course_id", "value": course_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_propotion_objective(course_id); get_objective_place_plus(); }) } $(document).delegate('#btn_add_teaching', 'click', function(event) { add_data_proportion(); chk_objective_conclude(); var course_id=$('#dropdown_course_id_list').val(); var term_search=$('#term_search').val(); var year_search=$('#year_search').val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "add_teaching" }); formData.push({ "name": "course_id", "value": course_id }); formData.push({ "name": "term_search", "value": term_search }); formData.push({ "name": "year_search", "value": year_search }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); get_exam_object(course_id); get_registed_course_teaching() ; }) }) $(document).delegate('.btn_delete_objective_first', 'click', function(event) { var course_id=$('#dropdown_course_id_list').val(); var data_id_objective = $(this).attr('data-id'); $(document).delegate('#btn_delete_objective_sec', 'click', function(event) { $.post('modules/' + opPage + '/process.php', { 'acc_action' : 'data_remove_objective', 'data_val' : data_id_objective }, function(response) { data_id=''; $(".modal").modal("hide"); get_propotion_objective(course_id); }); }); }); $(document).delegate('.bt_delete', 'click', function(event) { var course_id=$('#dropdown_course_id_list').val(); var data_id = $(this).attr('data-id'); //alert(data_id) $(document).delegate('#btn_to_delete', 'click', function(event) { $.post('modules/' + opPage + '/process.php', { 'acc_action' : 'data_remove', 'data_val' : data_id }, function(response) { data_id=''; $(".modal").modal("hide"); get_registed_course_teaching() ; get_name_to_add_std(course_id) ; }); }); }); function plus_objective() { var formData = $( "#frm_data_objective_plus" ).serializeArray(); formData.push({ "name": "acc_action", "value": "plus_objective" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#data_objective_place_plus').html(data); }) } $(document).delegate('#btn_plus_objective', 'click', function(event) { plus_objective(); }) function get_registed_course_teaching() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_registed_course_teaching" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#data_table_regis_course_teaching').html(data); }) } $(document).delegate('#btn__conf_add_std', 'click', function(event) { var tempValue=$("input[name='checkbox_delete[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var term_search=$('#term_search').val(); var year_search=$('#year_search').val(); var course_id=$('#dropdown_course_id_list').val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "data_add_std" }); formData.push({ "name": "data_val", "value": tempValue}); formData.push({ "name": "course_id", "value": course_id}); formData.push({ "name": "term_search", "value": term_search}); formData.push({ "name": "year_search", "value": year_search}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_registed_course_teaching(); get_std_list_new(); $('.modal').modal('hide'); }) }); $(document).delegate('#checkbox_all', 'click', function(event) { if(this.checked) { // check select status $('.checkbox_data').each(function() { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); }else{ $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } }); $(document).delegate('#btn_modal_std_search', 'click', function(event) { get_std_list_new(); }) function get_std_list_new() { var course_id=$('#dropdown_course_id_list').val(); var term_search=$('#term_search').val(); var year_search=$('#year_search').val(); var formData = $( "#frm_data_search_modal" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_std_list_new" }); formData.push({ "name": "course_id", "value": course_id }); formData.push({ "name": "term_search", "value": term_search }); formData.push({ "name": "year_search", "value": year_search }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#std_list").html(data.std_list); }) } function update_exam_mid_object(data_id_first,objective_conclude_id) { var formData = $( "#frm_data_objective" ).serializeArray(); formData.push({ "name": "acc_action", "value": "update_exam_mid_object" }); formData.push({ "name": "data_id_first", "value": data_id_first }); formData.push({ "name": "objective_conclude_id", "value": objective_conclude_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { }) } function update_exam_final_object(data_id_first,objective_conclude_id) { var formData = $( "#frm_data_objective" ).serializeArray(); formData.push({ "name": "acc_action", "value": "update_exam_final_object" }); formData.push({ "name": "data_id_first", "value": data_id_first }); formData.push({ "name": "objective_conclude_id", "value": objective_conclude_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { }) } function get_exam_object(data_id_first) { var formData = $( "#frm_data_objective" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_exam_object" }); formData.push({ "name": "data_id_first", "value": data_id_first }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { if (data.status==2) { $("#object_desc_status").hide(); }else{ $("#object_desc_status").show(); } $("#object_list_mid").html(data.object_list_mid); $("#object_list_final").html(data.object_list_final); }) } function get_propotion_objective(data_id_first) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_propotion_objective" }); formData.push({ "name": "data_id_first", "value": data_id_first }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { var cumulative_sum=parseInt(data.mid_exam)+parseInt(data.final_exam)+parseInt(data.cumulative_before_mid)+parseInt(data.cumulative_after_mid); $("#cumulative_sum").html(cumulative_sum); $("#cumulative_before_mid").val(data.cumulative_before_mid); $("#cumulative_after_mid").val(data.cumulative_after_mid); $("#cumulative_before_mid_sum").html(data.cumulative_before_mid); $("#cumulative_after_mid_sum").html(data.cumulative_after_mid); $("#mid_exam").val(data.mid_exam); $("#final_exam").val(data.final_exam); $("#data_objective_place").html(data.objective_list); $("#objective_data_all_id").val(data.objective_data_all_id); $("#score_sum_before").html(data.score_sum_before); $("#score_sum_after").html(data.score_sum_after); }) } function remove_alert(argument) { $("#alert_cumulative_over_before").hide(); $("#alert_cumulative_over_after").hide(); } function get_name_to_add_std(data_id_first,registed_course_id) { get_exam_object(data_id_first); var formData = new Array(); var term_search=$('#term_search').val(); var year_search=$('#year_search').val(); formData.push({ "name": "acc_action", "value": "get_name_to_add_std" }); formData.push({ "name": "data_id_first", "value": data_id_first }); formData.push({ "name": "registed_course_id", "value": registed_course_id }); formData.push({ "name": "term_search", "value": term_search }); formData.push({ "name": "year_search", "value": year_search }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { if (data.num_row!=0) { //$("#course_name_from_search").html(data.name+" (ลงทะเบียนแล้ว)"); //$("#chk_to_show_btn_add_std").hide(); $("#course_name_from_search").html(data.name+'(ลงทะเบียนแล้ว)'); get_propotion_objective(data_id_first); get_std_list_new(); }else{ $("#course_name_from_search").html(data.name); $("#chk_to_show_btn_add_std").show(); get_propotion_objective(data_id_first); get_std_list_new(); } if (data.status==2) { $("#rate_score_box").css("display","none"); $("#target_conclude").css("display","none"); $("#cumulative_text_chk").css("display","none"); $("#regis_course_hide").removeClass("btn-group-set-save-regis-course"); }else{ $("#rate_score_box").css("display","block"); $("#target_conclude").css("display","block"); $("#cumulative_text_chk").css("display","block"); $("#regis_course_hide").addClass("btn-group-set-save-regis-course"); if (data.class_level_status=='p') { $("#set-text-desc-1").html('ก่อนวัดผลกลางปี'); $("#set-text-desc-2").html('กลางปี'); $("#set-text-desc-3").html('หลังวัดผลกลางปี'); $("#set-text-desc-4").html('ปลายปี'); $("#op_drop_space_1").html('ก่อนวัดผลกลางปี'); $("#op_drop_space_2").html('หลังวัดผลกลางปี'); $("#text_exam_objective_mid").html('สอบกลางปี'); $("#text_exam_objective_final").html('สอบปลายปี'); }else{ $("#set-text-desc-1").html('ก่อนกลางภาค'); $("#set-text-desc-2").html('สอบกลางภาค'); $("#set-text-desc-3").html('หลังกลางภาค'); $("#set-text-desc-4").html('สอบปลายภาค'); $("#op_drop_space_1").html('ก่อนกลางภาค'); $("#op_drop_space_2").html('หลังกลางภาค'); $("#text_exam_objective_mid").html('สอบกลางภาค'); $("#text_exam_objective_final").html('สอบปลายภาค'); } } }) } function form_reset(form_se) { $("#"+form_se)[0].reset(); } function hide_class_std(data_id_first) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "hide_class_std" }); formData.push({ "name": "data_id_first", "value": data_id_first }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#search_class_modal").html(data); }) } function search_course_class() { form_reset("frm_data_teaching"); var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "search_course_class" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { var data_id_first=data.data_id_first; var registed_course_id=data.registed_course_id; hide_class_std(data_id_first); $("#dropdown_course_id_list").html(data.dropdown_list); $("#course_name_from_search").html(data.course_name); get_propotion_objective(0); get_exam_object(data_id_first); if (data_id_first!="" && data_id_first!="undefined") { $("#chk_to_show_btn_add_std").show(); get_name_to_add_std(data_id_first,registed_course_id); }else{ $("#chk_to_show_btn_add_std").hide(); } }) } $(document).delegate('#btn_search_course_class', 'click', function(event) { search_course_class(); }) // This dialog will not break other dialogs or modals var oldJqTrigger = jQuery.fn.trigger; jQuery.fn.trigger = function() { if ( arguments && arguments.length > 0) { if (typeof arguments[0] == "object") { if (typeof arguments[0].type == "string") { if (arguments[0].type == "show.bs.modal") { var ret = oldJqTrigger.apply(this, arguments); if ($('.modal:visible').length) { $('.modal-backdrop.in').first().css('z-index', parseInt($('.modal:visible').last().css('z-index')) + 10); $(this).css('z-index', parseInt($('.modal-backdrop.in').first().css('z-index')) + 10); } return ret; } } } else if (typeof arguments[0] == "string") { if (arguments[0] == "hidden.bs.modal") { if ($('.modal:visible').length) { $('.modal-backdrop').first().css('z-index', parseInt($('.modal:visible').last().css('z-index')) - 10); $('body').addClass('modal-open'); } } } } return oldJqTrigger.apply(this, arguments); };<file_sep>/modules/profile/upload.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $user_id=$_SESSION['ss_user_id']; if(is_array($_FILES)) { if(is_uploaded_file($_FILES['userImage']['tmp_name'])) { $ext=pathinfo(basename($_FILES['userImage']['name']),PATHINFO_EXTENSION); $new_file='file_'.uniqid().".".$ext; $oldFileName=$_FILES['userImage']['name']; $sourcePath = $_FILES['userImage']['tmp_name']; $targetPath = "../../file_managers/profile/".$new_file; $upload=move_uploaded_file($sourcePath,$targetPath); crop_img($targetPath); if ($upload==false) { echo "no"; exit(); } $class_data->sql="SELECT * FROM tbl_regis_teacher_gallery WHERE regis_teacher_id=$user_id"; $class_data->select(); $class_data->setRows(); $FileName=$class_data->rows[0]['FileName']; @unlink("../../file_managers/profile/".$FileName); $class_data->sql="DELETE FROM tbl_regis_teacher_gallery WHERE regis_teacher_id = $user_id"; $class_data->query(); $class_data->sql="INSERT INTO tbl_regis_teacher_gallery (regis_teacher_id,FileName) VALUES($user_id,'$new_file')"; $class_data->query(); echo json_encode("ok"); } } function crop_img($imgSrc){ $new = imagecreatefromjpeg($imgSrc); $crop_width = imagesx($new); $crop_height = imagesy($new); $size = min($crop_width, $crop_height); if($crop_width >= $crop_height) { $newx= ($crop_width-$crop_height)/2; $im2 = imagecrop($new, ['x' => $newx, 'y' => 0, 'width' => $size, 'height' => $size]); } else { $newy= ($crop_height-$crop_width)/2; $im2 = imagecrop($new, ['x' => 0, 'y' => $newy, 'width' => $size, 'height' => $size]); } imagejpeg($im2,$imgSrc,90); /* //getting the image dimensions list($width, $height) = getimagesize($imgSrc); //saving the image into memory (for manipulation with GD Library) $myImage = imagecreatefromjpeg($imgSrc); // calculating the part of the image to use for thumbnail if ($width > $height) { $y = 0; $x = ($width - $height) / 2; $smallestSide = $height; } else { $x = 0; $y = ($height - $width) / 2; $smallestSide = $width; } // copying the part into thumbnail $thumbSize = min($width,$height); $thumb = imagecreatetruecolor($thumbSize, $thumbSize); imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide); unlink($imgSrc); imagejpeg($thumb,$imgSrc); @imagedestroy($myImage); @imagedestroy($thumb);*/ } ?><file_sep>/modules/profile/index.js var opPage = 'profile'; $(document).ready(function() { get_data(); get_img(); }); function get_data() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_data" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#positionID").html(data.positionID); $("#full_name_th_s").html(data.full_name_th); $("#full_name_th_pro").html(data.full_name_th); $("#full_name_en").html(data.full_name_en); $("#study_history").html(data.study_history); $("#gender").html(data.gender); $("#blood_group").html(data.blood_group); $("#address").html(data.address); $("#position_name").html(data.position_name); $("#department").html(data.department); $("#department_pro").html(data.department); $("#birthday").html(data.birthday); $("#work").html(data.work); $("#more_detail").html(data.more_detail); $("#tell").html(data.tell); $("#email").html(data.email); }); } function get_img(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_img" }); formData.push({ "name": "status_get", "value": "index" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus) { // console.log(data); $("#get_profile_img").html(data.get_profile_img); }); }<file_sep>/modules/menu/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); /////// CLASS ROLE MANAGEMENT ///// require_once('../../src/class_role.php'); $role = new ClassRole(); $user_role_id = (int)$_SESSION['ss_user_id']; ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $targetfile = '../../../file_managers/menu/'; if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list"){ $sort_column = $_GET['sort_column']; $sort_by = $_GET['sort_by']; $pages_current = $_GET['pages_current']; $arr_search_val = array(); $arr_search_val['data_name'] = $_GET['data_name']; $arr_search_val['s_status'] = $_GET['s_status']; echo $class_data->get_data_list($arr_search_val,$pages_current,$sort_column,$sort_by); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_from"){ $data_id = $_GET['data_id']; echo $class_data->get_data_from($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $DataID = (int)$_POST['data_id']; if ($DataID > 0) { $arr_sql = array(); $arr_sql[]="DataID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['DataID'])))."'"; $arr_sql[]="boxI_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_name'])))."'"; $arr_sql[]="boxI_nameEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_nameEn'])))."'"; $arr_sql[]="boxI_desc='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_desc'])))."'"; $arr_sql[]="boxI_descEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_descEn'])))."'"; $arr_sql[]="boxII_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_name'])))."'"; $arr_sql[]="boxII_nameEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_nameEn'])))."'"; $arr_sql[]="boxII_desc='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_desc'])))."'"; $arr_sql[]="boxII_descEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_descEn'])))."'"; $arr_sql[]="boxIII_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_name'])))."'"; $arr_sql[]="boxIII_nameEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_nameEn'])))."'"; $arr_sql[]="boxIII_desc='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_desc'])))."'"; $arr_sql[]="boxIII_descEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_descEn'])))."'"; $arr_sql[]="boxIV_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_name'])))."'"; $arr_sql[]="boxIV_nameEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_nameEn'])))."'"; $arr_sql[]="boxIV_desc='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_desc'])))."'"; $arr_sql[]="boxIV_descEn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_descEn'])))."'"; $arr_sql[]="status='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['status'])))."'"; $arr_sql[]="tag_title='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tag_title'])))."'"; $arr_sql[]="tag_keyword='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tag_keyword'])))."'"; $arr_sql[]="tag_description='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tag_description'])))."'"; $arr_sql[]="update_time=now()"; $arr_sql[]="update_ip='".ipCheck()."'"; pre($arr_sql); echo $class_data->update_data($arr_sql,$DataID,$user_role_id); // if ($class_data->update_data($arr_sql,$DataID,$user_role_id) == "") { // echo "Y"; // }else{ // echo "N"; // } }else{ $arr_sql = array(); $arr_sql["DataID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['menu_id'])))."'"; $arr_sql["boxI_name"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_name'])))."'"; $arr_sql["boxI_nameEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_nameEn'])))."'"; $arr_sql["boxI_desc"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_desc'])))."'"; $arr_sql["boxI_descEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxI_descEn'])))."'"; $arr_sql["boxII_name"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_name'])))."'"; $arr_sql["boxII_nameEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_nameEn'])))."'"; $arr_sql["boxII_desc"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_desc'])))."'"; $arr_sql["boxII_descEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxII_descEn'])))."'"; $arr_sql["boxIII_name"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_name'])))."'"; $arr_sql["boxIII_nameEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_nameEn'])))."'"; $arr_sql["boxIII_desc"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_desc'])))."'"; $arr_sql["boxIII_descEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIII_descEn'])))."'"; $arr_sql["boxIV_name"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_name'])))."'"; $arr_sql["boxIV_nameEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_nameEn'])))."'"; $arr_sql["boxIV_desc"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_desc'])))."'"; $arr_sql["boxIV_descEn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['boxIV_descEn'])))."'"; $arr_sql["status"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['status'])))."'"; $arr_sql["tag_title"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tag_title'])))."'"; $arr_sql["tag_keyword"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tag_keyword'])))."'"; $arr_sql["tag_description"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tag_description'])))."'"; $arr_sql["create_time"]="now()"; $arr_sql["create_ip"]="'".$ip."'"; $arr_sql["update_time"]="now()"; $arr_sql["update_ip"]="'".$ip."'"; if ($class_data->insert_data($arr_sql,$user_role_id) == "") { echo "Y"; }else{ echo "N"; } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "sequence_data"){ $data_id = $_POST['data_id']; $sequence_old = $_POST['sequence_old']; $sequence = $_POST['sequence']; $res = $class_data->ex_sequence_data($data_id,$sequence_old,$sequence,$user_role_id); //echo "{$res}"; } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val,$user_role_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "upload_thumb"){ // $targetfile = $targetfile."project/"; if (!empty($_FILES)) { $size = getimagesize($_FILES['file']['tmp_name']); $chk_height = $size[1]; if($chk_height<271){ echo $chk_height; }else{ $new_file_name = date('Ymdhis'); ini_set ( "memory_limit", "80M"); $StatusSave = 0;//[0]=Problems [1]=Successfully $file_name = ""; // File name in Database # Check Type Files $typeaccept = array(".jpg",".gif",".jpeg",".png"); // $typeaccept_doc = array(".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"); $fileExt = "." . strtolower(end(explode('.', $_FILES['file']['name']))); $file_ok = (in_array($fileExt, $typeaccept)) ? true : false; // $document_ok = (in_array($fileExt, $typeaccept_doc)) ? true : false; list($width_n, $height_n, $type_n, $w_n) = getimagesize($_FILES['file']['tmp_name']); if($file_ok==true || $document_ok==true) { include ('../../src/class.upload.php'); // $thumbnail = new Upload($_FILES['file']); // if ($thumbnail->uploaded) { // $thumbnail->image_convert = 'jpg'; // $thumbnail->jpeg_quality = 100; // $thumbnail->image_resize = true; // $thumbnail->image_ratio_crop = true; // $thumbnail->image_x = 100; //4:3 Aspect Ratio // $thumbnail->image_y = 100; //4:3 Aspect Ratio // $thumbnail->file_new_name_body = $new_file_name; // $thumbnail->process($targetfile.'thumbnail/'); // if ($thumbnail->processed) { // UPLOAD THUMBNAIL PROCESS END // //$thumbnail->clean(); // $statussave = 1; // } // } $main_photo = new Upload($_FILES['file']); if ($main_photo->uploaded) { $main_photo->image_convert = 'jpg'; $main_photo->jpeg_quality = 100; $main_photo->image_resize = true; $main_photo->image_ratio_crop = true; $main_photo->image_x = $size[0]; //4:3 Aspect Ratio $main_photo->image_y = 350; //4:3 Aspect Ratio $main_photo->file_new_name_body = $new_file_name; $main_photo->process($targetfile.'thumbnails/'); if ($main_photo->processed) { // UPLOAD MAIN PHOTO PROCESS END //$main_photo->clean(); $statussave = 1; } } $file_name = $new_file_name.".jpg";//.$fileExt; $filetype = $fileExt; } # Check Upload Processed Successfully if($statussave==1){ $menuID = ((int)$_POST['data_id'] == 0) ? 0 : (int)$_POST['data_id']; $arr_sql["menuID"]= "'{$menuID}'"; $arr_sql["FileName"]= "'{$file_name}'"; $arr_sql["Type"]= "'0'"; $arr_sql["sequence"]= "'0'"; $arr_sql["status"]= "'{$menuID}'"; $arr_sql["create_time"]= "now()"; $arr_sql["create_ip"]= "'".$ip."'"; $arr_sql["update_time"]= "now()"; $arr_sql["update_ip"]= "'".$ip."'"; $new_par_id = $class_data->ex_add_thumb($arr_sql); // echo $menuID; echo "successfully"; }else{ echo "Problems"; } } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "get_thumb"){ $data_id = $_POST['data_id']; echo $class_data->get_thumb($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "remove_thumb"){ $data_id = $_POST['data_id']; echo $class_data->remove_thumb($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "upload_award"){ if (!empty($_FILES)) { $size = getimagesize($_FILES['file']['tmp_name']); $chk_height = $size[1]; if($chk_height<500){ echo $chk_height; }else{ $new_file_name = date('Ymdhis'); ini_set ( "memory_limit", "80M"); $StatusSave = 0;//[0]=Problems [1]=Successfully $file_name = ""; // File name in Database # Check Type Files $typeaccept = array(".jpg",".gif",".jpeg",".png"); $typeaccept_doc = array(".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"); $fileExt = "." . strtolower(end(explode('.', $_FILES['file']['name']))); $file_ok = (in_array($fileExt, $typeaccept)) ? true : false; $document_ok = (in_array($fileExt, $typeaccept_doc)) ? true : false; list($width_n, $height_n, $type_n, $w_n) = getimagesize($_FILES['file']['tmp_name']); $size_height = 500; $size_width=($width_n*$size_height)/$height_n; if($file_ok==true || $document_ok==true) { include ('../../src/class.upload.php'); $main_photo = new Upload($_FILES['file']); if ($main_photo->uploaded) { $main_photo->image_convert = 'jpg'; $main_photo->jpeg_quality = 100; $main_photo->image_resize = true; $main_photo->image_ratio_crop = true; $main_photo->image_x = $size_width; //4:3 Aspect Ratio $main_photo->image_y = $size_height; //4:3 Aspect Ratio $main_photo->file_new_name_body = $new_file_name; $main_photo->process($targetfile.'photo/'); if ($main_photo->processed) { // UPLOAD MAIN PHOTO PROCESS END //$main_photo->clean(); $statussave = 1; } } $file_name = $new_file_name.'.jpg';//.$fileExt; $filetype = '.jpg'; } # Check Upload Processed Successfully if($statussave==1){ $menuID = ((int)$_POST['data_id'] == 0) ? 0 : (int)$_POST['data_id']; $arr_sql["menuID"]= "'{$menuID}'"; $arr_sql["FileName"]= "'{$file_name}'"; $arr_sql["Type"]= "'1'"; $arr_sql["sequence"]= "'0'"; $arr_sql["status"]= "'{$menuID}'"; $arr_sql["create_time"]= "now()"; $arr_sql["create_ip"]= "'".$ip."'"; $arr_sql["update_time"]= "now()"; $arr_sql["update_ip"]= "'".$ip."'"; $new_par_id = $class_data->ex_add_award($arr_sql); // echo $FacilityName; echo "successfully"; }else{ echo "Problems"; } } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "get_award"){ $data_id = $_POST['data_id']; echo $class_data->get_photo_award($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "remove_file_award"){ $data_id = $_POST['data_id']; echo $class_data->remove_file_award($data_id); } ?><file_sep>/sratong_eva_after_18072561.sql -- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 23, 2018 at 07:10 PM -- Server version: 10.1.25-MariaDB -- PHP Version: 5.6.31 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `sratong_eva_after_18072561` -- -- -------------------------------------------------------- -- -- Table structure for table `ath_role_reletion_tasks` -- CREATE TABLE `ath_role_reletion_tasks` ( `rel_id` int(11) UNSIGNED NOT NULL, `task_id` int(11) DEFAULT '0', `role_id` int(11) DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `ath_role_reletion_tasks` -- INSERT INTO `ath_role_reletion_tasks` (`rel_id`, `task_id`, `role_id`) VALUES (1, 1, 1), (2, 2, 1), (3, 3, 1), (4, 4, 1), (5, 5, 1), (6, 6, 1), (7, 7, 1), (8, 8, 1), (9, 9, 1), (10, 10, 1), (11, 11, 1), (12, 12, 1), (13, 13, 1), (14, 14, 1), (15, 15, 1), (16, 16, 1), (17, 17, 1), (18, 5, 2), (19, 7, 2), (20, 9, 2), (21, 11, 2), (22, 12, 2), (23, 13, 2), (24, 14, 2), (25, 15, 2), (26, 17, 5), (27, 16, 5), (28, 15, 5), (29, 14, 5); -- -------------------------------------------------------- -- -- Table structure for table `ath_tasks` -- CREATE TABLE `ath_tasks` ( `task_id` int(11) UNSIGNED NOT NULL, `fun_id` int(11) DEFAULT '0', `task_key` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, `task_title` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, `task_description` varchar(250) COLLATE utf8_unicode_ci DEFAULT '', `sequence` int(11) DEFAULT '0', `status` int(2) DEFAULT '0' COMMENT '0=n 1=y', `cdate` datetime DEFAULT NULL, `mdate` datetime DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `ath_tasks` -- INSERT INTO `ath_tasks` (`task_id`, `fun_id`, `task_key`, `task_title`, `task_description`, `sequence`, `status`, `cdate`, `mdate`) VALUES (1, 1, 'create_user_ath', 'Create User Authentication ', 'สามารถเพิ่ม User Authentication ได้', 1, 1, NULL, NULL), (2, 1, 'edit_user_ath', 'Edit User Authentication', 'สามารถแก้ไข User Authentication ได้', 2, 1, NULL, NULL), (3, 1, 'del_user_ath', 'Delete User Authentication', 'สามารถลบ User Authentication ได้', 3, 1, NULL, NULL), (4, 1, 'view_user_ath', 'View Menu User Authentication', 'สามารถเข้าใช้งาน เมนู User Authentication ได้', 4, 1, NULL, NULL); -- -------------------------------------------------------- -- -- Table structure for table `ath_users` -- CREATE TABLE `ath_users` ( `user_id` int(11) UNSIGNED NOT NULL, `role_id` int(11) DEFAULT '0', `username` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `password` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'md5', `prefix_name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `first_name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, `last_name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, `email` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `phone_number` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `status` int(2) DEFAULT '0' COMMENT '0=n 1=y', `status_pass` int(2) DEFAULT '0' COMMENT '0 = default , 1 = change pass', `cdate` datetime DEFAULT NULL, `mdate` datetime DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `ath_users` -- INSERT INTO `ath_users` (`user_id`, `role_id`, `username`, `password`, `prefix_name`, `first_name`, `last_name`, `email`, `phone_number`, `status`, `status_pass`, `cdate`, `mdate`) VALUES (1, 1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'Mr.', 'Watcharapon', 'Kestarchon', '-', '-', 1, 0, NULL, '2016-03-18 12:51:44'), (6, 2, 'capsule', '2716373f1a0b85c7d8fb074fb4fc61c7', NULL, 'Tanapat', 'Sirisurt', NULL, NULL, 1, 0, '2017-01-24 11:18:35', '2017-01-24 12:02:25'), (7, 1, 'chanut', '73ca9be08aecbe3e156320d17209cd5a', NULL, 'chanut', 'chumjan', NULL, NULL, 1, 0, '2017-02-24 16:27:49', '2017-02-24 16:29:19'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_add_delete_course` -- CREATE TABLE `tbl_add_delete_course` ( `DataID` int(11) NOT NULL, `user_add` int(11) DEFAULT NULL, `courseID` varchar(250) DEFAULT NULL, `name` text, `class_level` varchar(250) DEFAULT NULL, `unit` decimal(2,1) DEFAULT NULL, `department` varchar(250) DEFAULT NULL, `hr_learn` varchar(250) DEFAULT NULL, `cdate` date NOT NULL, `status` int(11) NOT NULL, `status_form` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_add_delete_course` -- INSERT INTO `tbl_add_delete_course` (`DataID`, `user_add`, `courseID`, `name`, `class_level`, `unit`, `department`, `hr_learn`, `cdate`, `status`, `status_form`) VALUES (409, 311, 'ท21101', 'ภาษาไทย1', 'p1', '1.5', '71', '60', '2018-06-29', 1, 11), (410, 311, 'ท21102', 'ภาษาไทย2', 'p1', '1.5', '1', '60', '2018-06-29', 1, 12), (411, 311, 'ค 21101', 'คณิตศาสตร์ พื้นฐาน', 'm2', '1.5', '2', '60', '2018-06-29', 1, 11), (412, 311, 'ค 21102', 'คณิตศาสตร์ เพิ่มเติม', 'p1', '1.5', '2', '60', '2018-06-29', 1, 12), (413, 311, 'อ15101', 'ภาษาอังกฤษ', 'p1', '2.5', '1', '5', '2018-06-29', 1, 11), (414, 311, 'ท15201', 'ภาษาไทยเพิ่มเติม', 'p1', '0.5', '1', '1', '2018-06-29', 1, 11), (416, 311, '2', '2', 'p1', '0.0', '', '2', '2018-07-02', 2, 22), (417, 311, '1', '1', 'm1', '0.0', '', '1', '2018-07-02', 2, 26), (418, 311, 'ค11111', 'คณิตศาสตร์ พื้นฐาน', 'm1', '1.0', '2', '3', '2018-07-03', 1, 11), (419, 311, 'ท22222', 'ภาษาไทยพื้นฐาน', 'm1', '0.5', '1', '2', '2018-07-03', 1, 11), (420, 311, 'ท33333', 'ภาษาไทยเพิ่มเติม', 'm1', '1.0', '1', '2', '2018-07-03', 1, 12), (421, 311, 'ก11112', 'ก11112', 'm1', '0.5', '7', '4', '2018-07-04', 1, 11), (422, 311, 'ก11113', 'ก11113', 'm1', '0.5', '2', '3', '2018-07-04', 1, 11), (423, 311, 'ก11114', 'ก11114', 'm1', '0.5', '2', '2', '2018-07-04', 1, 11), (424, 311, 'ก11115', 'ก11115', 'm1', '0.5', '2', '2', '2018-07-04', 1, 11), (425, 311, 'ก11116', 'ก11116', 'm1', '0.5', '2', '1', '2018-07-04', 1, 11), (426, 311, 'ก11117', 'ก11117', 'm1', '0.5', '2', '1', '2018-07-04', 1, 11), (427, 311, 'ก11118', 'ก11118', 'm1', '0.5', '2', '1', '2018-07-04', 1, 11), (428, 311, 'ก11119', 'ก11119', 'm1', '0.5', '2', '2', '2018-07-04', 1, 11), (429, 311, 'ก111110', 'ก111110', 'm1', '0.5', '2', '2', '2018-07-04', 1, 11), (430, 311, 'ก45623', 'แนะแนว', 'm1', '9.9', '', '3', '2018-07-19', 2, 25); -- -------------------------------------------------------- -- -- Table structure for table `tbl_attend_class` -- CREATE TABLE `tbl_attend_class` ( `DataID` int(11) NOT NULL, `course_teaching_stdID` int(11) DEFAULT NULL, `week` int(11) DEFAULT NULL, `score_status` varchar(250) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `tbl_attend_class_std` -- CREATE TABLE `tbl_attend_class_std` ( `DataID` int(11) NOT NULL, `course_teaching_std_id` int(11) DEFAULT NULL, `set_attend_day_id` int(11) DEFAULT NULL, `week` int(11) DEFAULT NULL, `status` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_attend_class_std` -- INSERT INTO `tbl_attend_class_std` (`DataID`, `course_teaching_std_id`, `set_attend_day_id`, `week`, `status`) VALUES (1, 17922, 658, 1, 'ล'), (2, 17923, 673, 1, 'ล'), (3, 17927, 672, 1, 'ล'), (4, 17927, 672, 2, 'ล'), (5, 17927, 672, 3, 'ล'), (6, 17927, 672, 4, 'ล'), (7, 17927, 672, 5, 'ล'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_attend_class_week_list` -- CREATE TABLE `tbl_attend_class_week_list` ( `DataID` int(11) NOT NULL, `name` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_attend_class_week_list` -- INSERT INTO `tbl_attend_class_week_list` (`DataID`, `name`) VALUES (1, 'จันทร์'), (2, 'อังคาร'), (3, 'พุธ'), (4, 'พฤหัสบดี'), (5, 'ศุกร์'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_course_teacher` -- CREATE TABLE `tbl_course_teacher` ( `DataID` int(11) NOT NULL, `teacher_id` int(11) DEFAULT NULL, `regis_course_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_course_teacher` -- INSERT INTO `tbl_course_teacher` (`DataID`, `teacher_id`, `regis_course_id`) VALUES (215, 323, 696), (219, 323, 701), (220, 323, 700), (221, 323, 702), (222, 323, 703), (223, 323, 706), (224, 323, 705), (225, 323, 704), (226, 323, 707), (227, 323, 708), (228, 323, 709), (231, 323, 711), (254, 323, 698), (255, 325, 701); -- -------------------------------------------------------- -- -- Table structure for table `tbl_course_teaching_std` -- CREATE TABLE `tbl_course_teaching_std` ( `DataID` int(11) NOT NULL, `registed_courseID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `cdate` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_course_teaching_std` -- INSERT INTO `tbl_course_teaching_std` (`DataID`, `registed_courseID`, `stdID`, `cdate`) VALUES (17895, 696, '01111', '2018-07-13'), (17896, 696, '01112', '2018-07-13'), (17897, 696, '01117', '2018-07-13'), (17898, 697, '11141', '2018-07-13'), (17899, 697, '11144', '2018-07-13'), (17900, 698, '01111', '2018-07-13'), (17901, 698, '01112', '2018-07-13'), (17902, 698, '01117', '2018-07-13'), (17903, 699, '11141', '2018-07-13'), (17904, 699, '11144', '2018-07-13'), (17905, 701, '01111', '2018-07-13'), (17906, 701, '01112', '2018-07-13'), (17907, 701, '01117', '2018-07-13'), (17908, 700, '01111', '2018-07-13'), (17909, 700, '01112', '2018-07-13'), (17910, 700, '01117', '2018-07-13'), (17911, 703, '01111', '2018-07-15'), (17912, 702, '01111', '2018-07-15'), (17913, 706, '11141', '2018-07-15'), (17914, 705, '11141', '2018-07-15'), (17915, 704, '11141', '2018-07-15'), (17916, 707, '11141', '2018-07-15'), (17917, 707, '11144', '2018-07-15'), (17918, 708, '11141', '2018-07-15'), (17919, 708, '11144', '2018-07-15'), (17920, 709, '11141', '2018-07-15'), (17921, 709, '11144', '2018-07-15'), (17922, 698, '991115', '2018-07-19'), (17923, 711, '11144', '2018-07-19'), (17924, 711, '11141', '2018-07-19'), (17925, 711, '111541', '2018-07-19'), (17926, 711, '11143', '2018-07-19'), (17927, 711, '11142', '2018-07-19'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_1` -- CREATE TABLE `tbl_desirable_1` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_1` -- INSERT INTO `tbl_desirable_1` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 2), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_2` -- CREATE TABLE `tbl_desirable_2` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_2` -- INSERT INTO `tbl_desirable_2` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_3` -- CREATE TABLE `tbl_desirable_3` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_3` -- INSERT INTO `tbl_desirable_3` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_4` -- CREATE TABLE `tbl_desirable_4` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_4` -- INSERT INTO `tbl_desirable_4` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 1), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_5` -- CREATE TABLE `tbl_desirable_5` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_5` -- INSERT INTO `tbl_desirable_5` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_6` -- CREATE TABLE `tbl_desirable_6` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_6` -- INSERT INTO `tbl_desirable_6` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_7` -- CREATE TABLE `tbl_desirable_7` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_7` -- INSERT INTO `tbl_desirable_7` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_desirable_8` -- CREATE TABLE `tbl_desirable_8` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_desirable_8` -- INSERT INTO `tbl_desirable_8` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 449, '991115', 0), (157, 1, '11141', 3), (158, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_exam_final_object` -- CREATE TABLE `tbl_exam_final_object` ( `DataID` int(11) NOT NULL, `courseID` int(11) DEFAULT NULL, `objective_conclude` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `tbl_exam_mid_object` -- CREATE TABLE `tbl_exam_mid_object` ( `DataID` int(11) NOT NULL, `courseID` int(11) DEFAULT NULL, `objective_conclude` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `tbl_final_exam_score` -- CREATE TABLE `tbl_final_exam_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_final_exam_score` -- INSERT INTO `tbl_final_exam_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (240, 447, '01111', 25), (241, 447, '01112', 20), (242, 447, '01117', 20), (245, 451, '01111', 10), (246, 451, '01112', 15), (247, 451, '01117', 8), (248, 453, '01111', 25), (249, 454, '01111', 25), (250, 455, '11141', 25), (251, 456, '11141', 25), (252, 458, '11141', 25), (253, 458, '11144', 25), (254, 459, '11141', 5), (255, 459, '11144', 25), (256, 460, '11141', 25), (257, 460, '11144', 25); -- -------------------------------------------------------- -- -- Table structure for table `tbl_log` -- CREATE TABLE `tbl_log` ( `log_id` int(11) NOT NULL, `title_action` varchar(255) NOT NULL, `menu_name` varchar(200) NOT NULL, `data_id` int(11) NOT NULL, `update_by` int(11) NOT NULL, `update_time` datetime NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_log` -- INSERT INTO `tbl_log` (`log_id`, `title_action`, `menu_name`, `data_id`, `update_by`, `update_time`) VALUES (559, 'แก้ไขข้อมูล Aboutus', 'Aboutus', 20, 1, '2017-03-02 15:21:51'), (560, 'แก้ไขข้อมูล Aboutus', 'Aboutus', 20, 1, '2017-03-02 15:22:12'), (561, 'แก้ไขข้อมูล Aboutus', 'Aboutus', 20, 1, '2017-03-02 15:23:18'), (562, 'แก้ไขข้อมูล Aboutus', 'Aboutus', 20, 1, '2017-03-02 15:23:28'), (563, 'แก้ไขข้อมูล Aboutus', 'Aboutus', 20, 1, '2017-03-02 15:23:47'), (564, 'แก้ไขข้อมูล Contact', 'Contact', 8, 1, '2017-03-08 17:50:28'), (565, 'เพิ่มข้อมูล Project', 'Project', 30, 1, '2017-03-29 12:23:47'), (566, 'ลบข้อมูล Project', 'Project', 30, 1, '2017-03-29 12:23:54'), (567, 'เพิ่มข้อมูล Project', 'Project', 31, 1, '2017-03-29 14:12:11'), (568, 'เพิ่มข้อมูล Project', 'Project', 32, 1, '2017-03-29 14:12:37'), (569, 'แก้ไขข้อมูล Project', 'Project', 0, 32, '2017-03-29 14:13:01'), (570, 'แก้ไขข้อมูล Project', 'Project', 0, 32, '2017-03-29 14:13:23'), (571, 'เพิ่มข้อมูล Project', 'Project', 33, 1, '2017-03-29 14:14:24'), (572, 'แก้ไขข้อมูล Project', 'Project', 0, 33, '2017-03-29 14:15:37'), (573, 'เพิ่มข้อมูล Project', 'Project', 34, 1, '2017-03-29 14:19:54'), (574, 'ลบข้อมูล Project', 'Project', 33, 1, '2017-03-29 14:21:06'), (575, 'ลบข้อมูล Project', 'Project', 34, 1, '2017-03-29 14:21:09'), (576, 'แก้ไขข้อมูล Project', 'Project', 0, 29, '2017-03-29 14:21:25'), (577, 'เพิ่มข้อมูล Project', 'Project', 35, 1, '2017-03-29 14:24:07'), (578, 'ลบข้อมูล Product', 'Product', 32, 1, '2017-03-29 16:57:44'), (579, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:33:40'), (580, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:35:06'), (581, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:35:15'), (582, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:35:22'), (583, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:36:10'), (584, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:36:19'), (585, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:36:43'), (586, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:36:50'), (587, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:39:05'), (588, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:39:16'), (589, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:39:29'), (590, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:39:37'), (591, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:41:26'), (592, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:41:33'), (593, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-17 22:41:39'), (594, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 2, 1, '2017-08-17 22:48:15'), (595, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 3, 1, '2017-08-17 22:52:03'), (596, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 3, 1, '2017-08-17 22:56:55'), (597, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 4, 1, '2017-08-17 22:57:44'), (598, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 5, 1, '2017-08-18 10:45:38'), (599, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 6, 1, '2017-08-18 10:45:50'), (600, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 7, 1, '2017-08-18 10:50:00'), (601, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 8, 1, '2017-08-18 10:50:22'), (602, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 9, 1, '2017-08-18 10:52:03'), (603, 'เพิ่มข้อมูล km_committee', 'km_committee', 10, 1, '2017-08-18 11:11:03'), (604, 'เพิ่มข้อมูล km_committee', 'km_committee', 11, 1, '2017-08-18 11:27:37'), (605, 'แก้ไขข้อมูล km_department', 'km_department', 10, 1, '2017-08-18 11:30:01'), (606, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 2, 1, '2017-08-21 20:26:00'), (607, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 2, 1, '2017-08-21 20:27:15'), (608, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-21 20:29:41'), (609, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-21 20:30:05'), (610, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-21 20:31:53'), (611, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 2, 1, '2017-08-21 21:23:54'), (612, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 2, 1, '2017-08-21 21:23:55'), (613, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-21 21:24:29'), (614, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-21 21:26:15'), (615, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 2, 1, '2017-08-21 21:27:34'), (616, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-21 21:34:42'), (617, 'แก้ไขข้อมูล km_innovations_group', 'km_innovations_group', 12, 1, '2017-08-22 10:03:02'), (618, 'แก้ไขข้อมูล km_innovations_group', 'km_innovations_group', 12, 1, '2017-08-22 10:03:07'), (619, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:34:54'), (620, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:35:19'), (621, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:35:29'), (622, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:36:22'), (623, 'เพิ่มข้อมูล km_innovations_group', 'km_innovations_group', 13, 1, '2017-08-22 10:37:59'), (624, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:38:08'), (625, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:39:00'), (626, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 10:39:08'), (627, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 1, 1, '2017-08-22 11:24:59'), (628, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 2, 1, '2017-08-22 11:25:09'), (629, 'เพิ่มข้อมูล km_strategic', 'km_strategic', 3, 1, '2017-08-22 11:25:16'), (630, 'แก้ไขข้อมูล km_strategic', 'km_strategic', 3, 1, '2017-08-22 11:25:29'), (631, 'แก้ไขข้อมูล km_committee', 'km_committee', 10, 1, '2017-08-22 11:32:03'), (632, 'แก้ไขข้อมูล km_committee', 'km_committee', 11, 1, '2017-08-22 11:32:20'), (633, 'เพิ่มข้อมูล km_committee', 'km_committee', 12, 1, '2017-08-22 11:32:34'), (634, 'เพิ่มข้อมูล km_department', 'km_department', 12, 1, '2017-08-22 11:36:17'), (635, 'เพิ่มข้อมูล km_department', 'km_department', 13, 1, '2017-08-22 11:36:40'), (636, 'แก้ไขข้อมูล km_department', 'km_department', 10, 1, '2017-08-22 11:36:51'), (637, 'จัดอันดับข้อมูล km_department', 'km_department', 12, 1, '2017-08-22 11:37:08'), (638, 'เพิ่มข้อมูล km_department', 'km_department', 14, 1, '2017-08-22 11:38:32'), (639, 'เพิ่มข้อมูล km_department', 'km_department', 15, 1, '2017-08-22 11:38:56'), (640, 'เพิ่มข้อมูล km_department', 'km_department', 16, 1, '2017-08-22 11:39:23'), (641, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:40:08'), (642, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:40:21'), (643, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:40:33'), (644, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:42:49'), (645, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:43:30'), (646, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:45:31'), (647, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:46:16'), (648, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 1, 1, '2017-08-22 11:46:51'), (649, 'เพิ่มข้อมูล km_department_work', 'km_department_work', 3, 1, '2017-08-22 11:47:28'), (650, 'แก้ไขข้อมูล km_department_work', 'km_department_work', 3, 1, '2017-08-22 11:47:44'), (651, 'เพิ่มข้อมูล km_department_work', 'km_department_work', 4, 1, '2017-08-22 11:48:44'), (652, 'แก้ไขข้อมูล km_innovations_group', 'km_innovations_group', 12, 1, '2017-08-22 12:01:14'), (653, 'แก้ไขข้อมูล km_innovations_group', 'km_innovations_group', 13, 1, '2017-08-22 12:01:18'), (654, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 12:02:57'), (655, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-22 12:03:26'), (656, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-22 13:14:34'), (657, 'เพิ่มข้อมูล km_conner', 'km_conner', 2, 1, '2017-08-22 13:17:51'), (658, 'เพิ่มข้อมูล km_conner', 'km_conner', 3, 1, '2017-08-22 13:18:02'), (659, 'เพิ่มข้อมูล km_conner', 'km_conner', 4, 1, '2017-08-22 13:18:12'), (660, 'เพิ่มข้อมูล km_conner', 'km_conner', 5, 1, '2017-08-22 13:18:23'), (661, 'เพิ่มข้อมูล km_conner', 'km_conner', 6, 1, '2017-08-22 13:18:34'), (662, 'เพิ่มข้อมูล km_conner', 'km_conner', 7, 1, '2017-08-22 13:18:46'), (663, 'เพิ่มข้อมูล km_conner', 'km_conner', 8, 1, '2017-08-22 13:19:01'), (664, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 3, 1, '2017-08-22 13:34:07'), (665, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 3, 1, '2017-08-22 13:34:16'), (666, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 4, 1, '2017-08-22 13:35:34'), (667, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 4, 1, '2017-08-22 13:36:22'), (668, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 5, 1, '2017-08-22 13:36:54'), (669, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 6, 1, '2017-08-22 13:37:18'), (670, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 7, 1, '2017-08-22 13:37:48'), (671, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 8, 1, '2017-08-22 13:42:13'), (672, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 9, 1, '2017-08-22 13:43:14'), (673, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 10, 1, '2017-08-22 13:43:37'), (674, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 11, 1, '2017-08-22 13:43:55'), (675, 'เพิ่มข้อมูล km_innovations', 'km_innovations', 12, 1, '2017-08-22 13:44:18'), (676, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 11, 1, '2017-08-22 13:44:51'), (677, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:21:03'), (678, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:21:12'), (679, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:21:18'), (680, 'เพิ่มข้อมูล km_activities', 'km_activities', 2, 1, '2017-08-25 22:22:56'), (681, 'เพิ่มข้อมูล km_activities', 'km_activities', 3, 1, '2017-08-25 22:23:04'), (682, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:23:30'), (683, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:23:34'), (684, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:23:39'), (685, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:23:46'), (686, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:23:54'), (687, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:23:59'), (688, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:24:04'), (689, 'แก้ไขข้อมูล km_activities', 'km_activities', 1, 1, '2017-08-25 22:24:09'), (690, 'เพิ่มข้อมูล km_activities', 'km_activities', 4, 1, '2017-08-25 22:24:29'), (691, 'เพิ่มข้อมูล km_activities', 'km_activities', 5, 1, '2017-08-26 14:06:25'), (692, 'เพิ่มข้อมูล km_activities', 'km_activities', 6, 1, '2017-08-26 14:25:11'), (693, 'แก้ไขข้อมูล km_activities', 'km_activities', 5, 1, '2017-08-26 17:03:43'), (694, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 10:44:40'), (695, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-27 10:45:29'), (696, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 11:12:39'), (697, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 11:12:47'), (698, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 11:13:33'), (699, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 11:17:55'), (700, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 11:18:16'), (701, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 6, 1, '2017-08-27 11:18:50'), (702, 'แก้ไขข้อมูล km_conner', 'km_conner', 2, 1, '2017-08-27 11:31:49'), (703, 'แก้ไขข้อมูล km_conner', 'km_conner', 2, 1, '2017-08-27 11:32:24'), (704, 'แก้ไขข้อมูล km_documents', 'km_documents', 2, 1, '2017-08-27 11:34:38'), (705, 'แก้ไขข้อมูล km_conner', 'km_conner', 3, 1, '2017-08-27 11:37:04'), (706, 'เพิ่มข้อมูล km_documents', 'km_documents', 3, 1, '2017-08-27 14:01:03'), (707, 'เพิ่มข้อมูล km_documents', 'km_documents', 4, 1, '2017-08-27 14:01:36'), (708, 'แก้ไขข้อมูล km_documents', 'km_documents', 2, 1, '2017-08-27 14:02:25'), (709, 'แก้ไขข้อมูล km_documents', 'km_documents', 2, 1, '2017-08-27 14:07:45'), (710, 'เพิ่มข้อมูล km_documents', 'km_documents', 5, 1, '2017-08-27 14:09:41'), (711, 'เพิ่มข้อมูล km_documents', 'km_documents', 6, 1, '2017-08-27 14:21:08'), (712, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 2, 1, '2017-08-27 14:41:17'), (713, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 1, 1, '2017-08-27 15:06:09'), (714, 'แก้ไขข้อมูล km_innovations', 'km_innovations', 4, 1, '2017-08-27 15:09:31'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_log_upclass` -- CREATE TABLE `tbl_log_upclass` ( `DataID` int(11) NOT NULL, `user_add` int(11) NOT NULL, `c_date` date NOT NULL, `std_year_old` varchar(250) NOT NULL, `std_year_new` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `tbl_mid_exam_score` -- CREATE TABLE `tbl_mid_exam_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_mid_exam_score` -- INSERT INTO `tbl_mid_exam_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (240, 447, '01111', 25), (241, 447, '01112', 25), (242, 447, '01117', 25), (245, 451, '01111', 25), (246, 451, '01112', 25), (247, 451, '01117', 25), (248, 453, '01111', 25), (249, 454, '01111', 25), (250, 455, '11141', 25), (251, 456, '11141', 25), (252, 458, '11141', 25), (253, 458, '11144', 25), (254, 459, '11141', 5), (255, 459, '11144', 25), (256, 460, '11141', 25), (257, 460, '11144', 25); -- -------------------------------------------------------- -- -- Table structure for table `tbl_news` -- CREATE TABLE `tbl_news` ( `DataID` int(11) NOT NULL, `title` text NOT NULL, `detail` text NOT NULL, `author` int(11) NOT NULL, `date` date NOT NULL, `status` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_news` -- INSERT INTO `tbl_news` (`DataID`, `title`, `detail`, `author`, `date`, `status`) VALUES (48, 'โรงเรียนรับการประเมินสุขาน่าใช้ ส้วมปลอดภัย ประจำปี 2561', 'คณะกรรมการจาก กองสาธารณสุข ร่วมกับ รพ.ร้อยเอ็ด ประเมินสุขาน่าใช้ ส้วมปลอดภัย ประจำปี 2561 โดยมีคณะผู้บริหารสถานศึกษา หัวหน้าช่วงชั้น และคณะกรรมการนักเรียน ร่วมต้อนรับและ รายงานผลการปฏิบัติงาน', 313, '2018-06-29', 1), (49, 'อธิบดีกรมส่งเสริมการปกครองท้องถิ่นเยี่ยมชมโรงเรียน', 'คณะผู้บริหาร คณะครู และนักเรียนโรงเรียนเทศบาลวัดสระทอง ร่วมต้อนรับนายสุทธิพงษ์ จุลเจริญ อธิบดีกรมส่งเสริมการปกครองท้องถิ่น นายนายวันชัย คงเกษม ผู้ว่าราชการจังหวัดร้อยเอ็ด นายบรรจง โฆษิตจิรนันท์ นายกเทศมนตรีเมืองร้อยเอ็ด พร้อมคณะ เยี่ยมชมโครงการ SBMLD ของโรงเรียน เยี่ยมชมการแสดงของนักเรียน และเยี่ยมชมการเรียนการสอนภาษาจีนในโรงเรียน', 313, '2018-06-29', 1), (50, 'คุณครูสอนภาษาจีนคนใหม่ ประจำปีการศึกษา 2561', 'คณะผู้บริหาร คณะครูเดินทางไปสถาบันขงจื้อ มหาวิทยาลัยมหาสารคาม เพื่อรับคุณครูสอนภาษาจีนคนใหม่ ประจำปีการศึกษา 2561', 313, '2018-06-29', 1), (51, 'งานแถลงข่าวการจัดงาน &quot;เล่าเรื่องเมืองร้อยเอ็ด&quot; 243 ปี', 'คณะผู้บริหารโรงเรียนนำโดยท่าน ดร. ประวิทย์ โอวาทกานนท์ ผู้บริหารสถานศึกษา พร้อม คณะครู นักเรียน ร่วมต้อนรับนายวันชัย คงเกษม ผู้ว่าราชการจังหวัดร้อยเอ็ด ในงานแถลงข่าวการจัดงาน &quot;เล่าเรื่องเมืองร้อยเอ็ด&quot; 243 ปี', 313, '2018-06-29', 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_news_gallery` -- CREATE TABLE `tbl_news_gallery` ( `DataID` int(11) NOT NULL, `newsID` int(11) DEFAULT NULL, `file_name` text ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_news_gallery` -- INSERT INTO `tbl_news_gallery` (`DataID`, `newsID`, `file_name`) VALUES (14, 48, 'file_5b3541d9193e0.jpg'), (15, 49, 'file_5b3542063d8dc.jpg'), (16, 50, 'file_5b35422438d98.jpg'), (17, 51, 'file_5b354251e7891.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_news_gallery_sub` -- CREATE TABLE `tbl_news_gallery_sub` ( `DataID` int(11) NOT NULL, `newsID` int(11) DEFAULT NULL, `file_name` text ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_news_gallery_sub` -- INSERT INTO `tbl_news_gallery_sub` (`DataID`, `newsID`, `file_name`) VALUES (31, 48, 'file_5b3541d923851.jpg'), (32, 48, 'file_5b3541d934d17.jpg'), (33, 48, 'file_5b3541d9440df.jpg'), (34, 49, 'file_5b35420658d82.jpg'), (35, 49, 'file_5b35420678901.jpg'), (36, 49, 'file_5b3542068bc17.jpg'), (37, 50, 'file_5b35422444f10.jpg'), (38, 50, 'file_5b35422450487.jpg'), (39, 51, 'file_5b35425210ccc.jpg'), (40, 51, 'file_5b354252290a6.jpg'), (41, 51, 'file_5b35425233530.jpg'), (42, 51, 'file_5b3542523a8f3.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_objective_conclude` -- CREATE TABLE `tbl_objective_conclude` ( `DataID` int(11) NOT NULL, `courseID` int(11) DEFAULT NULL, `no_order` int(11) DEFAULT NULL, `detail` text, `proportion_status` int(11) NOT NULL, `score` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_objective_conclude` -- INSERT INTO `tbl_objective_conclude` (`DataID`, `courseID`, `no_order`, `detail`, `proportion_status`, `score`) VALUES (31, 412, 1, '1', 1, 25), (32, 412, 2, '2', 2, 25), (33, 419, 1, '1', 1, 25), (34, 419, 2, '2', 2, 25), (35, 409, 1, '1', 1, 25), (36, 409, 2, '2', 2, 25), (37, 410, 1, '1', 1, 25), (38, 410, 2, '2', 2, 25), (39, 413, 1, '1', 1, 25), (40, 413, 2, '2', 2, 25), (41, 414, 1, '1', 1, 25), (42, 414, 2, '2', 2, 25), (43, 418, 1, '1', 1, 25), (44, 418, 2, '2', 2, 25), (45, 420, 1, '1', 1, 25), (46, 420, 2, '2', 2, 25), (47, 421, 1, '1', 1, 25), (48, 421, 2, '2', 2, 25); -- -------------------------------------------------------- -- -- Table structure for table `tbl_objective_score_std` -- CREATE TABLE `tbl_objective_score_std` ( `DataID` int(11) NOT NULL, `objectiveID` int(11) DEFAULT NULL, `registed_courseID` int(11) DEFAULT NULL, `staID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_objective_score_std` -- INSERT INTO `tbl_objective_score_std` (`DataID`, `objectiveID`, `registed_courseID`, `staID`, `score`) VALUES (479, 32, 696, '01111', 25), (480, 32, 696, '01112', 25), (481, 32, 696, '01117', 25), (482, 31, 696, '01111', 25), (483, 31, 696, '01112', 25), (484, 31, 696, '01117', 25), (485, 33, 697, '11141', 25), (486, 33, 697, '11144', 25), (487, 34, 697, '11141', 25), (488, 34, 697, '11144', 25), (489, 35, 701, '01111', 25), (490, 35, 701, '01112', 24), (491, 35, 701, '01117', 25), (492, 36, 701, '01111', 25), (493, 36, 701, '01112', 25), (494, 36, 701, '01117', 25), (495, 41, 702, '01111', 25), (496, 42, 702, '01111', 25), (497, 39, 703, '01111', 25), (498, 40, 703, '01111', 25), (499, 43, 706, '11141', 25), (500, 44, 706, '11141', 25), (501, 33, 705, '11141', 25), (502, 34, 705, '11141', 25), (503, 47, 707, '11141', 25), (504, 47, 707, '11144', 25), (505, 48, 707, '11141', 25), (506, 48, 707, '11144', 25), (507, 45, 708, '11141', 25), (508, 45, 708, '11144', 25), (509, 46, 708, '11141', 25), (510, 46, 708, '11144', 25), (511, 43, 709, '11141', 25), (512, 43, 709, '11144', 25), (513, 44, 709, '11141', 25), (514, 44, 709, '11144', 25); -- -------------------------------------------------------- -- -- Table structure for table `tbl_pp6` -- CREATE TABLE `tbl_pp6` ( `DataID` int(11) NOT NULL, `std_ID` varchar(250) DEFAULT NULL, `card_ID` varchar(250) NOT NULL, `name_title` varchar(250) NOT NULL, `fname` varchar(250) NOT NULL, `lname` varchar(250) NOT NULL, `class_level` varchar(250) NOT NULL, `room` varchar(250) NOT NULL, `term` varchar(250) DEFAULT NULL, `year` varchar(250) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_pp6` -- INSERT INTO `tbl_pp6` (`DataID`, `std_ID`, `card_ID`, `name_title`, `fname`, `lname`, `class_level`, `room`, `term`, `year`) VALUES (1745, '11141', '1232312321122', 'dekchai', 'นักเรียน17', 'นักเรียน17', 'm1', '1', '2', '2561'), (1746, '11142', '1232312324414', 'dekchai', 'นักเรียน19', 'นักเรียน19', 'm1', '1', '2', '2561'), (1747, '11144', '1232312321891', 'dekchai', 'นักเรียน18', 'นักเรียน18', 'm1', '2', '2', '2561'), (1748, '11143', '3322312321892', 'dekchai', 'นักเรียน20', 'นักเรียน20', 'm1', '2', '2', '2561'), (1749, '111541', '1232312321224', 'dekchai', 'นักเรียน21', 'นักเรียน21', 'm1', '3', '2', '2561'), (1750, '01112', '1232345432344', 'dekchai', 'นักเรียน2', 'นักเรียน2', 'p1', '1', '1,2', '2561'), (1751, '01117', '1232123456543', 'nangsaw', 'นักเรียน6', 'นักเรียน6', 'p1', '1', '1,2', '2561'), (1752, '991115', '2345434567654', 'dekchai', '991115', '991115', 'p1', '2', '1,2', '2561'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_pp6_mid` -- CREATE TABLE `tbl_pp6_mid` ( `DataID` int(11) NOT NULL, `std_ID` varchar(250) DEFAULT NULL, `card_ID` varchar(250) DEFAULT NULL, `name_title` varchar(250) DEFAULT NULL, `fname` varchar(250) DEFAULT NULL, `lname` varchar(250) DEFAULT NULL, `class_level` varchar(250) DEFAULT NULL, `room` varchar(250) DEFAULT NULL, `term` varchar(250) DEFAULT NULL, `year` varchar(250) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_pp6_mid` -- INSERT INTO `tbl_pp6_mid` (`DataID`, `std_ID`, `card_ID`, `name_title`, `fname`, `lname`, `class_level`, `room`, `term`, `year`) VALUES (550, '01112', '1232345432344', 'dekchai', 'นักเรียน2', 'นักเรียน2', 'p1', '1', '1,2', '2561'), (551, '01117', '1232123456543', 'nangsaw', 'นักเรียน6', 'นักเรียน6', 'p1', '1', '1,2', '2561'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_proportion` -- CREATE TABLE `tbl_proportion` ( `DataID` int(11) NOT NULL, `courseID` int(11) DEFAULT NULL, `comulative` int(11) DEFAULT NULL, `mid_exam` int(11) DEFAULT NULL, `final_exam` int(11) DEFAULT NULL, `cumulative_before_mid` int(11) NOT NULL, `cumulative_after_mid` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_proportion` -- INSERT INTO `tbl_proportion` (`DataID`, `courseID`, `comulative`, `mid_exam`, `final_exam`, `cumulative_before_mid`, `cumulative_after_mid`) VALUES (1770, 412, NULL, 25, 25, 25, 25), (1771, 419, NULL, 25, 25, 25, 25), (1772, 409, NULL, 25, 25, 25, 25), (1773, 410, NULL, 25, 25, 25, 25), (1774, 413, NULL, 25, 25, 25, 25), (1775, 414, NULL, 25, 25, 25, 25), (1776, 418, NULL, 25, 25, 25, 25), (1777, 420, NULL, 25, 25, 25, 25), (1778, 421, NULL, 25, 25, 25, 25); -- -------------------------------------------------------- -- -- Table structure for table `tbl_read_score` -- CREATE TABLE `tbl_read_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_read_score` -- INSERT INTO `tbl_read_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 1), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 1, '11141', 3), (157, 1, '11142', 3), (158, 1, '11144', 2); -- -------------------------------------------------------- -- -- Table structure for table `tbl_registed_course` -- CREATE TABLE `tbl_registed_course` ( `DataID` int(11) NOT NULL, `courseID` int(11) DEFAULT NULL, `term` varchar(250) DEFAULT NULL, `year` varchar(250) DEFAULT NULL, `cdate` date DEFAULT NULL, `export_status` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_registed_course` -- INSERT INTO `tbl_registed_course` (`DataID`, `courseID`, `term`, `year`, `cdate`, `export_status`) VALUES (696, 412, '1,2', '2561', '2018-07-13', 0), (697, 419, '1', '2561', '2018-07-13', 0), (698, 416, '1,2', '2561', '2018-07-13', 0), (699, 417, '1', '2561', '2018-07-13', 0), (700, 410, '1,2', '2561', '2018-07-13', 0), (701, 409, '1,2', '2561', '2018-07-13', 0), (703, 413, '1,2', '2560', '2018-07-15', 0), (704, 420, '1', '2560', '2018-07-15', 0), (707, 421, '1', '2561', '2018-07-15', 0), (708, 420, '1', '2561', '2018-07-15', 0), (709, 418, '2', '2561', '2018-07-15', 0), (710, 417, '1', '2560', '2018-07-18', 0), (711, 430, '2', '2561', '2018-07-19', 0); -- -------------------------------------------------------- -- -- Table structure for table `tbl_registed_course_teaching` -- CREATE TABLE `tbl_registed_course_teaching` ( `DataID` int(11) NOT NULL, `registed_courseID` int(11) DEFAULT NULL, `cdate` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_registed_course_teaching` -- INSERT INTO `tbl_registed_course_teaching` (`DataID`, `registed_courseID`, `cdate`) VALUES (1, 711, '2018-07-19'), (447, 696, '2018-07-13'), (451, 701, '2018-07-13'), (452, 700, '2018-07-13'), (453, 702, '2018-07-15'), (454, 703, '2018-07-15'), (455, 706, '2018-07-15'), (456, 705, '2018-07-15'), (457, 704, '2018-07-15'), (458, 707, '2018-07-15'), (459, 708, '2018-07-15'), (460, 709, '2018-07-15'), (483, 698, '2018-07-20'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_regis_teacher` -- CREATE TABLE `tbl_regis_teacher` ( `DataID` int(11) NOT NULL, `positionID` varchar(250) NOT NULL, `username` varchar(250) NOT NULL, `password` varchar(250) NOT NULL, `position_name` varchar(250) NOT NULL, `department` text NOT NULL, `work` text NOT NULL, `more_detail` text NOT NULL, `fname_th` varchar(250) NOT NULL, `lname_th` varchar(250) NOT NULL, `fname_en` varchar(250) NOT NULL, `lname_en` varchar(250) NOT NULL, `study_history` text NOT NULL, `birthday` date NOT NULL, `blood_group` varchar(250) NOT NULL, `gender` varchar(250) NOT NULL, `tell` varchar(250) NOT NULL, `email` varchar(250) NOT NULL, `address` text NOT NULL, `cdate` date NOT NULL, `status` int(11) NOT NULL, `teacher_status` varchar(250) NOT NULL, `who_status` varchar(250) NOT NULL, `status_rang` int(11) NOT NULL, `status_alive` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_regis_teacher` -- INSERT INTO `tbl_regis_teacher` (`DataID`, `positionID`, `username`, `password`, `position_name`, `department`, `work`, `more_detail`, `fname_th`, `lname_th`, `fname_en`, `lname_en`, `study_history`, `birthday`, `blood_group`, `gender`, `tell`, `email`, `address`, `cdate`, `status`, `teacher_status`, `who_status`, `status_rang`, `status_alive`) VALUES (21, '07693-2', 'admin_eva', '82219639bd900cdaf1c6b2e8c8064f0a', 'ครู', '', '', '', 'กัญญาวีร์', 'เขตคาม', 'gunyavi', 'khetkam', '', '1970-01-01', 'A', 'female', '-', '-', '-', '2017-09-10', 2, '', '1', 3, 5), (311, '000001', 'Admin.E', '5dfb5c7190c9c6cec5bb20cf128a8c16', '', '', '', '', 'แอดมิน', 'วัดผล', 'Admin', 'Evaluation', '', '2008-01-16', 'A', 'male', '', '', '', '2018-06-19', 2, '', '', 3, 1), (312, '000002', 'Admin.H', '12d0caa96704aa2fa0eafcda1da2f514', '', '', '', '', 'แอดมิน', 'สายชั้น', 'Admin', 'Headline', '', '2008-01-02', 'A', 'male', '', '', '', '2018-06-19', 4, '', '', 0, 1), (313, '000003', 'Admin.N', 'ab7c65eb52e56a61e941f009a6e44c17', '', '', '', '', 'แอดมิน', 'ข่าว', 'Admin', 'News', '', '2008-01-01', 'A', 'male', '', '', '', '2018-06-19', 3, '', '', 0, 1), (321, '2000002', 'two.m', 'ab7c65eb52e56a61e941f009a6e44c17', '', '', '', '', 'สอง', 'คณิต', 'two', 'ma', '', '1970-01-01', '', '', '', '', '', '0000-00-00', 1, '', '', 0, 1), (323, '2000001', 'one.m', 'ab7c65eb52e56a61e941f009a6e44c17', '', '', '', '', 'หนึ่ง', 'คณิต', 'one', 'ma', '', '0000-00-00', '', '', '', '', '', '0000-00-00', 1, '', '', 0, 1), (325, '2000003', 'tree.s', 'ab7c65eb52e56a61e941f009a6e44c17', '', '', '', '', 'สาม', 'วิทย์', 'tree', 'sci', '', '0000-00-00', '', '', '', '', '', '0000-00-00', 1, '', '', 0, 1), (326, '2000004', 'four.t', 'ab7c65eb52e56a61e941f009a6e44c17', '', '', '', '', 'สี่', 'ไทย', 'four', 'th', '', '0000-00-00', '', '', '', '', '', '0000-00-00', 1, '', '', 0, 1), (327, '2000005', 'five.e', 'ab7c65eb52e56a61e941f009a6e44c17', '', '', '', '', 'ห้า', 'สังคม', 'five', 'en', '', '0000-00-00', '', '', '', '', '', '0000-00-00', 1, '', '', 0, 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_regis_teacher_gallery` -- CREATE TABLE `tbl_regis_teacher_gallery` ( `DataID` int(11) NOT NULL, `regis_teacher_id` int(11) DEFAULT NULL, `FileName` text ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_regis_teacher_gallery` -- INSERT INTO `tbl_regis_teacher_gallery` (`DataID`, `regis_teacher_id`, `FileName`) VALUES (126, 312, 'file_5b28b6640cd25.png'), (127, 313, 'file_5b28b67eab1d2.png'), (129, 311, 'file_5b28b6b832273.png'), (130, 21, 'file_5b31d38264d07.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_report_mid` -- CREATE TABLE `tbl_report_mid` ( `DataID` int(11) NOT NULL, `pp6_mid_ID` int(11) DEFAULT NULL, `sub_ID` int(11) DEFAULT NULL, `courseID` varchar(250) DEFAULT NULL, `name` text, `unit` decimal(2,1) DEFAULT NULL, `department` varchar(250) DEFAULT NULL, `status` int(11) DEFAULT NULL, `status_form` int(11) DEFAULT NULL, `score_mid` int(11) DEFAULT NULL, `score_final` int(11) DEFAULT NULL, `score_total` int(11) DEFAULT NULL, `score_desirable` float DEFAULT NULL, `score_rtw` float DEFAULT NULL, `score_attend` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_report_mid` -- INSERT INTO `tbl_report_mid` (`DataID`, `pp6_mid_ID`, `sub_ID`, `courseID`, `name`, `unit`, `department`, `status`, `status_form`, `score_mid`, `score_final`, `score_total`, `score_desirable`, `score_rtw`, `score_attend`) VALUES (1634, 550, 409, 'ท21101', 'ภาษาไทย1', '1.5', '71', 1, 11, 50, 40, 50, 3, 3, 1), (1635, 551, 409, 'ท21101', 'ภาษาไทย1', '1.5', '71', 1, 11, 50, 33, 50, 3, 3, 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_room_export` -- CREATE TABLE `tbl_room_export` ( `DataID` int(11) NOT NULL, `registed_courseID` int(11) DEFAULT NULL, `room` int(11) DEFAULT NULL, `cdate` date DEFAULT NULL, `status` int(11) NOT NULL, `sended_status` int(11) NOT NULL, `user_add` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_room_export` -- INSERT INTO `tbl_room_export` (`DataID`, `registed_courseID`, `room`, `cdate`, `status`, `sended_status`, `user_add`) VALUES (235, 711, 1, '2018-07-23', 0, 0, 323), (236, 711, 2, '2018-07-23', 0, 0, 323), (237, 711, 3, '2018-07-23', 0, 0, 323), (238, 698, 0, '2018-07-23', 0, 0, 323), (239, 709, 1, '2018-07-23', 0, 0, 323), (240, 696, 1, '2018-07-23', 0, 0, 323); -- -------------------------------------------------------- -- -- Table structure for table `tbl_room_teacher` -- CREATE TABLE `tbl_room_teacher` ( `DataID` int(11) NOT NULL, `course_teacherID` int(11) DEFAULT NULL, `room` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_room_teacher` -- INSERT INTO `tbl_room_teacher` (`DataID`, `course_teacherID`, `room`) VALUES (172, 215, 1), (173, NULL, 1), (175, NULL, 1), (176, 219, 1), (177, 220, 1), (178, 221, 1), (179, 222, 1), (180, 225, 1), (181, 224, 1), (182, 223, 1), (183, 226, 1), (184, 227, 1), (185, 228, 1), (186, 231, 1), (187, 231, 2), (188, 231, 3), (197, 234, 1), (199, 240, 1), (205, 244, 1), (206, 248, 1), (207, 252, 2), (208, 252, 3), (209, 254, 1), (210, 254, 2), (212, 255, 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_rtw_4_score` -- CREATE TABLE `tbl_rtw_4_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_rtw_4_score` -- INSERT INTO `tbl_rtw_4_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (1, 1, '11141', 3), (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_rtw_5_score` -- CREATE TABLE `tbl_rtw_5_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_rtw_5_score` -- INSERT INTO `tbl_rtw_5_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (1, 1, '11141', 3), (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_set_attend_day` -- CREATE TABLE `tbl_set_attend_day` ( `DataID` int(11) NOT NULL, `registed_course_teachingID` int(11) DEFAULT NULL, `attend_class_week_listID` int(11) DEFAULT NULL, `hr` int(11) NOT NULL, `room` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_set_attend_day` -- INSERT INTO `tbl_set_attend_day` (`DataID`, `registed_course_teachingID`, `attend_class_week_listID`, `hr`, `room`) VALUES (662, 451, 3, 1, '1'), (663, 452, 4, 1, '1'), (664, 453, 3, 1, '1'), (665, 454, 5, 1, '1'), (666, 455, 2, 1, '1'), (667, 456, 5, 1, '1'), (668, 457, 1, 1, '1'), (669, 458, 2, 1, '1'), (670, 459, 4, 1, '1'), (671, 460, 3, 1, '1'), (672, 1, 4, 1, '1'), (673, 1, 3, 1, '2'), (674, 1, 2, 1, '2'), (678, 1, 1, 1, '3'), (690, 449, 1, 1, '1'), (691, 447, 2, 1, '1'), (692, 482, 2, 1, ''), (693, 483, 1, 1, ''); -- -------------------------------------------------------- -- -- Table structure for table `tbl_set_count_adttend_class` -- CREATE TABLE `tbl_set_count_adttend_class` ( `DataID` int(11) NOT NULL, `registed_courseID` int(11) DEFAULT NULL, `week_name` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_set_count_adttend_class` -- INSERT INTO `tbl_set_count_adttend_class` (`DataID`, `registed_courseID`, `week_name`) VALUES (0, 710, 20), (426, 696, 20), (427, 697, 20), (428, 698, 20), (429, 699, 20), (430, 700, 20), (431, 701, 20), (432, 702, 20), (433, 703, 20), (434, 704, 20), (435, 705, 20), (436, 706, 20), (437, 707, 20), (438, 708, 20), (439, 709, 20); -- -------------------------------------------------------- -- -- Table structure for table `tbl_set_term_year` -- CREATE TABLE `tbl_set_term_year` ( `DataID` int(11) NOT NULL, `term` varchar(250) NOT NULL, `year` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_set_term_year` -- INSERT INTO `tbl_set_term_year` (`DataID`, `term`, `year`) VALUES (1, '2', '2561'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_std_class_room` -- CREATE TABLE `tbl_std_class_room` ( `DataID` int(11) NOT NULL, `std_ID` varchar(250) DEFAULT NULL, `class_level` varchar(250) DEFAULT NULL, `room` varchar(250) DEFAULT NULL, `year` varchar(250) DEFAULT NULL, `status` int(11) DEFAULT '1' COMMENT '1 = active' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_std_class_room` -- INSERT INTO `tbl_std_class_room` (`DataID`, `std_ID`, `class_level`, `room`, `year`, `status`) VALUES (1, '991114', 'p1', '1', '2560', 1), (3, '01115', 'p2', '1', '2561', 1), (4, '01116', 'p2', '1', '2561', 1), (5, '1118', 'p3', '1', '2561', 1), (6, '1119', 'p3', '1', '2561', 1), (7, '11120', 'p4', '1', '2561', 1), (8, '11121', 'p4', '1', '2561', 1), (9, '11122', 'p4', '2', '2561', 1), (10, '11123', 'p4', '2', '2561', 1), (11, '11131', 'p5', '1', '2561', 1), (12, '11134', 'p5', '1', '2561', 1), (13, '11132', 'p6', '1', '2561', 1), (14, '11133', 'p6', '1', '2561', 1), (15, '11141', 'm1', '1', '2561', 1), (16, '11144', 'm1', '2', '2561', 1), (17, '11142', 'm1', '1', '2561', 1), (18, '11143', 'm1', '2', '2561', 1), (19, '111541', 'm1', '3', '2561', 1), (20, '111144', 'm3', '1', '2561', 1), (21, '111142', 'm4', '1', '2561', 1), (22, '111143', 'm4', '1', '2561', 1), (23, '211541', 'm5', '1', '2561', 1), (24, '211144', 'm5', '1', '2561', 1), (25, '211142', 'm6', '1', '2561', 1), (26, '211143', 'm6', '1', '2561', 1), (27, '01111', 'p1', '1', '2561', 0), (28, '01112', 'p1', '1', '2561', 1), (29, '01113', 'p1', '2', '2561', 1), (30, '01117', 'p1', '1', '2561', 1), (31, '01111', 'p1', '1', '2560', 1), (32, '11141', 'm1', '1', '2560', 1), (33, '991115', 'p1', '2', '2561', 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_student` -- CREATE TABLE `tbl_student` ( `std_ID` varchar(250) NOT NULL, `card_ID` varchar(250) NOT NULL, `password` varchar(250) NOT NULL, `class_level` varchar(250) NOT NULL, `room` varchar(250) NOT NULL, `name_title` varchar(250) NOT NULL, `fname` varchar(250) NOT NULL, `lname` varchar(250) NOT NULL, `birthday` date NOT NULL, `blood_group` varchar(250) NOT NULL, `address` mediumtext NOT NULL, `parent_name_title` varchar(250) NOT NULL, `parent_fname` varchar(250) NOT NULL, `parent_lname` varchar(250) NOT NULL, `tell` varchar(250) NOT NULL, `parent_address` mediumtext NOT NULL, `status` int(11) NOT NULL, `cdate` date NOT NULL, `status_alive` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_student` -- INSERT INTO `tbl_student` (`std_ID`, `card_ID`, `password`, `class_level`, `room`, `name_title`, `fname`, `lname`, `birthday`, `blood_group`, `address`, `parent_name_title`, `parent_fname`, `parent_lname`, `tell`, `parent_address`, `status`, `cdate`, `status_alive`) VALUES ('01111', '1234567898765', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekchai', 'นักเรียน1', 'นักเรียน1', '2017-01-01', 'A', '', 'nai', '', '', '', '', 1, '2018-07-12', 1), ('01112', '1232345432344', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekchai', 'นักเรียน2', 'นักเรียน2', '2018-01-01', 'A', '', 'nai', '', '', '', '', 1, '2018-07-12', 1), ('01113', '2312344454322', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekying', 'นักเรียน3', 'นักเรียน3', '2018-01-01', 'A', '', 'nai', '', '', '', '', 1, '2018-07-12', 1), ('01115', '2231234565432', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekchai', 'นักเรียน4', 'นักเรียน4', '2018-01-01', 'A', '', 'nai', '', '', '', '', 1, '2018-07-12', 1), ('01116', '1234323454322', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'nai', 'นักเรียน5', 'นักเรียน5', '2018-01-01', 'A', '', 'nai', '', '', '', '', 1, '2018-07-12', 1), ('01117', '1232123456543', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'nangsaw', 'นักเรียน6', 'นักเรียน6', '2018-01-01', 'A', '', 'nai', '', '', '', '', 1, '2018-07-12', 1), ('111142', '1232312324416', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน23', 'นักเรียน23', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('111143', '3322312321893', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน24', 'นักเรียน24', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('111144', '1232312321774', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน22', 'นักเรียน22', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11120', '1232312321188', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน9', 'นักเรียน9', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11121', '1232312321899', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน10', 'นักเรียน10', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11122', '1232312324412', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน11', 'นักเรียน11', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11123', '3322312321899', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน12', 'นักเรียน12', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11131', '1232312321115', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน13', 'นักเรียน13', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11132', '1232312324411', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน15', 'นักเรียน15', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11133', '3322312321891', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน16', 'นักเรียน16', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11134', '1232312321897', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน14', 'นักเรียน14', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11141', '1232312321122', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน17', 'นักเรียน17', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11142', '1232312324414', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน19', 'นักเรียน19', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11143', '3322312321892', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน20', 'นักเรียน20', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('11144', '1232312321891', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน18', 'นักเรียน18', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('111541', '1232312321224', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน21', 'นักเรียน21', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('1118', '1232312321123', '7d8209670a3415eee3f55abc59e87e63', '', '', 'nai', 'นักเรียน7', 'นักเรียน7', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('1119', '1232312321127', '7d8209670a3415eee3f55abc59e87e63', '', '', 'nai', 'นักเรียน8', 'นักเรียน8', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('211142', '1232312324418', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน27', 'นักเรียน27', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('211143', '3322312321894', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน28', 'นักเรียน28', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('211144', '1232312321112', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน26', 'นักเรียน26', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('211541', '1232312321889', '7d8209670a3415eee3f55abc59e87e63', '', '', 'dekchai', 'นักเรียน25', 'นักเรียน25', '1994-07-26', '', '', '', '', '', '', '', 0, '0000-00-00', 1), ('991112', '1223432343233', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekchai', '991112', '991112', '2018-01-01', 'A', '', 'nai', '', '', '', '', 0, '2018-07-18', 1), ('991114', '2312345456542', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekchai', '991114', '991114', '2017-01-01', 'A', '', 'nai', '', '', '', '', 0, '2018-07-18', 1), ('991115', '2345434567654', 'e10adc3949ba59abbe56e057f20f883e', '', '', 'dekchai', '991115', '991115', '2018-01-01', 'A', '', 'nai', '', '', '', '', 0, '2018-07-18', 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_sub_pp6` -- CREATE TABLE `tbl_sub_pp6` ( `DataID` int(11) NOT NULL, `pp6_ID` int(11) DEFAULT NULL, `sub_ID` int(11) DEFAULT NULL, `courseID` varchar(250) NOT NULL, `name` text NOT NULL, `unit` decimal(2,1) NOT NULL, `department` varchar(250) NOT NULL, `status` int(11) NOT NULL, `status_form` int(11) NOT NULL, `score_mid` int(11) DEFAULT NULL, `score_final` int(11) DEFAULT NULL, `score_total` int(11) NOT NULL, `score_desirable` float DEFAULT NULL, `score_rtw` float DEFAULT NULL, `score_attend` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_sub_pp6` -- INSERT INTO `tbl_sub_pp6` (`DataID`, `pp6_ID`, `sub_ID`, `courseID`, `name`, `unit`, `department`, `status`, `status_form`, `score_mid`, `score_final`, `score_total`, `score_desirable`, `score_rtw`, `score_attend`) VALUES (4311, 1745, 430, 'ก45623', 'แนะแนว', '9.9', '', 2, 25, 0, 0, -1, 3, 3, 1), (4312, 1746, 430, 'ก45623', 'แนะแนว', '9.9', '', 2, 25, 0, 0, -1, 3, 3, -1), (4313, 1747, 430, 'ก45623', 'แนะแนว', '9.9', '', 2, 25, 0, 0, -1, 0, 0.4, 1), (4314, 1748, 430, 'ก45623', 'แนะแนว', '9.9', '', 2, 25, 0, 0, -1, 0, 0, 1), (4315, 1749, 430, 'ก45623', 'แนะแนว', '9.9', '', 2, 25, 0, 0, -1, 0, 0, 1), (4316, 1750, 416, '2', '2', '0.0', '', 2, 22, 0, 0, -1, 0, 0, 1), (4317, 1751, 416, '2', '2', '0.0', '', 2, 22, 0, 0, -1, 0, 0, 1), (4318, 1752, 416, '2', '2', '0.0', '', 2, 22, 0, 0, -1, 0, 0, 1), (4319, 1745, 418, 'ค11111', 'คณิตศาสตร์ พื้นฐาน', '1.0', '2', 1, 11, 50, 50, 100, 3, 3, 1); -- -------------------------------------------------------- -- -- Table structure for table `tbl_think_score` -- CREATE TABLE `tbl_think_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_think_score` -- INSERT INTO `tbl_think_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (1, 1, '11141', 3), (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `tbl_write_score` -- CREATE TABLE `tbl_write_score` ( `DataID` int(11) NOT NULL, `course_teachingID` int(11) DEFAULT NULL, `stdID` varchar(250) DEFAULT NULL, `score` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `tbl_write_score` -- INSERT INTO `tbl_write_score` (`DataID`, `course_teachingID`, `stdID`, `score`) VALUES (1, 1, '11141', 3), (133, 447, '01111', 3), (134, 447, '01112', 3), (135, 447, '01117', 3), (138, 449, '01111', 3), (139, 449, '01112', 3), (140, 449, '01117', 3), (143, 451, '01111', 3), (144, 451, '01112', 3), (145, 451, '01117', 3), (146, 453, '01111', 3), (147, 454, '01111', 3), (148, 455, '11141', 3), (149, 456, '11141', 3), (150, 458, '11141', 3), (151, 458, '11144', 3), (152, 459, '11141', 3), (153, 459, '11144', 3), (154, 460, '11141', 3), (155, 460, '11144', 3), (156, 1, '11142', 3); -- -------------------------------------------------------- -- -- Table structure for table `wait_data_objective` -- CREATE TABLE `wait_data_objective` ( `no_order` int(11) NOT NULL, `detail` text NOT NULL, `user_do` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `wait_data_objective` -- INSERT INTO `wait_data_objective` (`no_order`, `detail`, `user_do`) VALUES (10, '10', 21), (20, '20', 21); -- -- Indexes for dumped tables -- -- -- Indexes for table `ath_role_reletion_tasks` -- ALTER TABLE `ath_role_reletion_tasks` ADD PRIMARY KEY (`rel_id`); -- -- Indexes for table `ath_tasks` -- ALTER TABLE `ath_tasks` ADD PRIMARY KEY (`task_id`); -- -- Indexes for table `ath_users` -- ALTER TABLE `ath_users` ADD PRIMARY KEY (`user_id`); -- -- Indexes for table `tbl_add_delete_course` -- ALTER TABLE `tbl_add_delete_course` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_add_delete_course_fk1` (`user_add`); -- -- Indexes for table `tbl_attend_class` -- ALTER TABLE `tbl_attend_class` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_attend_class_fk1` (`course_teaching_stdID`); -- -- Indexes for table `tbl_attend_class_std` -- ALTER TABLE `tbl_attend_class_std` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_attend_class_std_fk1` (`course_teaching_std_id`), ADD KEY `tbl_attend_class_std_fk2` (`set_attend_day_id`); -- -- Indexes for table `tbl_attend_class_week_list` -- ALTER TABLE `tbl_attend_class_week_list` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_course_teacher` -- ALTER TABLE `tbl_course_teacher` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_course_teacher_fk_1` (`teacher_id`), ADD KEY `tbl_course_teacher_fk_2` (`regis_course_id`); -- -- Indexes for table `tbl_course_teaching_std` -- ALTER TABLE `tbl_course_teaching_std` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_course_teaching_std_fk1` (`registed_courseID`), ADD KEY `tbl_course_teaching_std_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_1` -- ALTER TABLE `tbl_desirable_1` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_1_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_1_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_2` -- ALTER TABLE `tbl_desirable_2` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_2_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_2_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_3` -- ALTER TABLE `tbl_desirable_3` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_3_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_3_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_4` -- ALTER TABLE `tbl_desirable_4` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_4_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_4_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_5` -- ALTER TABLE `tbl_desirable_5` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_5_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_5_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_6` -- ALTER TABLE `tbl_desirable_6` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_6_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_6_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_7` -- ALTER TABLE `tbl_desirable_7` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_7_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_7_fk2` (`stdID`); -- -- Indexes for table `tbl_desirable_8` -- ALTER TABLE `tbl_desirable_8` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_desirable_8_fk1` (`course_teachingID`), ADD KEY `tbl_desirable_8_fk2` (`stdID`); -- -- Indexes for table `tbl_exam_final_object` -- ALTER TABLE `tbl_exam_final_object` ADD PRIMARY KEY (`DataID`), ADD KEY `exam_final_object_fk1` (`courseID`), ADD KEY `exam_final_object_fk2` (`objective_conclude`); -- -- Indexes for table `tbl_exam_mid_object` -- ALTER TABLE `tbl_exam_mid_object` ADD PRIMARY KEY (`DataID`), ADD KEY `exam_mid_object_fk1` (`courseID`), ADD KEY `exam_mid_object_fk2` (`objective_conclude`); -- -- Indexes for table `tbl_final_exam_score` -- ALTER TABLE `tbl_final_exam_score` ADD PRIMARY KEY (`DataID`), ADD KEY `final_exam_score_fk1` (`course_teachingID`), ADD KEY `final_exam_score_fk2` (`stdID`); -- -- Indexes for table `tbl_log` -- ALTER TABLE `tbl_log` ADD PRIMARY KEY (`log_id`); -- -- Indexes for table `tbl_log_upclass` -- ALTER TABLE `tbl_log_upclass` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_mid_exam_score` -- ALTER TABLE `tbl_mid_exam_score` ADD PRIMARY KEY (`DataID`), ADD KEY `mid_exam_score_fk1` (`course_teachingID`), ADD KEY `mid_exam_score_fk2` (`stdID`); -- -- Indexes for table `tbl_news` -- ALTER TABLE `tbl_news` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_news_gallery` -- ALTER TABLE `tbl_news_gallery` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_news_gallery_fk1` (`newsID`); -- -- Indexes for table `tbl_news_gallery_sub` -- ALTER TABLE `tbl_news_gallery_sub` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_news_gallery_subpk_fk1` (`newsID`); -- -- Indexes for table `tbl_objective_conclude` -- ALTER TABLE `tbl_objective_conclude` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_objective_conclude_fk1` (`courseID`); -- -- Indexes for table `tbl_objective_score_std` -- ALTER TABLE `tbl_objective_score_std` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_objective_score_std_fk1` (`objectiveID`), ADD KEY `tbl_objective_score_std_fk2` (`staID`), ADD KEY `tbl_objective_score_std_fk3` (`registed_courseID`); -- -- Indexes for table `tbl_pp6` -- ALTER TABLE `tbl_pp6` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_pp6_mid` -- ALTER TABLE `tbl_pp6_mid` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_proportion` -- ALTER TABLE `tbl_proportion` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_proportion_fk1` (`courseID`); -- -- Indexes for table `tbl_read_score` -- ALTER TABLE `tbl_read_score` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_read_score_fk1` (`course_teachingID`), ADD KEY `tbl_read_score_fk2` (`stdID`); -- -- Indexes for table `tbl_registed_course` -- ALTER TABLE `tbl_registed_course` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_registed_course_fk1` (`courseID`); -- -- Indexes for table `tbl_registed_course_teaching` -- ALTER TABLE `tbl_registed_course_teaching` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_registed_course_teaching_fk1` (`registed_courseID`); -- -- Indexes for table `tbl_regis_teacher` -- ALTER TABLE `tbl_regis_teacher` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_regis_teacher_gallery` -- ALTER TABLE `tbl_regis_teacher_gallery` ADD PRIMARY KEY (`DataID`), ADD KEY `regis_teacher_gal_fk1` (`regis_teacher_id`); -- -- Indexes for table `tbl_report_mid` -- ALTER TABLE `tbl_report_mid` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_report_mid_1` (`pp6_mid_ID`); -- -- Indexes for table `tbl_room_export` -- ALTER TABLE `tbl_room_export` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_room_exportfk1` (`registed_courseID`); -- -- Indexes for table `tbl_room_teacher` -- ALTER TABLE `tbl_room_teacher` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_room_teacher_fk1` (`course_teacherID`); -- -- Indexes for table `tbl_rtw_4_score` -- ALTER TABLE `tbl_rtw_4_score` ADD PRIMARY KEY (`DataID`), ADD KEY `rtw_4_score_fk1` (`course_teachingID`), ADD KEY `rtw_4_score_fk2` (`stdID`); -- -- Indexes for table `tbl_rtw_5_score` -- ALTER TABLE `tbl_rtw_5_score` ADD PRIMARY KEY (`DataID`), ADD KEY `rtw_5_score_fk1` (`course_teachingID`), ADD KEY `rtw_5_score_fk2` (`stdID`); -- -- Indexes for table `tbl_set_attend_day` -- ALTER TABLE `tbl_set_attend_day` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_set_attend_day_fk1` (`registed_course_teachingID`), ADD KEY `tbl_set_attend_day_fk2` (`attend_class_week_listID`); -- -- Indexes for table `tbl_set_count_adttend_class` -- ALTER TABLE `tbl_set_count_adttend_class` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_set_count_adttend_class_fk1` (`registed_courseID`); -- -- Indexes for table `tbl_set_term_year` -- ALTER TABLE `tbl_set_term_year` ADD PRIMARY KEY (`DataID`); -- -- Indexes for table `tbl_std_class_room` -- ALTER TABLE `tbl_std_class_room` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_std_class_room_fk1` (`std_ID`); -- -- Indexes for table `tbl_student` -- ALTER TABLE `tbl_student` ADD PRIMARY KEY (`std_ID`); -- -- Indexes for table `tbl_sub_pp6` -- ALTER TABLE `tbl_sub_pp6` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_sub_pp6_fk1` (`pp6_ID`); -- -- Indexes for table `tbl_think_score` -- ALTER TABLE `tbl_think_score` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_think_score_fk1` (`course_teachingID`), ADD KEY `tbl_think_score_fk2` (`stdID`); -- -- Indexes for table `tbl_write_score` -- ALTER TABLE `tbl_write_score` ADD PRIMARY KEY (`DataID`), ADD KEY `tbl_write_score_fk1` (`course_teachingID`), ADD KEY `tbl_write_score_fk2` (`stdID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `ath_role_reletion_tasks` -- ALTER TABLE `ath_role_reletion_tasks` MODIFY `rel_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; -- -- AUTO_INCREMENT for table `ath_tasks` -- ALTER TABLE `ath_tasks` MODIFY `task_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `ath_users` -- ALTER TABLE `ath_users` MODIFY `user_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `tbl_add_delete_course` -- ALTER TABLE `tbl_add_delete_course` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=431; -- -- AUTO_INCREMENT for table `tbl_attend_class` -- ALTER TABLE `tbl_attend_class` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbl_attend_class_std` -- ALTER TABLE `tbl_attend_class_std` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `tbl_course_teacher` -- ALTER TABLE `tbl_course_teacher` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=256; -- -- AUTO_INCREMENT for table `tbl_course_teaching_std` -- ALTER TABLE `tbl_course_teaching_std` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17928; -- -- AUTO_INCREMENT for table `tbl_desirable_1` -- ALTER TABLE `tbl_desirable_1` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_2` -- ALTER TABLE `tbl_desirable_2` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_3` -- ALTER TABLE `tbl_desirable_3` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_4` -- ALTER TABLE `tbl_desirable_4` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_5` -- ALTER TABLE `tbl_desirable_5` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_6` -- ALTER TABLE `tbl_desirable_6` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_7` -- ALTER TABLE `tbl_desirable_7` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_desirable_8` -- ALTER TABLE `tbl_desirable_8` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_exam_final_object` -- ALTER TABLE `tbl_exam_final_object` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbl_exam_mid_object` -- ALTER TABLE `tbl_exam_mid_object` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbl_final_exam_score` -- ALTER TABLE `tbl_final_exam_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=258; -- -- AUTO_INCREMENT for table `tbl_log` -- ALTER TABLE `tbl_log` MODIFY `log_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=715; -- -- AUTO_INCREMENT for table `tbl_log_upclass` -- ALTER TABLE `tbl_log_upclass` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbl_mid_exam_score` -- ALTER TABLE `tbl_mid_exam_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=258; -- -- AUTO_INCREMENT for table `tbl_news` -- ALTER TABLE `tbl_news` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52; -- -- AUTO_INCREMENT for table `tbl_news_gallery` -- ALTER TABLE `tbl_news_gallery` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT for table `tbl_news_gallery_sub` -- ALTER TABLE `tbl_news_gallery_sub` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=43; -- -- AUTO_INCREMENT for table `tbl_objective_conclude` -- ALTER TABLE `tbl_objective_conclude` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=49; -- -- AUTO_INCREMENT for table `tbl_objective_score_std` -- ALTER TABLE `tbl_objective_score_std` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=515; -- -- AUTO_INCREMENT for table `tbl_pp6` -- ALTER TABLE `tbl_pp6` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1753; -- -- AUTO_INCREMENT for table `tbl_pp6_mid` -- ALTER TABLE `tbl_pp6_mid` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=552; -- -- AUTO_INCREMENT for table `tbl_proportion` -- ALTER TABLE `tbl_proportion` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1779; -- -- AUTO_INCREMENT for table `tbl_read_score` -- ALTER TABLE `tbl_read_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=159; -- -- AUTO_INCREMENT for table `tbl_registed_course` -- ALTER TABLE `tbl_registed_course` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=712; -- -- AUTO_INCREMENT for table `tbl_registed_course_teaching` -- ALTER TABLE `tbl_registed_course_teaching` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=484; -- -- AUTO_INCREMENT for table `tbl_regis_teacher` -- ALTER TABLE `tbl_regis_teacher` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=328; -- -- AUTO_INCREMENT for table `tbl_report_mid` -- ALTER TABLE `tbl_report_mid` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1636; -- -- AUTO_INCREMENT for table `tbl_room_export` -- ALTER TABLE `tbl_room_export` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=241; -- -- AUTO_INCREMENT for table `tbl_room_teacher` -- ALTER TABLE `tbl_room_teacher` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=213; -- -- AUTO_INCREMENT for table `tbl_rtw_4_score` -- ALTER TABLE `tbl_rtw_4_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=157; -- -- AUTO_INCREMENT for table `tbl_rtw_5_score` -- ALTER TABLE `tbl_rtw_5_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=157; -- -- AUTO_INCREMENT for table `tbl_set_attend_day` -- ALTER TABLE `tbl_set_attend_day` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=696; -- -- AUTO_INCREMENT for table `tbl_std_class_room` -- ALTER TABLE `tbl_std_class_room` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34; -- -- AUTO_INCREMENT for table `tbl_sub_pp6` -- ALTER TABLE `tbl_sub_pp6` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4320; -- -- AUTO_INCREMENT for table `tbl_think_score` -- ALTER TABLE `tbl_think_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=157; -- -- AUTO_INCREMENT for table `tbl_write_score` -- ALTER TABLE `tbl_write_score` MODIFY `DataID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=157;COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/modules/authen_user/index.php <?php $create_user_ath = $role->ath_user_reletion_tasks('create_user_ath',$user_role_id); //สามารถแก้ไข ข้อมูลการสั่งซื้อได้ $edit_user_ath = $role->ath_user_reletion_tasks('edit_user_ath',$user_role_id); //สามารถแก้ไข ข้อมูลการสั่งซื้อได้ $del_user_ath = $role->ath_user_reletion_tasks('del_user_ath',$user_role_id); //สามารถแก้ไข ข้อมูลการสั่งซื้อได้ ?> <!-- START CONTAINER FLUID --> <div class="container-fluid container-fixed-lg m-t-20"> <div class="row"> <div class="col-md-12"> <!-- START PANEL --> <form id="frm_search"> <div class="panel panel-default"> <div class="panel-heading"> <div class="panel-title">Authentication Search</div> </div> <div class="panel-body"> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default "> <label>USER Name</label> <input name="data_name" type="text" class="form-control" placeholder=""> </div> </div> <div class="col-sm-4"> <div class="form-group form-group-default form-group-default-select2 "> <label class="">STATUS</label> <select class="full-width" name="data_status" data-placeholder="Select Status" data-init-plugin="select2"> <option value="">All status</option> <option value="1">Published </option> <option value="0">Save Draft </option> </select> </div> </div> <div class="col-sm-2 text-right m-t-10"> <a href="javascript:;" id="btn__search" class="btn btn-complete btn-cons"> <i class="pg-search p-r-5"></i> Search</a> <!-- <a href="javascript:;" id="btn__insert" class="btn btn-success btn-cons"><i class="fa fa-plus p-r-5"></i> CREATE BRAND</a> --> </div> </div> </div> </div> </form> <!-- END PANEL --> </div> </div> </div> <!-- END CONTAINER FLUID --> <!-- START CONTAINER FLUID --> <div class="container-fluid container-fixed-lg"> <div class="row"> <div class="col-md-12"> <!-- START PANEL --> <div class="panel panel-default"> <div class="panel-heading"> <div class="col-md-6"><div class="panel-title">USER Authentication LIST</div></div> <div class="col-md-6 text-right"> <div class="btn-group"> <?php if($create_user_ath){ ?><button id="btn__insert" type="button" class="btn btn-success"><i class="fa fa-plus"></i></button><?php } ?> <?php if($del_user_ath){ ?><button id="btn__remove" type="button" class="btn btn-danger"><i class="fa fa-trash-o"></i></button><?php } ?> </div> </div> </div> <div class="panel-body"> <div id="tb_data_list" class="table-responsive"> <table class="table table-hover table-condensed " id="detailedTable"> <thead> <tr> <th style="width:7%" > <div class="checkbox check-success" style="padding-left:2px !important;"> <input type="checkbox" id="checkbox_all"> <label for="checkbox_all">&nbsp;</label> </div> </th> <th style="">USER NAME</th> <th style="">ROLES</th> <th style="width:15%">STATUS</th> </tr> </thead> <tbody> </tbody> </table> <div class="col-md-6"></div> <div id="data_pagination" class="col-md-6 text-right m-t-0" > <ul class="pagination m-t-0"> <!-- <li><a href="#">&laquo;</a></li> <li class="active"><a href="#">1</a></li> <li class="disabled"><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li><a href="#">&raquo;</a></li> --> </ul> </div> </div> </div> </div> <!-- END PANEL --> </div> </div> </div> <!-- END CONTAINER FLUID --> <!-- Modal --> <div class="modal fade slide-up disable-scroll" id="modal_msg" tabindex="-1" role="dialog" aria-hidden="false"> <div class="modal-dialog modal-sm"> <div class="modal-content-wrapper"> <div class="modal-content"> <div class="modal-body text-center m-t-20"> <div id="popup_msg"></div> <button type="button" class="btn btn-primary btn-cons" data-dismiss="modal">Continue</button> </div> </div> </div> <!-- /.modal-content --> </div> </div> <!-- /.modal-dialog --> <!-- Modal --> <div class="modal fade slide-up disable-scroll" id="modal_cancel" tabindex="-1" role="dialog" aria-hidden="false"> <div class="modal-dialog modal-me"> <div class="modal-content-wrapper"> <div class="modal-content"> <div class="modal-body text-center m-t-20"> <h4 class="no-margin p-b-10">Are you sure you want to delete?</h4> <button type="button" class="btn btn-cons" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-danger" id="btn__conf_remove" >Delete</button> </div> </div> </div> <!-- /.modal-content --> </div> </div> <!-- /.modal-dialog --> <file_sep>/src/lang.php <?php session_start(); if (isset($_GET['ss_lang']) && $_GET['ss_lang']=='en' || $_GET['ss_lang']=='th') { $_SESSION['ss_lang']=$_GET['ss_lang']; } ?><file_sep>/includes/left-tab.php <?php $op=$_GET['op']; ?> <div class="col-sm-3 logo-tab" > <div class="row" > <nav class="navbar-default"> <div class="btn-mobile"> <button type="button" class="navbar-toggle" onclick="addTopMenu()"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="col-md-3 col-sm-3 col-xs-3"> <img class="logo-nav" src="assets/images/logo_bg_white.png" > </div> <div class="col-md-9 col-sm-9 col-xs-7"> <h4 class="title-text">ระบบวัดและประเมินผล</h4> <h5 class="title-sub-text"> โรงเรียนเทศบาลวัดสระทอง</h5> </div> </nav> </div> <div class="row"> <div class="left-menu"> <ul class="nav nav-pills nav-stacked left-text-set" > <?php if (isset($_SESSION['ss_status_std']) && $_SESSION['ss_status_std']==1) { ?> <li role="presentation" class="active-menu"><a href="index.php?op=chk_grade-index"><img class="img-icon-left" src="assets/images/03.png">ผลการศึกษา</a></li> <?php }else{ ?> <?php if($_SESSION['ss_status']==1){ ?> <li role="presentation" class="<?php if(!isset($op)){echo "active-menu";} ?>"><a href="index.php"><img class="img-icon-left" src="assets/images/01.png">หน้าแรก</a></li> <li role="presentation" class="<?php if($op=='profile-index' || $op=='profile-edit'){echo "active-menu";} ?>"><a href="index.php?op=profile-index"><img class="img-icon-left" src="assets/images/02.png">ข้อมูลส่วนตัว</a></li> <li role="presentation" class="<?php if($op=='summary-index'){echo "active-menu";} ?>"><a href="index.php?op=summary-index"><img class="img-icon-left" src="assets/images/03.png">แก้ไขผลการเรียน</a></li> <li role="presentation" class="<?php if($op=='print-index'){echo "active-menu";} ?>"><a href="index.php?op=print-index"><img class="img-icon-left" src="assets/images/04.png">พิมพ์ใบ ปพ.5</a></li> <li role="presentation"><a target="_blank" href="file_managers/manual/manual_teacher.pdf"><img class="img-icon-left" src="assets/images/05.png">ดาวน์โหลดคู่มือ</a></li> <?php }elseif($_SESSION['ss_status']==2){ ?> <li role="presentation" class="<?php if(!isset($op)){echo "active-menu";} ?>"><a href="index.php"><img class="img-icon-left" src="assets/images/01.png">หน้าแรก</a></li> <li role="presentation" class="<?php if($op=='profile-index' || $op=='profile-edit'){echo "active-menu";} ?>"><a href="index.php?op=profile-index"><img class="img-icon-left" src="assets/images/02.png">ข้อมูลส่วนตัว</a></li> <li role="presentation" class="<?php if($op=='summary-index'){echo "active-menu";} ?>"><a href="index.php?op=summary-index"><img class="img-icon-left" src="assets/images/03.png">แก้ไขผลการเรียน</a></li> <li role="presentation" class="<?php if($op=='report_std_personal-index'){echo "active-menu";} ?>"><a href="index.php?op=report_std_personal-index"><img class="img-icon-left" src="assets/images/pp6.png">พิมพ์ใบ ปพ.6</a></li> <li role="presentation"><a target="_blank" href="file_managers/manual/admin_eva.pdf"><img class="img-icon-left" src="assets/images/05.png">ดาวน์โหลดคู่มือ</a></li> <?php }elseif($_SESSION['ss_status']==3){ ?> <li role="presentation" class="<?php if(!isset($op)){echo "active-menu";} ?>"><a href="index.php"><img class="img-icon-left" src="assets/images/01.png">หน้าแรก</a></li> <li role="presentation" class="<?php if($op=='profile-index' || $op=='profile-edit'){echo "active-menu";} ?>"><a href="index.php?op=profile-index"><img class="img-icon-left" src="assets/images/02.png">ข้อมูลส่วนตัว</a></li> <li role="presentation"><a target="_blank" href="file_managers/manual/admin_news.pdf"><img class="img-icon-left" src="assets/images/05.png">ดาวน์โหลดคู่มือ</a></li> <?php }elseif($_SESSION['ss_status']==4){ ?> <li role="presentation" class="<?php if(!isset($op)){echo "active-menu";} ?>"><a href="index.php"><img class="img-icon-left" src="assets/images/01.png">หน้าแรก</a></li> <li role="presentation" class="<?php if($op=='profile-index' || $op=='profile-edit'){echo "active-menu";} ?>"><a href="index.php?op=profile-index"><img class="img-icon-left" src="assets/images/02.png">ข้อมูลส่วนตัว</a></li> <li role="presentation" class="<?php if($op=='report_std_personal-index'){echo "active-menu";} ?>"><a href="index.php?op=report_std_personal-index"><img class="img-icon-left" src="assets/images/pp6.png">พิมพ์ใบ ปพ.6</a></li> <li role="presentation"><a target="_blank" href="file_managers/manual/admin_grade_level.pdf"><img class="img-icon-left" src="assets/images/05.png">ดาวน์โหลดคู่มือ</a></li> <?php } ?> <?php } ?> </ul> <a href="modules/logout/process.php"> <div class="logout-box"> <div class="logout-first-box"> <img class="img-power" src="assets/images/power.png"> </div> <div class="logout-sec-box"> <p>ออกจากระบบ</p> </div> </div> </a> </div> </div> </div><file_sep>/modules/chk_grade/index.js var opPage = 'chk_grade'; $(document).ready(function() { get_grade(); }); function get_grade() { var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_grade" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#menu_year_list").html(data.menu_year_list); $("#table_place").html(data.table_list); $("#std_ID").html(data.std_ID); $("#full_name").html(data.full_name); $("#class_level").html(data.class_level); $("#room").html(data.room); }); }<file_sep>/modules/conclusion/class_modules/learing_resualt_mid.php <?php class ClassData extends Databases { public function get_mid_head($class_level,$room,$year){ $this->sql ="SELECT DISTINCT(sub_ID),courseID,department FROM tbl_report_mid WHERE pp6_mid_ID in( SELECT DataID FROM tbl_pp6_mid WHERE class_level='$class_level' AND room='$room' AND term='1,2' AND year='$year' ) ORDER BY sub_ID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $courseID= $value['courseID']; $department_data=$value['department']; $department=$this->get_department($department_data); $data_response['head_list'].=' <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> '.$department.' </div> </th> '; $data_response['sum_100_list'].=' <th style="text-align: center;">100</th> '; } $data_response['head_list'].=' <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> คะแนนรวม </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ร้อยละ </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> อันดับที่ </div> </th> '; return $data_response; } public function get_course_list($pp6_mid_id,$i,$year_data,$room,$class_level_data,$std_ID){ $this->sql ="SELECT * FROM tbl_report_mid WHERE pp6_mid_ID=$pp6_mid_id AND status=1 ORDER BY sub_ID ASC "; $this->select(); $this->setRows(); $score_total_count=0; $score_by_unit_row=0; $fully_score_count=0; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $score_total= $value['score_total']; if($score_total==-1){ $grade_set='ร'; }else{ $grade_set=$score_total; $grade_set_dec=$this->get_grade($score_total); $score_total_count=$score_total_count+$score_total; } if ($i==1) { $data_response.=' <td style="width: 1%;">'.$grade_set.'</td> '; }elseif($i>1){ $data_response.=' <td style="width: 1%;">'.$grade_set.'</td> '; } $fully_score_count=$fully_score_count+50; } $find_percentage=($score_total_count*100)/$fully_score_count; $find_position=$this->find_position($year_data,$class_level_data,$room); arsort($find_position); $arrayValuePosition=$this->arrayValuePositionNew($find_position,$std_ID); $data_response.=' <td style="width: 1%;">'.$score_total_count.'</td> <td style="width: 1%;">'.number_format($find_percentage,2).'</td> <td style="width: 1%;">'.$arrayValuePosition.'</td> '; return $data_response; } public function find_position($year_data,$class_level_data,$room){ $data_response = array(); $this->sql ="SELECT distinct(tbl_pp6_mid.std_ID) as std_pp6_id,tbl_pp6_mid.DataID as pp6_id FROM tbl_pp6_mid,tbl_report_mid WHERE tbl_pp6_mid.DataID=tbl_report_mid.pp6_mid_ID AND tbl_pp6_mid.year='$year_data' AND tbl_pp6_mid.room='$room' AND tbl_pp6_mid.class_level='$class_level_data' AND tbl_report_mid.status=1 "; $this->select(); $this->setRows(); $find_gpa_sum=0; $score_final_count=0; foreach($this->rows as $key => $value) { $std_pp6_id=$value['std_pp6_id']; $pp6_id=$value['pp6_id']; $data_big_std= $this->get_data_big_std($std_pp6_id,$pp6_id); $test[$std_pp6_id] = $data_big_std; } return $test; } public function get_data_big_std($std_pp6_id,$pp6_id){ $this->sql ="SELECT sum(score_total) as sumed FROM tbl_pp6_mid,tbl_report_mid WHERE tbl_pp6_mid.DataID=tbl_report_mid.pp6_mid_ID AND tbl_report_mid.pp6_mid_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); return $this->rows[0]['sumed']; } public function arrayValuePositionNew($find_position,$std_ID){ $result = array(); $pos = $real_pos = 0; $prev_score = -1; foreach ($find_position as $exam_n => $score) { $real_pos += 1;// Natural position. $pos = ($prev_score != $score) ? $real_pos : $pos;// If I have same score, I have same position in ranking, otherwise, natural position. $result[$exam_n] = array( "score" => $score, "position" => $pos, "exam_no" => $exam_n ); $prev_score = $score;// update last score. } return $result[$std_ID]["position"]; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_count_std($class_level,$room,$year){ $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_pp6_mid WHERE class_level='$class_level' AND room='$room' AND term='1,2' AND year='$year' "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_mid_data($class_level,$room,$year,$image_logo,$footer_text){ $mid_head=$this->get_mid_head($class_level,$room,$year); $count_std=$this->get_count_std($class_level,$room,$year); if ($count_std<=38) { $set_loop_html=2; }else{ $set_loop_html=3; } if ($set_loop_html==1) { $loop_data=$this->get_loop_data($class_level,$room,$year); $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:16px"> <img class="logo-print-size" src="'.$image_logo.'"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 30px;">ระดับชั้น <span style="font-weight: normal;">ประถมศึกษาปีที่ '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">กลางปี</span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> <p style="margin-top: 10px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 15px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th rowspan="2" style="width: 20%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> <tr> '.$mid_head['sum_100_list'].' <th></th> <th></th> <th></th> </tr> </thead> <tbody > '.$loop_data.' </tbody> </table> </page> </div> <div style="page-break-after:always;"> <page > '.$footer_text.' </page> </div> '; }else{ if ($set_loop_html==2) { for ($i=1; $i <=$set_loop_html ; $i++) { $loop_data=$this->get_loop_data($class_level,$room,$year,$i,$set_loop_html); if ($i==1) { $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:16px"> <img class="logo-print-size" src="'.$image_logo.'"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 30px;">ระดับชั้น <span style="font-weight: normal;">ประถมศึกษาปีที่ '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">กลางปี</span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> <p style="margin-top: 10px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 15px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th rowspan="2" style="width: 20%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> <tr> '.$mid_head['sum_100_list'].' <th></th> <th></th> <th></th> </tr> </thead> <tbody > '.$loop_data.' </tbody> </table> </page> </div> '; }else{ $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 15px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th rowspan="2" style="width: 20%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> <tr> '.$mid_head['sum_100_list'].' <th></th> <th></th> <th></th> </tr> </thead> <tbody > '.$loop_data.' </tbody> </table> '.$footer_text.' </page> </div> '; } } }else{ for ($i=1; $i <=$set_loop_html ; $i++) { $loop_data=$this->get_loop_data($class_level,$room,$year,$i,$set_loop_html); if ($i==1) { $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:16px"> <img class="logo-print-size" src="'.$image_logo.'"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 30px;">ระดับชั้น <span style="font-weight: normal;">ประถมศึกษาปีที่ '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">กลางปี</span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> <p style="margin-top: 10px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 15px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th rowspan="2" class="rotate" style="width: 1%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th rowspan="2" style="width: 20%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> '.$mid_head['head_list'].' </tr> <tr> '.$mid_head['sum_100_list'].' <th></th> <th></th> <th></th> </tr> </thead> <tbody > '.$loop_data.' </tbody> </table> </page> </div> '; }elseif($i==2){ $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 15px;"> <tbody > '.$loop_data.' </tbody> </table> </page> </div> '; }elseif($i==3){ $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 15px;"> <tbody > '.$loop_data.' </tbody> </table> '.$footer_text.' </page> </div> '; } } } } return $data_response; } public function get_loop_data($class_level,$room,$year,$i,$set_loop_html){ if ($i!='') { if ($set_loop_html<3) { if ($i==1) { $find_start=0; $find_end=19; }elseif($i==2){ $find_start=19; $find_end=19; } }else{ if ($i==1) { $find_start=0; $find_end=19; }elseif($i==2){ $find_start=19; $find_end=25; }else{ $find_start=44; $find_end=25; } } $this->sql ="SELECT * FROM tbl_pp6_mid WHERE class_level='$class_level' AND room='$room' AND term='1,2' AND year='$year' ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END LIMIT $find_start,$find_end "; $this->select(); $this->setRows(); $number=$find_start+1; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $std_ID= $value['std_ID']; $name_title_set= $value['name_title']; $name_title=$this->get_name_title($name_title_set); $fname=$value['fname']; $lname=$value['lname']; $class_level=$value['class_level']; $name=$name_title.$fname.' '.$lname; $course_list=$this->get_course_list($DataID,$i,$year,$room,$class_level,$std_ID); $data_response.=' <tr> <td style="width: 3%;">'.$number.'</td> <td style="width: 5%;">'.$std_ID.'</td> <td style="text-align:left;padding-left:10px;width: 28%;">'.$name.'</td> '.$course_list.' </tr> '; $number++; } }else{ $this->sql ="SELECT * FROM tbl_pp6_mid WHERE class_level='$class_level' AND room='$room' AND term='1,2' AND year='$year' ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $number=1; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $std_ID= $value['std_ID']; $name_title_set= $value['name_title']; $name_title=$this->get_name_title($name_title_set); $fname=$value['fname']; $lname=$value['lname']; $class_level=$value['class_level']; $name=$name_title.$fname.' '.$lname; $course_list=$this->get_course_list($DataID,-1,$year,$room,$class_level,$std_ID); $data_response.=' <tr> <td>'.$number.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:10px;">'.$name.'</td> '.$course_list.' </tr> '; $number++; } } return $data_response; } public function get_data_list($class_level,$room_data,$term_data,$year_data){ if ($term_data=='mid') { $this->sql ="SELECT DISTINCT(room) as room,class_level,year FROM tbl_pp6_mid WHERE class_level='$class_level' AND room='$room_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); $term= 'กลางปี'; $year= $value['year']; $data_response.=' <tr class="text-table-center"> <td>'.$class_label.'</td> <td>'.$room.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_mid.php?class_level='.$class_level.'&room='.$room.'&term=mid&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } }else{ $this->sql ="SELECT DISTINCT(room) as room,class_level,term,year FROM tbl_pp6 WHERE class_level='$class_level' AND room='$room_data' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room= $value['room']; $class_level= $value['class_level']; $class_label=$this->get_class_level($class_level); if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term='ปลายปี'; }else{ $term= $value['term']; } $year= $value['year']; $data_response.=' <tr class="text-table-center"> <td><input id="checkbox_all" type="checkbox"></td> <td>'.$class_label.'</td> <td>'.$room.'</td> <td>'.$term.'</td> <td>'.$year.'</td> <td> <a target="_blank" href="modules/conclusion/form/learning_result_final.php?class_level='.$class_level.'&room='.$room.'&term=mid&year='.$year.'" style="color: #ac68cc;"> <span class="glyphicon glyphicon-print" aria-hidden="true"></span> </a> </td> </tr> '; } } return json_encode($data_response); } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_registed_course ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพฯ'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; case 9: $department='หน้าที่พลเมือง'; break; case 10: $department='ศิลปะพื้นบ้าน'; break; case 11: $department='ศักยภาพ'; break; case 12: $department='ภาษาจีน'; break; default: $department=''; } return $department; } }<file_sep>/modules/authen_user/index.js var opPage = 'authen_user'; var sort_column = 'cdate'; var sort_by = 'desc'; var cur_parent_id = '0'; var pages_sec = 1; $(document).ready(function() { get_data_list(pages_sec,'cdate','desc'); if (_get.data == 'success') { $('#popup_msg').html('<h4 class="no-margin p-b-10">The changes have been saved.</h4>'); $('#modal_msg').modal('show'); } }); function get_data_list(pages_current,sort_column,sort_by){ // POST var formData = $( "#frm_search" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_list" }); formData.push({ "name": "sort_column", "value": sort_column}); formData.push({ "name": "sort_by", "value": sort_by}); formData.push({ "name": "pages_current", "value": pages_current }); // console.log($.param(formData)); $.ajax({ url: 'modules/' + opPage + '/process.php',type: 'GET',data: formData}).done(function(data) {console.log(data);}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus) { console.log(data.data_list); $('#tb_data_list').find('tbody').html(data.data_list); $('#data_pagination').find('ul').html(data.data_pagination); }); } $(document).delegate('.chg_pagination', 'click', function(event) { pages_sec = $(this).attr('data-id'); get_data_list(pages_sec,sort_column,sort_by); }); $(document).delegate('#btn__search', 'click', function(event) { pages_sec = 1; get_data_list(pages_sec,sort_column,sort_by); }); $(document).delegate('#btn__insert', 'click', function(event) { window.location = 'index.php?op='+opPage+'-from'; }); $(document).delegate('#btn__remove', 'click', function(event) { $('#modal_cancel').modal('show'); }); $(document).delegate('#btn__conf_remove', 'click', function(event) { var tempValue=$("input[name='checkbox_delete[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var formData = new Array(); formData.push({ "name": "acc_action", "value": "data_remove" }); formData.push({ "name": "data_val", "value": tempValue}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_data_list('1','cdate','desc'); $('#modal_cancel').modal('hide'); }); }); $(document).delegate('#checkbox_all', 'click', function(event) { if(this.checked) { // check select status $('.checkbox_data').each(function() { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); }else{ $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } }); // $(document).delegate('#btn_edit_changes', 'click', function(event) { // var cat_id = $(this).attr('data-id'); // var parent_id = $('#parent_id').val(); // $("#frm_data").attr("action", 'modules/' + opPage + '/process.php?kno_action=edit_post&id='+cat_id+'&cid='+parent_id); // $("#frm_data").attr("target", '_self'); // $('#frm_data').submit(); // }); // $(document).delegate('#btn_new_post', 'click', function(event) { // window.location = 'index.php?op=' + opPage + '-form'+'&cid='+cur_parent_id; // }); // $(document).delegate('.btn_edit', 'click', function(event) { // var cat_id = $(this).attr('data-id'); // window.location = 'index.php?op=' + opPage + '-form&id='+cat_id+'&cid='+cur_parent_id; // }); // $(document).delegate('.btn_sequence', 'click', function(event) { // var data_id = $(this).attr('data-id'); // var sequence = $('#sequence_'+data_id).val(); // var sequence_old = $('#sequence_'+data_id).attr('data-id'); // if(confirm("Are you sure you want to move ?")) { // $.post('modules/' + opPage + '/process.php', { // 'kno_action' : 'sequence_data', // 'parent_id' : cur_parent_id, // 'data_id' : data_id, // 'sequence_old' : sequence_old, // 'sequence' : sequence // }, function(response) { // // alert(response); // window.location.reload(); // }); // } // }); // $(document).delegate('.bt_delete', 'click', function(event) { // var par_id = $(this).attr('data-id'); // if(confirm("Are you sure you want to delete")) { // $.post('modules/' + opPage + '/process.php', { // 'kno_action' : 'del_kno_category', // 'par_id' : par_id // }, function(response) { // window.location.reload(); // }); // } // return false; // });<file_sep>/assets/js/modal-alert.js /*Get the modal var modal = document.getElementById('myModal-alert'); var modalRegistedEdit = document.getElementById('myModal-alert-registed-edit'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); var btnRegistedEdit = document.getElementById("myBtn-registed-edit"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close-modal")[0]; var closeBtn = document.getElementsByClassName("close-modal-alert")[0]; // When the user clicks the button, open the modal btn.onclick = function() { modal.style.display = "block"; } btnRegistedEdit.onclick = function() { modalRegistedEdit.style.display = "block"; } // When the user clicks on <span> (x), close the modal closeBtn.onclick = function() { modal.style.display = "none"; } span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }*/ <file_sep>/modules/report_std_personal/index.js var opPage = 'report_std_personal'; $(document).ready(function() { get_year(); get_std_list(); }); function get_year(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_year" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#year_data").html(data); }) } $(document).delegate('#btn_search_name_id', 'click', function(event) { var formData = $( "#form_search_name_id" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_std_list" }); formData.push({ "name": "search_status", "value": "name_id" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list").html(data); }) }); $(document).delegate('#btn_search_class_room', 'click', function(event) { get_std_list(); }); function get_std_list(){ var formData = $( "#frm_search_class_room" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_std_list" }); formData.push({ "name": "search_status", "value": "class_room" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list").html(data); }) } $(document).delegate('#chk_value_select', 'click', function(event) { var tempValue=$("input[name='checkbox_print[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var term =$("#term_data").val(); var year =$("#year_data").val(); var class_level_set =$(".class_level_set").val(); if (class_level_set=='p1' || class_level_set=='p2' || class_level_set=='p3' || class_level_set=='p4' || class_level_set=='p5' || class_level_set=='p6') { window.open( 'modules/report_std_personal/report_form_p.php?std_ID='+tempValue+'&term='+term+'&year='+year, '_blank' // <- This is what makes it open in a new window. ); }else{ window.open( 'modules/report_std_personal/report_form_m.php?std_ID='+tempValue+'&term='+term+'&year='+year, '_blank' // <- This is what makes it open in a new window. ); } }); $(document).delegate('#checkbox_all', 'click', function(event) { if(this.checked) { // check select status $('.checkbox_data').each(function() { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); }else{ $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } });<file_sep>/modules/up_class/view.js var opPage = 'up_class'; $(document).ready(function() { data_year_search_student(); }); $(document).delegate('#btn_name_id_search', 'click', function(event) { get_data(); }); function data_year_search_student() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "data_year_search_student" }); formData.push({ "name": "data_class_search", "value": _get.class_level }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list").html(data.table_list); }); } <file_sep>/modules/attend_class/backup2/index.js var opPage = 'attend_class'; $(document).ready(function() { get_coures_id_list(); //$(".course_detal_box").hide(); }); function save_attend(value,attend_id,course_teaching_stdID,set_attend_day_id,week){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "save_attend" }); formData.push({ "name": "status", "value": value.value }); formData.push({ "name": "attend_id", "value": attend_id }); formData.push({ "name": "course_teaching_stdID", "value": course_teaching_stdID }); formData.push({ "name": "set_attend_day_id", "value": set_attend_day_id }); formData.push({ "name": "week", "value": week }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_week_list_data(); }) } function set_day(value_day){ var hr_set=$(".hr_set_"+value_day.value).val(); var registed_course_id=$("#registed_course_id").val(); var value_day=value_day.value; var formData = new Array(); formData.push({ "name": "acc_action", "value": "set_day" }); formData.push({ "name": "registed_course_id", "value": registed_course_id }); formData.push({ "name": "value_day", "value": value_day }); formData.push({ "name": "hr_set", "value": hr_set }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_day_list(); get_day_set(); }) } function get_day_set() { var registed_course_id=$("#registed_course_id").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_day_set" }); formData.push({ "name": "registed_course_id", "value": registed_course_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#get_day_set").html(data); }) } function get_week_list_data() { var registed_course_teaching_id=$("#registed_course_id").val(); var room_search=$("#room_search").val(); var length_list_val=$("#length_list_val").val(); var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_week_list_data" }); formData.push({ "name": "room_search", "value": room_search}); formData.push({ "name": "length_list_val", "value": length_list_val}); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val}); formData.push({ "name": "registed_course_teaching_id", "value": registed_course_teaching_id}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#header_sum_score").html(data.num_day); $("#all_attendID").val(data.all_attendID); $("#std_id_all").val(data.std_id_all); $("#detail_std").html(data.detail_std); //open_edit_attend(); }) } function get_day_list() { var registed_course_id=$("#registed_course_id").val(); var length_list_val=$("#length_list_val").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_day_list" }); formData.push({ "name": "registed_course_id", "value": registed_course_id}); formData.push({ "name": "length_list_val", "value": length_list_val}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { //alert(data) if (parseInt(data.num_attend_day)==0) { $(".num_attend_day_chk").css('display','none'); $(".alert_attend_day_chk").css('display','block'); }else{ $(".num_attend_day_chk").css('display','block'); $(".alert_attend_day_chk").css('display','none'); } $("#set_colspan_save_score_title").attr("colspan",data.data_count+2); $("#week_title").attr("colspan",data.data_count); $("#week_title").html(data.week_title); $("#week_header").html(data.week_header); $(".set_header_width").attr("width",400/data.data_count); get_week_list_data(); }) } $(document).delegate('#btn_search_course_detail', 'click', function(event) { var formData = $( "#frm_data_room" ).serializeArray(); formData.push({ "name": "acc_action", "value": "search_course_detail" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#length_list_val").html(data.week_menu_data); $("#place_detail_courseID").html(data.courseID); $("#place_detail_name").html(data.name); $("#place_detail_unit").html(data.unit); $("#place_detail_hr_learn").html(data.hr_learn); $("#place_detail_class_level").html(data.class_level_co); $("#hr-co-text-depart_course").show(); $(".course_detal_box").show(); $("#registed_course_id").val(data.registed_course_id); get_day_set(); get_day_list(); //get_config(); }) }) function get_class_level() { var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_class_level" }); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#place_class_level").html(data.class_level); $("#room_search").html(data.room); }) } function get_coures_id_list() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_coures_id_list" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#coures_id_list").html(data.coures_id_list); get_class_level(); }) }<file_sep>/modules/regis_course_teaching/back/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_term_year_now"){ echo $class_data->get_term_year_now(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_teaching_student_only"){ $data_id=$_GET['data_id']; $data_room=$_GET['data_room']; echo $class_data->get_teaching_student_only($data_id,$data_room); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_course_teaching_student"){ $data_id=$_GET['data_id']; echo $class_data->get_course_teaching_student($data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_propotion_objective"){ $data_id_first=$_GET['data_id_first']; echo $class_data->get_propotion_objective($data_id_first); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_objective_place_plus"){ $data_responds=' <div class="set-line pl-20 object-mb-set mt-nega-10"> <p class=" text-inline">ข้อที่</p> <div class="input-group form-serch-width-small"> <input name="no_order_new[]" type="text" class="form-control form-set" aria-describedby="basic-addon1" value=""> </div> <p class=" text-inline">ตัวชี้วัด</p> <div class="input-group form-serch-width-large"> <input name="detail_new[]" type="text" class="form-control form-set" aria-describedby="basic-addon1" value=""> </div> <div id="btn_plus_objective" class="btn-search"> <span class="text-icon">+</span> </div> </div> '; echo json_encode($data_responds); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "plus_objective"){ $no_order_new=$_GET['no_order_new']; $detail_new=$_GET['detail_new']; $user_id=$_SESSION['ss_user_id']; for ($i=0; $i < count($no_order_new) ; $i++) { $data_responds.=' <div class="set-line pl-20 object-mb-set mt-10"> <p class=" text-inline">ข้อที่</p> <div class="input-group form-serch-width-small"> <input name="no_order_new[]" type="text" class="form-control form-set" aria-describedby="basic-addon1" value="'.$no_order_new[$i].'"> </div> <p class=" text-inline">ตัวชี้วัด</p> <div class="input-group form-serch-width-large"> <input name="detail_new[]" type="text" class="form-control form-set" aria-describedby="basic-addon1" value="'.$detail_new[$i].'"> </div> </div> '; } $data_responds.=' <div class="set-line pl-20 object-mb-set "> <p class=" text-inline">ข้อที่</p> <div class="input-group form-serch-width-small"> <input name="no_order_new[]" type="text" class="form-control form-set" aria-describedby="basic-addon1" value=" "> </div> <p class=" text-inline">ตัวชี้วัด</p> <div class="input-group form-serch-width-large"> <input name="detail_new[]" type="text" class="form-control form-set" aria-describedby="basic-addon1" value=" "> </div> <div id="btn_plus_objective" class="btn-search"> <span class="text-icon">+</span> </div> </div> '; echo json_encode($data_responds); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "add_data_proportion"){ $course_id=$_POST['course_id']; $arr_sql["courseID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($course_id)))."'"; $arr_sql["comulative"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['comulative'])))."'"; $arr_sql["mid_exam"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['mid_exam'])))."'"; $arr_sql["final_exam"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['final_exam'])))."'"; echo $class_data->insert_data_proportion($arr_sql,$course_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "add_objective_conclude"){ $course_id=$_POST['course_id']; $no_order_new=$_POST['no_order_new']; $detail_new=$_POST['detail_new']; for ($i=0; $i < count($no_order_new) ; $i++) { if ($no_order_new[$i]=="" || $detail_new[$i]=="") { }else{ $class_data->sql ="INSERT INTO tbl_objective_conclude(courseID,no_order,detail) VALUES($course_id,$no_order_new[$i],'$detail_new[$i]')"; echo $class_data->query(); } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "update_objective_conclude"){ $course_id=$_POST['course_id']; $objective_data_all_id=$_POST['objective_data_all_id']; $no_order=$_POST['no_order']; $detail=$_POST['detail']; $arr_id = explode("-", $objective_data_all_id); $class_data->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$course_id "; $class_data->select(); $class_data->setRows(); foreach($class_data->rows as $key => $value) { $DataID=$value['DataID']; for ($i=0; $i < count($arr_id) ; $i++) { if ($DataID==$arr_id[$i]) { $sql="UPDATE tbl_objective_conclude SET no_order=$no_order[$i],detail='$detail[$i]' WHERE DataID={$arr_id[$i]}"; $class_data->sql =$sql; $class_data->query(); } } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "add_teaching"){ $course_id=$_POST['course_id']; $term_search=$_POST['term_search']; $year_search=$_POST['year_search']; echo $class_data->insert_data_teaching($course_id,$term_search,$year_search); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove_std"){ $data_val = $_POST['data_val']; echo $class_data->data_remove_std($data_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove_objective"){ $data_val = $_POST['data_val']; echo $class_data->data_remove_objective($data_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_registed_course_teaching"){ echo $class_data->get_registed_course_teaching(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_std_list_new"){ $id_std_search=$_GET['id_std_search']; $search_class_modal=$_GET['search_class_modal']; $search_room_modal=$_GET['search_room_modal']; $course_id=$_GET['course_id']; $term_search=$_GET['term_search']; $year_search=$_GET['year_search']; echo $class_data->get_std_list($id_std_search,$search_class_modal,$search_room_modal,$course_id,$term_search,$year_search); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_add_std"){ $data_val = $_POST['data_val']; $course_id = $_POST['course_id']; $term_search = $_POST['term_search']; $year_search = $_POST['year_search']; echo $class_data->data_add_std($data_val,$course_id,$term_search,$year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_std_list"){ $id_std_search=$_GET['id_std_search']; $search_class_modal=$_GET['search_class_modal']; $search_room_modal=$_GET['search_room_modal']; $course_id=$_GET['course_id']; echo $class_data->get_std_list($id_std_search,$search_class_modal,$search_room_modal,$course_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_name_to_add_std"){ $data_id_first=$_GET['data_id_first']; $registed_course_id=$_GET['registed_course_id']; $term_search=$_GET['term_search']; $year_search=$_GET['year_search']; echo $class_data->get_name_to_add_std($data_id_first,$registed_course_id,$term_search,$year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_class"){ $department_search=$_GET['department_search']; $class_level_search=$_GET['class_level_search']; $term_search=$_GET['term_search']; $year_search=$_GET['year_search']; echo $class_data->search_course_class($department_search,$class_level_search,$term_search,$year_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "hide_class_std"){ $data_id_first=$_GET['data_id_first']; echo $class_data->hide_class_std($data_id_first); } <file_sep>/modules/conclusion/learning_result_report_p.php <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/print_conclusion.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" rel="stylesheet" type="text/css"> <script type="text/javascript" src="../../assets/js/jquery.js"></script> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 2px; } --> </style> <?php @session_start(); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); $std_ID=$_GET['std_ID']; $term=$_GET['term']; $year=$_GET['year']; ?> <div style="background-color: rgb(82, 86, 89);min-height: 100%"> <div style="font-size: 10%;background-color: white;min-height: 100%;padding-right: 15px; padding-left: 15px;margin-right: auto;margin-left: auto;width: 80%"> <div style="page-break-after:always;"> <page > <div > <table cellspacing="0" style=" text-align: center; font-size: 22px;width:142%;"> <caption style="font-size:28px ;margin-left: 30px;margin-top: 0px;">บันทึกเวลาเข้าเรียน</caption> <thead> <tr class="text-middle"> <td rowspan="3" class="rotate" style="width: 0.1%;font-size: 22px;height: 0px;"><div >เลขที่</div></td> <td rowspan="3" class="rotate" style="width: 0.1%;font-size: 22px;height: 0px;"><div >รหัส</div></td> <td rowspan="3" style="width: 10%;vertical-align: middle;font-size: 22px;">ชื่อ-สกุล</td> <td colspan="40" style="width: 50%;padding: 5px;font-size: 22px;">'.$num_day.' ชั่วโมง/สัปดาห์</td> <td rowspan="3" class="rotate" style="width: 0.1%;height: 0px;"><div style="margin-top: 30px;">รวม '.$total_hr.' ชั่วโมง</div></td> <td rowspan="3" class="rotate" style="width: 0.1%;height: 0px;"><div style="margin-top: 30px;">ร้อยละ</div></td> </tr> <tr> <td colspan="40" style="width: 60%;padding: 5px;border-left:none;font-size: 22px;">สัปดาห์ที่</td> </tr> <tr> <td style="border-left: none;width: 0.5%;">1</td> <td style="width: 0.5%;">2</td> <td style="width: 0.5%;">3</td> <td style="width: 0.5%;">4</td> <td style="width: 0.5%;">5</td> <td style="width: 0.5%;">6</td> <td style="width: 0.5%;">7</td> <td style="width: 0.5%;">8</td> <td style="width: 0.5%;">9</td> <td style="width: 0.5%;">10</td> <td style="width: 0.5%;">11</td> <td style="width: 0.5%;">12</td> <td style="width: 0.5%;">13</td> <td style="width: 0.5%;">14</td> <td style="width: 0.5%;">15</td> <td style="width: 0.5%;">16</td> <td style="width: 0.5%;">17</td> <td style="width: 0.5%;">18</td> <td style="width: 0.5%;">19</td> <td style="width: 0.5%;">20</td> <td style="width: 0.5%;">21</td> <td style="width: 0.5%;">22</td> <td style="width: 0.5%;">23</td> <td style="width: 0.5%;">24</td> <td style="width: 0.5%;">25</td> <td style="width: 0.5%;">26</td> <td style="width: 0.5%;">27</td> <td style="width: 0.5%;">28</td> <td style="width: 0.5%;">29</td> <td style="width: 0.5%;">30</td> <td style="width: 0.5%;">31</td> <td style="width: 0.5%;">32</td> <td style="width: 0.5%;">33</td> <td style="width: 0.5%;">34</td> <td style="width: 0.5%;">35</td> <td style="width: 0.5%;">36</td> <td style="width: 0.5%;">37</td> <td style="width: 0.5%;">38</td> <td style="width: 0.5%;">39</td> <td style="width: 0.5%;">40</td> </tr> </thead> <tbody > '.$detail_std_attend_p['detail_std'].' </tbody> </table> </div> </page> </div> </div> </div> <script> /*$(document).ready(function() { get_print(); setTimeout(window.close, 0); }); function get_print() { window.print(); }*/ var css = '@page { size: landscape; }', head = document.head || document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css'; style.media = 'print'; if (style.styleSheet){ style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); window.print(); </script><file_sep>/modules/mobile_api/host/newssubboxhome.php <?php @session_start(); require_once('config.php'); require_once('src/database.php'); include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $condition = false; $num= $class_data->rows[0]['num']; $json = json_decode(file_get_contents('php://input'), true); $newsheighlight=1; if (!empty($newsheighlight) ) { $products_arr=array(); $products_arr["records"]=array(); $sql = "SELECT DataID,title,detail,date FROM tbl_news WHERE DataID not in(SELECT MAX(date) FROM tbl_news) ORDER BY date DESC"; $class_data->sql = $sql; $class_data->select(); $class_data->setRows(); foreach($class_data->rows as $key => $value) { $DataID= $value['DataID']; $title= strip_tags(htmlspecialchars_decode($value['title'])); $detail= $value['detail']; $detail= htmlspecialchars_decode($detail); //if(strlen($detail) > 80) $detail = substr($detail, 0, 80).'...'; if(strlen($detail) > 40) { $detail = iconv_substr($detail, 0, 40).'...'; } $detail= strip_tags(htmlspecialchars_decode($detail)); $date_set= $value['date']; $old_form_date = strtotime($date_set); $date=date('d-m-Y', $old_form_date); $class_data->sql = "SELECT file_name FROM tbl_news_gallery WHERE newsID=$DataID"; $class_data->select(); $class_data->setRows(); $img_url='/sratong-app/file_managers/news/'.$class_data->rows[0]['file_name']; $data_res['status']=1; $product_item=array( "key" => $key, "DataID" => $DataID, "title" => $title, "detail" => $detail, "date" => $date, "img_url" => $img_url, ); array_push($products_arr["records"], $product_item); } echo json_encode($products_arr,JSON_UNESCAPED_UNICODE); }else{ $data_res['status']=0; } ?> <file_sep>/modules/maneger_student/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "chk_id"){ $std_ID=$_GET['std_ID']; $card_ID=$_GET['card_ID']; echo $class_data->chk_id($std_ID,$card_ID); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $data_id=$_POST['data_id']; $day=$_POST['day']; $mouth=$_POST['mouth']; $years=$_POST['years']-543; $birthday=$years.'-'.$mouth.'-'.$day; $arr_sql[]="std_ID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['std_ID'])))."'"; $arr_sql[]="card_ID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['card_ID'])))."'"; /*$arr_sql[]="class_level='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['class_level'])))."'"; $arr_sql[]="room='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['room'])))."'";*/ $arr_sql[]="name_title='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['name_title'])))."'"; $arr_sql[]="fname='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname'])))."'"; $arr_sql[]="lname='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname'])))."'"; $arr_sql[]="birthday='".chkhtmlspecialchars($InputFilter->clean_script(trim($birthday)))."'"; $arr_sql[]="blood_group='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['blood_group'])))."'"; $arr_sql[]="address='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['address'])))."'"; $arr_sql[]="parent_name_title='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_name_title'])))."'"; $arr_sql[]="parent_fname='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_fname'])))."'"; $arr_sql[]="parent_lname='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_lname'])))."'"; $arr_sql[]="tell='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tell'])))."'"; $arr_sql[]="parent_address='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_address'])))."'"; $arr_sql[]="status_alive='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['status_alive'])))."'"; $arr_sql_class_room[]="std_ID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['std_ID'])))."'"; /*$arr_sql_class_room[]="class_level='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['class_level'])))."'"; $arr_sql_class_room[]="room='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['room'])))."'";*/ $arr_sql_class_room[]="status='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['status_alive'])))."'"; $class_data->update_data($arr_sql,$arr_sql_class_room,$data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_form"){ $data_id=$_GET['data_id']; $new_data_id=$_GET['new_data_id']; echo $class_data->get_data_form($data_id,$new_data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_years"){ echo $class_data->get_years(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day"){ $mouth=$_GET['mouth']; echo $class_data->get_day($mouth); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "data_year_search_student"){ $arr_search_val['data_class_search'] = $_GET['data_class_search']; $arr_search_val['data_room_search'] = $_GET['data_room_search']; echo $class_data->data_year_search_student($arr_search_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data"){ $arr_search_val['name_id_search'] = $_GET['name_id_search']; echo $class_data->get_data($arr_search_val); }<file_sep>/modules/regis_student/upload_one.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $file = $_FILES['file']['tmp_name']; $year_main = $_POST['year_main']; $handle = fopen($file, "r"); fgetcsv($handle); while(($filesop = fgetcsv($handle, 1000, ",")) !== false) { $std_ID = trim($filesop[0]); $card_ID = trim($filesop[1]); $name_title_set = trim($filesop[2]); $fname = trim($filesop[3]); $lname = trim($filesop[4]); $birthday_set = trim($filesop[5]); $class_level = trim($filesop[6]); $room = trim($filesop[7]); if ($name_title_set=='เด็กชาย') { $name_title='dekchai'; }elseif($name_title_set=='เด็กหญิง'){ $name_title='dekying'; }elseif($name_title_set=='นาย'){ $name_title='nai'; }elseif($name_title_set=='นางสาว'){ $name_title='nangsaw'; } list($day,$month,$year_set) = split('[/]', $birthday_set); $year=$year_set-543; $birthday=$year.'-'.$month.'-'.$day; $password_show=$day.$month.$year_set; $password=MD5($day.$month.$year_set); $class_data->sql = "SELECT count(*) as num_data FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_student.std_ID='$std_ID' AND tbl_std_class_room.std_ID='$std_ID' "; $class_data->select(); $class_data->setRows(); $num_data=$class_data->rows[0]['num_data']; if ($num_data==0) { $class_data->sql = "INSERT INTO tbl_student(std_ID,card_ID,password,name_title,fname,lname,birthday) VALUES ('$std_ID','$card_ID','$password','$name_title','$fname','$lname','$birthday')"; $class_data->query(); $class_data->sql = "INSERT INTO tbl_std_class_room(std_ID,class_level,room,year,status) VALUES ('$std_ID','$class_level','$room','$year_main',1)"; $class_data->query(); $data_res.=' <tr> <td>'.$std_ID.'</td> <td>'.$password_show.'</td> <td>'.$class_level.'</td> <td>'.$room.'</td> <td>'.$name_title_set.'</td> <td>'.$fname.'</td> <td>'.$lname.'</td> <td>'.$birthday_set.'</td> </tr> '; }else{ $class_data->sql = "SELECT COUNT(*) as num_data_finish FROM tbl_std_class_room WHERE std_ID='$std_ID' AND status=2 "; $class_data->select(); $class_data->setRows(); $num_data_finish=$class_data->rows[0]['num_data_finish']; if ($num_data_finish>0) { $class_data->sql = "INSERT INTO tbl_std_class_room(std_ID,class_level,room,year,status) VALUES ('$std_ID','$class_level','$room','$year_main',1)"; $class_data->query(); $data_res.=' <tr> <td>'.$std_ID.'</td> <td>'.$password_show.'</td> <td>'.$class_level.'</td> <td>'.$room.'</td> <td>'.$name_title_set.'</td> <td>'.$fname.'</td> <td>'.$lname.'</td> <td>'.$birthday_set.'</td> </tr> '; } } $c = $c + 1; } echo $data_res; ?><file_sep>/modules/send_midterm/class_modules.php <?php class ClassData extends Databases { public function get_dev_summary($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $data_atte_nopass=0; $data_atte_pass=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val,$room_search); if ($score_attend_class=='nopass') { $data_atte_nopass++; }else{ $data_atte_pass++; } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } if ($score_attend_class=='pass') { $pass_status='<td><span class="glyphicon glyphicon-ok text-violet" aria-hidden="true"></span></td> <td></td>'; }else{ $pass_status='<td></td> <td><span class="glyphicon glyphicon-ok text-violet" aria-hidden="true"></span></td>'; } $data_response['std_list'].=' <tr> <td>'.$number.'</td> <td style="text-align:left;padding-left:20%;">'.$name_title.$fname.' '.$lname.'</td> '.$pass_status.' </tr> '; $number++; } $data_response['data_atte_nopass']=$data_atte_nopass; $data_response['data_atte_pass']=$data_atte_pass; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; echo json_encode($data_response); } public function get_registed_courseID($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_score_pick($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $num_of_i=0; $this->sql ="SELECT COUNT(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1 "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($num_of_i>0) { $total='i'; }else{ $total=$score_total_data; } return $total; } public function get_score_exam($std_ID,$coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $mid_status=0; $final_status=0; $this->sql ="SELECT COUNT(score) as num_of_i_mid FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_mid=$this->rows[0]['num_of_i_mid']; if ($num_of_i_mid>0) { $mid_status=-1; } $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $mid_exam_score=$this->rows[0]['score']; $this->sql ="SELECT COUNT(score) as num_of_i_final FROM tbl_final_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_final=$this->rows[0]['num_of_i_final']; if ($num_of_i_final>0) { $final_status=-1; } $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $final_exam_score=$this->rows[0]['score']; if ($mid_status==-1 || $final_status==-1) { $total='i'; }else{ $total=$mid_exam_score+$final_exam_score; } return $total; } public function get_grade($score_exam,$score_pick){ $total=$score_exam+$score_pick; if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_registed_course_id($coures_id_list){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; /*$this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); */ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$coures_id_list ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $data_response['status']=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data_response['class_data']='p'; }else{ $data_response['class_data']='m'; } return $data_response; } public function get_score_attend_class($std_ID,$coures_id_list_val,$room_search){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $registed_course_teaching_id=$this->get_registed_course_id($coures_id_list_val); $this->sql ="SELECT status FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $status=$this->rows[0]['status']; $this->sql ="SELECT COUNT(course_teaching_std_id) as sum_no_come FROM tbl_attend_class_std WHERE course_teaching_std_id IN( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) AND set_attend_day_id IN( SELECT DataID FROM tbl_set_attend_day WHERE registed_course_teachingID IN( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) ) "; $this->select(); $this->setRows(); $sum_no_come=$this->rows[0]['sum_no_come']; $registed_course_teaching_id=$this->get_registed_course_id($coures_id_list_val); $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status['status']==1) { $condition="AND room='$room_search'"; }else{ $condition=""; } $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id $condition "; $this->select(); $this->setRows(); $num_hr=$this->rows[0]['num_hr']; if ($class_level_status['class_data']=='p') { $week_all=40; }else{ $week_all=20; } $total_day=$num_hr*$week_all; $total_attend_per=round((($total_day-$sum_no_come)*100)/$total_day); if ($total_attend_per>=80) { $find_80_per='pass'; }else{ $find_80_per='nopass'; } /* $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; $this->sql ="SELECT SUM(score_status) as sum_score FROM tbl_attend_class WHERE week BETWEEN 1 AND $week_name AND course_teaching_stdID in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $sum_score=$this->rows[0]['sum_score']; $data_must_pass=floor((80*$week_name)/100); if ($sum_score>=$data_must_pass) { $find_80_per='pass'; }else{ $find_80_per='nopass'; }*/ return $find_80_per; } public function get_desirable_number($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; for ($i=1; $i <= 8 ; $i++) { $this->sql ="SELECT * FROM tbl_desirable_$i WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score=$this->rows[0]['score']; $score_total=$score_total+$score; } $evaluation_score=number_format($score_total/8,1); return $evaluation_score; } public function get_desirable($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; for ($i=1; $i <= 8 ; $i++) { $this->sql ="SELECT * FROM tbl_desirable_$i WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score=$this->rows[0]['score']; $score_total=$score_total+$score; } $evaluation_score=$score_total/8; if ($evaluation_score<1) { $data='nopass'; }elseif($evaluation_score<1.5){ $data='pass'; }elseif($evaluation_score<2.5){ $data='good'; }elseif($evaluation_score>=2.5){ $data='verygood'; } return $data; } public function get_read_think_write_number($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; $score_read=0; $score_think=0; $score_write=0; $this->sql ="SELECT * FROM tbl_read_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_read=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_think_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_think=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_write_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_write=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_4=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_5=$this->rows[0]['score']; $score_total=number_format(($score_read+$score_think+$score_write+$score_rtw_4+$score_rtw_5)/5,1); return $score_total; } public function get_read_think_write($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; $score_read=0; $score_think=0; $score_write=0; $this->sql ="SELECT * FROM tbl_read_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_read=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_think_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_think=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_write_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_write=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_4=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_5=$this->rows[0]['score']; $score_total=($score_read+$score_think+$score_write+$score_rtw_4+$score_rtw_5)/5; if ($score_total<1) { $data='nopass'; }elseif($score_total<1.5){ $data='pass'; }elseif($score_total<2.5){ $data='good'; }elseif($score_total>=2.5){ $data='verygood'; } return $data; } public function get_propotion_total($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val"; $this->select(); $this->setRows(); $data_response['cumulative_before_mid']=$this->rows[0]['cumulative_before_mid']; $data_response['cumulative_after_mid']=$this->rows[0]['cumulative_after_mid']; $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; $data_response['total']=$mid_exam+$final_exam; return $data_response; } public function get_comulative_score($std_ID,$coures_id_list_val){ $data_response = array(); $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT SUM(score) as sum_score_total_before FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$std_ID' AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude WHERE proportion_status=1 ) "; $this->select(); $this->setRows(); $data_response['sum_score_total_before']=$this->rows[0]['sum_score_total_before']; $this->sql ="SELECT SUM(score) as sum_score_total_after FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$std_ID' AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude WHERE proportion_status=2 ) "; $this->select(); $this->setRows(); $data_response['sum_score_total_after']=$this->rows[0]['sum_score_total_after']; return $data_response; } public function get_mid_exam_score($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_final_exam_score($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function un_export($data_id,$data_term,$data_year,$data_room,$data_class){ $this->sql ="SELECT status FROM tbl_add_delete_course WHERE DataID=$data_id "; $this->select(); $this->setRows(); $status=$this->rows[0]['status']; if ($status==2) { $condition_sql_1=""; }else{ $condition_sql_1="AND room='$data_room'"; } $this->sql = " DELETE FROM tbl_sub_pp6 WHERE sub_ID=$data_id AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE term='$data_term' AND year='$data_year' AND class_level='$data_class' $condition_sql_1 ) "; $this->query(); if ($status==2) { $condition_sql_2="WHERE room='0' "; }else{ $condition_sql_2="WHERE room='$data_room' "; } $this->sql = " UPDATE tbl_room_export SET status=1 $condition_sql_2 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$data_id AND term='$data_term' AND year='$data_year' ) "; $this->query(); return json_encode(1); } public function export_data($data_val,$data_term_set){ $data_response = array(); $arr_id = explode(",", $data_val); for ($i=0; $i < count($arr_id) ; $i++) { $divider=explode("-", $arr_id[$i]); $data_func.=$this->export_data_func($divider[0],$divider[1],$divider[2]); } return $data_func; } public function export_data_func($coures_id_list_val,$room_search,$room_exportID){ $ss_status=$_SESSION['ss_status']; $cdate = date("Y-m-d"); if ($ss_status==2){ $this->sql = " UPDATE tbl_room_export SET status=0 ,sended_status=1 ,cdate='$cdate' WHERE DataID=$room_exportID "; $this->query(); } $this->sql ="SELECT class_level,status FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $status=$this->rows[0]['status']; $class_level=$this->rows[0]['class_level']; if ($status==1) { $condition="WHERE room='$room_search' AND"; }else{ $condition="WHERE"; } $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT COUNT(*) as num_row_room FROM tbl_room_export WHERE registed_courseID=$registed_courseID AND room=$room_search "; $this->select(); $this->setRows(); $num_row_room=$this->rows[0]['num_row_room']; if ($num_row_room==0) { $this->sql = "INSERT INTO tbl_room_export(registed_courseID,room,cdate) VALUES ($registed_courseID,$room_search,'$cdate')"; $this->query(); } $this->sql ="SELECT * FROM tbl_student $condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $card_ID=$value['card_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $class_level=$value['class_level']; $room=$value['room']; $comulative_score=$this->get_comulative_score($std_ID,$coures_id_list_val); $mid_exam_score=$this->get_mid_exam_score($std_ID,$coures_id_list_val); $final_exam_score=$this->get_final_exam_score($std_ID,$coures_id_list_val); $total_before_mide=$comulative_score['sum_score_total_before']+$mid_exam_score;//mid $total_after_mide=$comulative_score['sum_score_total_after']+$final_exam_score;//afer_mid $total_score_data=$total_before_mide+$total_after_mide;//total $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val,$room_search); if($score_exam=='i' || $score_pick=='i'){ $total_score_data=-1; } if($score_attend_class=='nopass'){ $score_attend=-1; }else{ $score_attend=1; } $desirable=$this->get_desirable_number($std_ID,$coures_id_list_val);//score_desirable $read_think_write=$this->get_read_think_write_number($std_ID,$coures_id_list_val);//score_rtw $this->sql ="SELECT COUNT(*) as number_std,DataID as pp6_id FROM tbl_pp6 WHERE std_ID='$std_ID' AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); $number_std=$this->rows[0]['number_std']; if($number_std>0){ $new_id=$this->rows[0]['pp6_id']; }else{ $this->sql = "INSERT INTO tbl_pp6(std_ID,card_ID,name_title,fname,lname,class_level,room,term,year) VALUES ('$std_ID','$card_ID','$name_title_data','$fname','$lname','$class_level','$room','$term_set','$year_set')"; $this->query(); $new_id = $this->insertID(); } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $courseID_in=$this->rows[0]['courseID']; $name_in=$this->rows[0]['name']; $unit_in=$this->rows[0]['unit']; $department_in=$this->rows[0]['department']; $status_in=$this->rows[0]['status']; $status_form_in=$this->rows[0]['status_form']; $this->sql = "INSERT INTO tbl_sub_pp6(pp6_ID,sub_ID,courseID,name,unit,department,status,status_form,score_mid,score_final,score_total,score_desirable,score_rtw,score_attend) VALUES ($new_id,$coures_id_list_val,'$courseID_in','$name_in',$unit_in,'$department_in',$status_in,$status_form_in,$total_before_mide,$total_after_mide,$total_score_data,$desirable,$read_think_write,$score_attend)"; $this->query(); } return $room_search; } public function get_grade_summary($coures_id_list_val,$room_search){ $data_response = array(); $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $comulative_score=$this->get_comulative_score($std_ID,$coures_id_list_val); $mid_exam_score=$this->get_mid_exam_score($std_ID,$coures_id_list_val); $final_exam_score=$this->get_final_exam_score($std_ID,$coures_id_list_val); $total_score_std=$comulative_score['sum_score_total_before']+$comulative_score['sum_score_total_after']+$mid_exam_score+$final_exam_score; $comulative_score_sum=$comulative_score['sum_score_total_before']+$comulative_score['sum_score_total_after']; $score_exam=$mid_exam_score+$final_exam_score; $grade_data=$this->get_grade($score_exam,$comulative_score_sum); $data_response['std_list'].=' <tr> <td>'.$number.'</td> <td style="text-align:left;padding-left:4%;">'.$name_title.$fname.' '.$lname.'</td> <td>'.$comulative_score['sum_score_total_before'].'</td> <td>'.$mid_exam_score.'</td> <td>'.$comulative_score['sum_score_total_after'].'</td> <td>'.$final_exam_score.'</td> <td>'.$total_score_std.'</td> <td>'.$grade_data.'</td> </tr> '; $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val,$room_search); //$data_response['score_attend_class']=$score_attend_class; if ($score_exam=='i' || $score_pick=='i' || $score_attend_class=='nopass') { if ($score_exam=='i' || $score_pick=='i') { $data_i++; } if ($score_attend_class=='nopass') { $data_atte++; } }else{ $grade=$this->get_grade($score_exam,$score_pick); $data_response['exam'].=$grade.'-'; if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } $number++; } $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_i']=$data_i; $data_response['data_atte']=$data_atte; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $propotion_total=$this->get_propotion_total($coures_id_list_val); $comulative_before_mid_title=$propotion_total['cumulative_before_mid']; $comulative_after_mid_title=$propotion_total['cumulative_after_mid']; $mid_exam_title=$propotion_total['mid_exam']; $final_exam_title=$propotion_total['final_exam']; $data_response['total_title']=$comulative_before_mid_title+$comulative_after_mid_title+$mid_exam_title+$final_exam_title; $data_response['comulative_before_mid_title']=$comulative_before_mid_title; $data_response['comulative_after_mid_title']=$comulative_after_mid_title; $data_response['mid_exam_title']=$mid_exam_title; $data_response['final_exam_title']=$final_exam_title; echo json_encode($data_response); } public function search_course_detail($coures_id_list,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level']=$class_level_data; $data_response['class_level_co']=$class_level.'/'.$room_search; return json_encode($data_response); } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); /*$this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); */ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $data_response['status']=$status; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } return json_encode($data_response); } public function get_data_dicision_edit($DataID,$courseID_long,$class_level,$name,$term_set,$year_set,$status,$room_export){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $term_set='1,2'; } $class_level_new=$this->get_class_level_new($class_level); if ($status==1) { $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $find_in_pp6=$this->find_in_pp6($DataID,$room,$term_set,$year_set); if ($find_in_pp6!=0) { $data_response.=' <tr> <td style="text-align:center;"> </td> <td>'.$courseID_long.'</td> <td><a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'&room='.$room.'">'.$name.'</a></td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> <div class="btn_un_export" data-term="'.$term_set.'" data-room='.$room.' data-class='.$class_level.' data-year="'.$year_set.'" data-id="'.$DataID.'" aria-hidden="true" data-toggle="modal" data-target="#modalCancelUnExport"> <span class="glyphicon glyphicon-refresh edit-icon-table"></span> </div> </td> </tr> '; } } }else{ $data_response.=' <tr> <td style="text-align:center;"> </td> <td>'.$courseID_long.'</td> <td><a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'&room=0">'.$name.'</a></td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">-</td> <td style="text-align: center;"> <div class="btn_un_export" data-term="'.$term_set.'" data-room="0" data-class='.$class_level.' data-year="'.$year_set.'" data-id="'.$DataID.'" aria-hidden="true" data-toggle="modal" data-target="#modalCancelUnExport"> <span class="glyphicon glyphicon-refresh edit-icon-table"></span> </div> </td> </tr> '; } return $data_response; } public function get_data_dicision_added($DataID,$courseID_long,$class_level,$name,$status){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $term_set='1,2'; } $ss_status=$_SESSION['ss_status']; if ($ss_status==2) { $condition_sql=" "; $condition_date=' <td style="text-align: center;">'.$find_in_pp6['cdate'].'</td> ' ; }else{ $condition_sql=" AND term='$term_set' AND year='$year_set' "; } $class_level_new=$this->get_class_level_new($class_level); if ($status==1) { $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID $condition_sql ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $find_in_pp6=$this->find_in_pp6_added($DataID,$room,$term_set,$year_set); if ($find_in_pp6['num_row']>0) { if ($ss_status==2) { $data_response.=' <tr> <td style="text-align:center;"> </td> <td>'.$courseID_long.'</td> <td><a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'&room='.$room.'">'.$name.'</a></td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;">'.$find_in_pp6['cdate'].'</td> </tr> '; }else{ $data_response.=' <tr> <td style="text-align:center;"> </td> <td>'.$courseID_long.'</td> <td><a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'&room='.$room.'">'.$name.'</a></td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">'.$room.'</td> </tr> '; } } } }else{ if ($ss_status==2) { $find_in_pp6=$this->find_in_pp6_added($DataID,0,$term_set,$year_set); $data_response.=' <tr> <td style="text-align:center;"> </td> <td>'.$courseID_long.'</td> <td><a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'">'.$name.'</a></td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">-</td> <td style="text-align: center;">'.$find_in_pp6['cdate'].'</td> </tr> '; }else{ $data_response.=' <tr> <td style="text-align:center;"> </td> <td>'.$courseID_long.'</td> <td><a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'">'.$name.'</a></td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">-</td> </tr> '; } } return $data_response; } public function get_data_dicision($DataID,$courseID_long,$class_level,$name,$status){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $term_set='1,2'; } $class_level_new=$this->get_class_level_new($class_level); if ($status==1) { $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $find_in_pp6=$this->find_in_pp6_teacher($DataID,$room,$term_set,$year_set); if ($find_in_pp6==0) { $data_response.=' <tr> <td style="text-align:center;"> <input class="checkbox_data" type="checkbox" value="'.$DataID.'-'.$room.'" name="checkbox_export[]" id="checkbox'.$DataID.'"> </td> <td>'.$courseID_long.'</td> <td> <a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'&room='.$room.'">'.$name.'</a> </td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">'.$room.'</td> </tr> '; } } }else{ $data_response.=' <tr> <td style="text-align:center;"> <input class="checkbox_data" type="checkbox" value="'.$DataID.'-0" name="checkbox_export[]" id="checkbox'.$DataID.'"> </td> <td>'.$courseID_long.'</td> <td> <a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'">'.$name.'</a> </td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">-</td> </tr> '; } return $data_response; } public function get_data_dicision_admin($DataID,$courseID_long,$class_level,$name,$term_set,$year_set,$status){ $class_level_new=$this->get_class_level_new($class_level); if ($status==1) { $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $find_in_pp6=$this->find_in_pp6_admin($DataID,$room,$term_set,$year_set); if ($find_in_pp6['num_row']>0) { $data_response.=' <tr> <td style="text-align:center;"> <input class="checkbox_data" type="checkbox" value="'.$DataID.'-'.$room.'-'.$find_in_pp6['room_export_ID'].'" name="checkbox_export[]" id="checkbox'.$DataID.'"> </td> <td>'.$courseID_long.'</td> <td> <a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'&room='.$room.'">'.$name.'</a> </td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">'.$room.'</td> </tr> '; } } }else{ $find_in_pp6=$this->find_in_pp6_admin($DataID,0,$term_set,$year_set); $data_response.=' <tr> <td style="text-align:center;"> <input class="checkbox_data" type="checkbox" value="'.$DataID.'-0-'.$find_in_pp6['room_export_ID'].'" name="checkbox_export[]" id="checkbox'.$DataID.'"> </td> <td>'.$courseID_long.'</td> <td> <a style="color:#000;text-decoration-line: underline;" href="index.php?op=summary-view&id='.$DataID.'">'.$name.'</a> </td> <td style="text-align: center;">'.$class_level_new.'</td> <td style="text-align: center;">-</td> </tr> '; } return $data_response; } public function find_in_pp6_admin($course_id,$room,$term_set,$year_set){ $this->sql =" SELECT COUNT(*) AS num_row,DataID as room_export_ID FROM tbl_room_export WHERE room=$room AND status=1 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND courseID=$course_id ) "; $this->select(); $this->setRows(); $data_response['num_row']=$this->rows[0]['num_row']; $data_response['room_export_ID']=$this->rows[0]['room_export_ID']; return $data_response; } public function find_in_pp6_teacher($course_id,$room,$term_set,$year_set){ $this->sql =" SELECT COUNT(*) AS num_row FROM tbl_room_export WHERE room=$room AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND courseID=$course_id ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function find_in_pp6_added($course_id,$room,$term_set,$year_set){ $ss_status=$_SESSION['ss_status']; $condition_1=''; $condition_2=''; if ($ss_status==2) { $condition_1=" AND status=0 AND sended_status=1 "; }else{ $condition_2=" AND year='$year_set' AND term='$term_set' "; } $this->sql =" SELECT COUNT(*) AS num_row,cdate FROM tbl_room_export WHERE room=$room $condition_1 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$course_id $condition_2 ) "; $this->select(); $this->setRows(); $cdate_data=$this->rows[0]['cdate']; $old_date_timestamp = strtotime($cdate_data); $cdate=date('d-m-Y', $old_date_timestamp); $data_response['cdate']=$cdate; $data_response['num_row']=$this->rows[0]['num_row']; return $data_response; } public function find_in_pp6($course_id,$room,$term_set,$year_set){ $this->sql =" SELECT COUNT(*) AS num_row FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_pp6.room='$room' AND tbl_sub_pp6.sub_ID=$course_id AND tbl_pp6.term='$term_set' AND tbl_pp6.year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_pp6 ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; if($key==0){ $data_response.=' <option selected="selected" value="'.$year.'">'.$year.'</option> '; }else{ $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } } return json_encode($data_response); } public function get_coures_id_list_edit($data_term_search,$data_year_search){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT DISTINCT(tbl_add_delete_course.DataID),tbl_add_delete_course.name,tbl_add_delete_course.courseID,tbl_add_delete_course.class_level,tbl_add_delete_course.status FROM tbl_add_delete_course,tbl_registed_course,tbl_sub_pp6 WHERE tbl_registed_course.courseID=tbl_add_delete_course.DataID AND tbl_add_delete_course.DataID=tbl_sub_pp6.sub_ID AND tbl_registed_course.term='$data_term_search' AND tbl_registed_course.year='$data_year_search' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $name=$value['name']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; if ($status==2) { $room_export=$this->chk_room_export_edit($DataID,$data_year_search); if ($room_export>0) { $data_dicision=$this->get_data_dicision_edit($DataID,$courseID_long,$class_level,$name,$data_term_search,$data_year_search,$status); } }else{ $data_dicision=$this->get_data_dicision_edit($DataID,$courseID_long,$class_level,$name,$data_term_search,$data_year_search,$status); } $data_response['coures_id_list'].=$data_dicision; } if ($data_response['coures_id_list']=='') { $data_response['coures_id_list']=''; } return json_encode($data_response); } public function get_coures_id_list_added(){ $ss_status=$_SESSION['ss_status']; $condition_sql_user=""; $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; if ($ss_status==2) { $condition_sql="WHERE"; }else{ $condition_sql=" WHERE year='$year_set' AND "; $user_id=$_SESSION['ss_user_id']; $condition_sql_user=" WHERE teacher_id=$user_id "; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course $condition_sql DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) AND DataID in( SELECT regis_course_id FROM tbl_course_teacher $condition_sql_user ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $name=$value['name']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; if ($status==2) { $room_export=$this->chk_room_export($DataID,$year_set,$ss_status); if ($room_export!=0) { $data_dicision=$this->get_data_dicision_added($DataID,$courseID_long,$class_level,$name,$status); } }else{ $data_dicision=$this->get_data_dicision_added($DataID,$courseID_long,$class_level,$name,$status); } $data_response['coures_id_list'].=$data_dicision; } return json_encode($data_response); } public function get_coures_id_list($data_id,$data_room){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) AND DataID in( SELECT regis_course_id FROM tbl_course_teacher WHERE teacher_id=$user_id ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $name=$value['name']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; if ($status==2) { $room_export=$this->chk_room_export($DataID,$year_set); if ($room_export==0) { $data_dicision=$this->get_data_dicision($DataID,$courseID_long,$class_level,$name,$status); } }else{ $data_dicision=$this->get_data_dicision($DataID,$courseID_long,$class_level,$name,$status); } $data_response['coures_id_list'].=$data_dicision; } return json_encode($data_response); } public function chk_room_export_edit($course_id,$year_set){ $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_add_delete_course WHERE DataID=$course_id AND DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export WHERE status=0 AND sended_status=0 OR sended_status=1 ) ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function chk_room_export($course_id,$year_set,$ss_status){ $condition=""; if ($ss_status==2) { $condition="WHERE status=0 AND sended_status=1"; } $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_add_delete_course WHERE DataID=$course_id AND DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export $condition ) ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_coures_id_list_admin($term_set,$year_set){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $name=$value['name']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; if ($status==2) { $room_export=$this->chk_room_export_admin($DataID,$year_set,$term_set); if ($room_export>0) { $data_dicision=$this->get_data_dicision_admin($DataID,$courseID_long,$class_level,$name,$term_set,$year_set,$status); } }else{ $data_dicision=$this->get_data_dicision_admin($DataID,$courseID_long,$class_level,$name,$term_set,$year_set,$status); } $data_response['coures_id_list'].=$data_dicision; } return json_encode($data_response); } public function chk_room_export_admin($course_id,$year_set,$term_set){ $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_add_delete_course WHERE DataID=$course_id AND DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export WHERE status=1 ) ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } }<file_sep>/src/class.notification.php <?php class Notification extends Databases { public function sap_date_format($strDate){ $strYear = date("Y",strtotime($strDate)); $strMonth= date("m",strtotime($strDate)); $strDay= date("d",strtotime($strDate)); return "{$strDay}.{$strMonth}.{$strYear}"; } /*************************************** API ACCOUNTING ****************************************/ public function ex_not_membership($insert){ $this->sql = "INSERT INTO not_membership(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); return $this->insertID(); } public function ex_not_backoffice($insert){ $this->sql = "INSERT INTO not_backoffice(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); return $this->insertID(); } public function ex_not_message($msg_key){ $this->sql = "SELECT msg_text FROM not_message WHERE msg_key = '{$msg_key}' "; $this->query(); $this->setRows(); return $this->rows[0]['msg_text'] ; } public function feed_not_backoffice($service_type){ ## DATA TBLE ## $item_no = 0; $sql = "SELECT * FROM not_backoffice WHERE service_type = {$service_type} ORDER BY not_datetime DESC "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response = ""; foreach($this->rows as $key => $value) { $data_response[$item_no]['not_datetime'] = $value['not_datetime']; $data_response[$item_no]['not_message'] = $value['not_message']; $data_response[$item_no]['not_status'] = $value['not_status']; $data_response[$item_no]['user_id'] = $value['user_id']; $item_no++; } ## DATA TBLE ## return $data_response; } public function feed_not_membership($member_id=null) { ## DATA TBLE ## $where = ' WHERE '; $where .= ' member_id='.$member_id.' AND '; //if($account_id) $where .= ' account_id='.$account_id.' AND '; $where = substr($where, 0, -4); $item_no = 0; $sql = "SELECT * FROM not_membership {$where} ORDER BY not_datetime DESC "; $this->sql = $sql; $this->select(); $this->setRows(); return $this->rows; /*$data_response = ""; foreach($this->rows as $key => $value) { $data_response[$item_no]['not_datetime'] = $value['not_datetime']; $data_response[$item_no]['not_message'] = $value['not_message']; $data_response[$item_no]['not_status'] = $value['not_status']; $data_response[$item_no]['user_id'] = $value['user_id']; $item_no++; } ## DATA TBLE ## return $data_response; */ } /*************************************** API ACCOUNTING ****************************************/ // Aoo: 04/02/15 // Insert Notification public function noti_member($message,$member_id,$account_id=0,$user_id=0,$settime="") { if( !$message ){ $arr_response = array('status' => 'n', 'not_temp' => time(),'messages' => "Message Empty!"); return json_encode($arr_response); } // Get Memeber_id if(!$member_id){ $where = ' WHERE account_id='.$account_id; $sql = "SELECT * FROM mm_member_accounts {$where} LIMIT 0,1 "; $this->sql = $sql; $this->select(); $this->setRows(); $member_id = $this->rows[0]['member_id']; } $not_mm = array(); $not_mm["not_message"]= "'".$message."'"; $not_mm["member_id"]= "'".$member_id."'"; $not_mm["account_id"]= "'".$account_id."'"; $not_mm["user_id"]= "'".$user_id."'"; $not_mm["not_status"]= 1; $not_mm["not_datetime"]= ($settime)? "'".$settime."'":"now()"; $not_mm["cdate"]= "now()"; $not_id = self::ex_not_membership($not_mm); $arr_response = array('status' => 'y', 'not_temp' => time(),'messages' => ""); return json_encode($arr_response); } public function noti_backoffice($message,$role_id=0,$user_id=0,$settime="") { if( !$message ){ $arr_response = array('status' => 'n', 'not_temp' => time(),'messages' => "Message Empty!"); return json_encode($arr_response); } $not_mm = array(); $not_mm["not_message"]= "'".$message."'"; $not_mm["role_id"]= "'".$role_id."'"; $not_mm["user_id"]= "'".$user_id."'"; $not_mm["not_status"]= 1; $not_mm["not_datetime"]= ($settime)? "'".$settime."'":"now()"; $not_mm["cdate"]= "now()"; $not_id = self::ex_not_backoffice($not_mm); $arr_response = array('status' => 'y', 'not_temp' => time(),'messages' => ""); return json_encode($arr_response); } } ?><file_sep>/modules/report/class_modules.php <?php set_time_limit(120); class ClassData extends Databases { public function get_dev_summary($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_atte_nopass=0; $data_atte_pass=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); if ($score_attend_class=='nopass') { $data_atte_nopass++; }else{ $data_atte_pass++; } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } include('checked.php'); if ($score_attend_class=='pass') { $pass_status='<td>/</td> <td></td>'; }else{ $pass_status='<td></td> <td>/</td>'; } $data_response['std_list'].=' <tr> <td>'.$number.'</td> <td>'.$name_title.$fname.' '.$lname.'</td> '.$pass_status.' </tr> '; $number++; } $data_response['data_atte_nopass']=$data_atte_nopass; $data_response['data_atte_pass']=$data_atte_pass; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; return $data_response; } public function get_std_desirable($coures_id_list_val,$room_search){ $course_teachingID=$this->get_registed_course_id($coures_id_list_val); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' || $status==2) { $term_set='1,2'; } if ($status!=2) { $sql_condition="WHERE room='$room_search' AND"; }else{ $sql_condition="WHERE"; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_set=1; $loo_no=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_desirable_1=$this->get_score_desirable_1($std_ID,$course_teachingID); $score_desirable_2=$this->get_score_desirable_2($std_ID,$course_teachingID); $score_desirable_3=$this->get_score_desirable_3($std_ID,$course_teachingID); $score_desirable_4=$this->get_score_desirable_4($std_ID,$course_teachingID); $score_desirable_5=$this->get_score_desirable_5($std_ID,$course_teachingID); $score_desirable_6=$this->get_score_desirable_6($std_ID,$course_teachingID); $score_desirable_7=$this->get_score_desirable_7($std_ID,$course_teachingID); $score_desirable_8=$this->get_score_desirable_8($std_ID,$course_teachingID); $score_total_sum=$score_desirable_1['score']+$score_desirable_2['score']+$score_desirable_3['score']+$score_desirable_4['score']+$score_desirable_5['score']+$score_desirable_6['score']+$score_desirable_7['score']+$score_desirable_8['score']; $score_total=round(($score_total_sum)/8,2); $get_score_read=$this->get_score_read($std_ID,$course_teachingID); $get_score_write=$this->get_score_write($std_ID,$course_teachingID); $get_score_think=$this->get_score_think($std_ID,$course_teachingID); $get_score_rtw_4=$this->get_score_rtw_4($std_ID,$course_teachingID); $get_score_rtw_5=$this->get_score_rtw_5($std_ID,$course_teachingID); $score_total_rwt_sum=$get_score_read['score']+$get_score_write['score']+$get_score_think['score']+$get_score_rtw_4['score']+$get_score_rtw_5['score']; $score_total_rwt=round(($score_total_rwt_sum)/5,2); $fname=$value['fname']; $lname=$value['lname']; $data_response.=' <tr> <td>'.$num_set.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> <td>'.$score_desirable_1['score'].'</td> <td>'.$score_desirable_2['score'].'</td> <td>'.$score_desirable_3['score'].'</td> <td>'.$score_desirable_4['score'].'</td> <td>'.$score_desirable_5['score'].'</td> <td>'.$score_desirable_6['score'].'</td> <td>'.$score_desirable_7['score'].'</td> <td>'.$score_desirable_8['score'].'</td> <td>'.$score_total_sum.'</td> <td>'.$score_total.'</td> <td>'.$get_score_read['score'].'</td> <td>'.$get_score_write['score'].'</td> <td>'.$get_score_think['score'].'</td> <td>'.$get_score_rtw_4['score'].'</td> <td>'.$get_score_rtw_5['score'].'</td> <td>'.$score_total_rwt_sum.'</td> <td>'.$score_total_rwt.'</td> </tr> '; $num_set++; } return $data_response; } public function get_score_read($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_read_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_write($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_write_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_think($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_think_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_rtw_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_rtw_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_1($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_1 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_2($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_2 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_3($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_3 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_4 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_5 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_6($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_6 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_7($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_7 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_8($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_8 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_attend($coures_id_list,$status,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_status='p'; }else{ $class_status='m'; } $registed_course_id=$this->get_registed_course_id($coures_id_list); $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id ORDER BY attend_class_week_listID ASC "; $this->select(); $this->setRows(); $num_day=$this->rows[0]['num_hr']; if ($status==1 && $class_status=='m') { //p and m $total_hr=20*$num_day; /*for ($i=1; $i <= 20; $i++) { if ($i==1) { $data_response['num_day'].='<td style="border-left:none;">'.$num_day.'</td>'; }else{ $data_response['num_day'].='<td>'.$num_day.'</td>'; } }*/ $set_page='port'; }elseif($status==2 || $class_status=='p'){ $total_hr=40*$num_day; /*for ($i=1; $i <= 40; $i++) { if ($i==1) { $data_response['num_day'].='<td style="border-left:none;">'.$num_day.'</td>'; }else{ $data_response['num_day'].='<td>'.$num_day.'</td>'; } }*/ $set_page='land'; } $detail_std=$this->get_detail_std_attend($coures_id_list,$room_search,$status,$num_day,$set_page); $data_response['detail_std']=$detail_std['detail_std']; $data_response['class_status']=$class_status; $data_response['set_page']=$set_page; $data_response['total_hr']=$total_hr; $data_response['num_day']=$num_day; return $data_response; } public function get_detail_std_attend($coures_id_list_val,$room_search,$status,$num_day,$set_page){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val); if ($status!=2) { $sql_condition="WHERE room='$room_search' AND"; }else{ $sql_condition="WHERE"; } $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); // $attend_data=$this->get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status); $attend_data=$this->get_attend_data($std_ID,$registed_courseID,$status,$num_day,$set_page); $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data['total_attend_list'].' <td>'.$attend_data['sum_attend'].'</td> <td>'.round($attend_data['sum_attend_per'],2).'</td> </tr> '; $no_std++; } return $data_response; } public function get_attend_data($std_ID,$registed_courseID,$status,$num_day,$set_page){ if ($set_page=='port') { $count_no_attend=0; for ($i=1; $i <=20 ; $i++) { $this->sql ="SELECT COUNT(*) as num_no_attend FROM tbl_attend_class_std WHERE week=$i AND course_teaching_std_id in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $num_no_attend=$this->rows[0]['num_no_attend']; $total_attend=$num_day-$num_no_attend; $data_response['total_attend_list'].='<td>'.$total_attend.'</td>'; $count_no_attend=$count_no_attend+$num_no_attend; } $all_day=$num_day*20; $sum_attend=$all_day-$count_no_attend; $data_response['sum_attend']=$sum_attend; $data_response['sum_attend_per']=($sum_attend*100)/$all_day; }else{ $count_no_attend=0; for ($i=1; $i <=40 ; $i++) { $this->sql ="SELECT COUNT(*) as num_no_attend FROM tbl_attend_class_std WHERE week=$i AND course_teaching_std_id in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $num_no_attend=$this->rows[0]['num_no_attend']; $total_attend=$num_day-$num_no_attend; $data_response['total_attend_list'].='<td>'.$total_attend.'</td>'; $count_no_attend=$count_no_attend+$num_no_attend; } $all_day=$num_day*40; $sum_attend=$all_day-$count_no_attend; $data_response['sum_attend']=$sum_attend; $data_response['sum_attend_per']=($sum_attend*100)/$all_day; } return $data_response; } public function get_objective_list($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT COUNT(*) as find_end FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); $find_end=$this->rows[0]['find_end']; $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val ORDER BY no_order ASC "; $this->select(); $this->setRows(); $chk_loop=1; $sum_score_main=0; foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $no_order=$value['no_order']; $detail=$value['detail']; $score=$value['score']; $objective_conclude_detail.=' <tr> <td style="border: none;"> ตัวชี้วัดที่ '.$no_order.' </td> <td style="border: none;"> '.$detail.' </td> </tr> '; if ($chk_loop==1) { $data_response['ob_title_table_col'].=' <td style="border-left:none;">'.$no_order.'</td>'; $data_response['score_title_table_col'].=' <td style="border-left:none;width: 4%;">'.$score.'</td>'; }else{ $data_response['ob_title_table_col'].=' <td >'.$no_order.'</td>'; $data_response['score_title_table_col'].=' <td style="width: 4%;">'.$score.'</td>'; } if ($find_end==$chk_loop) { $data_objective.=$DataID; }else{ $data_objective.=$DataID.'-'; } $sum_score_main=$sum_score_main+$score; $chk_loop++; } $data_response['objective_conclude_detail']=$objective_conclude_detail; $data_response['chk_loop']=$chk_loop; $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; $data_response['sum_score_main']=$sum_score_main; $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $data_response['detail_std']=$this->get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$room_search); return $data_response; } public function get_course_teachingID($DataID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); $score_col=$this->get_score_col($std_ID,$data_objective,$registed_courseID); $score_col_total=$this->get_score_col_total($std_ID,$registed_courseID); $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $score_mid_exam=$this->get_score_mid_exam($std_ID,$course_teachingID); $score_final_exam=$this->get_score_final_exam($std_ID,$course_teachingID); $sum_score=$score_col_total+$score_mid_exam['score']+$score_final_exam['score']; $score_exam=$score_mid_exam['score']+$score_final_exam['score']; $grade=$this->get_grade($score_exam,$score_col_total); $data_response.='<tr> <td>'.$no_std.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> '.$score_col.' <td>'.$score_mid_exam['score'].'</td> <td>'.$score_final_exam['score'].'</td> <td>'.$sum_score.'</td> <td>'.$grade.'</td> </tr> '; $no_std++; } return $data_response; } public function get_score_final_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_score_mid_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_score_col_total($std_ID,$registed_courseID){ $num_of_i=0; $this->sql ="SELECT count(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1; "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($score_total_data==0) { $score_total=0; }else{ $score_total=$score_total_data; } return $score_total+$num_of_i; } public function get_score_col($std_ID,$data_objective,$registed_courseID){ $arr_id = explode("-", $data_objective); for ($i=0; $i < count($arr_id) ; $i++) { if ($arr_id[$i]=='') { $arr_id[$i]=0; }else{ $arr_id[$i]=$arr_id[$i]; } $total_ob_conclude=$this->get_total_ob_conclude($arr_id[$i]); $this->sql ="SELECT * FROM tbl_objective_score_std WHERE staID='$std_ID' AND objectiveID={$arr_id[$i]} AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $score=0; }else{ if ($score==-1) { $score='ร'; }else{ $score=$score; } } $data_response.='<td>'.$score.'</td>'; $start_data++; } return $data_response; } public function get_total_ob_conclude($data_objective_ob){ $this->sql ="SELECT score FROM tbl_objective_conclude WHERE DataID=$data_objective_ob "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_grade_summary($coures_id_list_val,$room_search,$status){ $data_response = array(); $registed_courseID=$this->get_registed_courseID($coures_id_list_val); if ($status!=2) { $sql_condition="WHERE room='$room_search' AND"; }else{ $sql_condition="WHERE"; } $this->sql ="SELECT count(*) as num_row_std FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $comulative_score=$this->get_comulative_score($std_ID,$coures_id_list_val); $mid_exam_score=$this->get_mid_exam_score($std_ID,$coures_id_list_val); $final_exam_score=$this->get_final_exam_score($std_ID,$coures_id_list_val); $total_score_std=$comulative_score['sum_score_total_before']+$comulative_score['sum_score_total_after']+$mid_exam_score+$final_exam_score; $comulative_score_sum=$comulative_score['sum_score_total_before']+$comulative_score['sum_score_total_after']; $score_exam=$mid_exam_score+$final_exam_score; $grade_data=$this->get_grade($score_exam,$comulative_score_sum); $data_response['std_list'].=' <tr> <td>'.$number.'</td> <td>'.$name_title.$fname.' '.$lname.'</td> <td>'.$comulative_score['sum_score_total_before'].'</td> <td>'.$comulative_score['sum_score_total_after'].'</td> <td>'.$mid_exam_score.'</td> <td>'.$final_exam_score.'</td> <td>'.$total_score_std.'</td> <td>'.$grade_data.'</td> </tr> '; $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); //$data_response['score_attend_class']=$score_attend_class; if ($score_exam=='i' || $score_pick=='i' || $score_attend_class=='nopass') { if ($score_exam=='i' || $score_pick=='i') { $data_i++; } if ($score_attend_class=='nopass') { $data_atte++; } }else{ $grade=$this->get_grade($score_exam,$score_pick); $data_response['exam'].=$grade.'-'; if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } $number++; } $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_i']=$data_i; $data_response['data_atte']=$data_atte; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $propotion_total=$this->get_propotion_total($coures_id_list_val); $comulative_before_mid_title=$propotion_total['cumulative_before_mid']; $comulative_after_mid_title=$propotion_total['cumulative_after_mid']; $mid_exam_title=$propotion_total['mid_exam']; $final_exam_title=$propotion_total['final_exam']; $data_response['total_title']=$comulative_before_mid_title+$comulative_after_mid_title+$mid_exam_title+$final_exam_title; $data_response['comulative_before_mid_title']=$comulative_before_mid_title; $data_response['comulative_after_mid_title']=$comulative_after_mid_title; $data_response['mid_exam_title']=$mid_exam_title; $data_response['final_exam_title']=$final_exam_title; return $data_response; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_comulative_score($std_ID,$coures_id_list_val){ $data_response = array(); $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT SUM(score) as sum_score_total_before FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$std_ID' AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude WHERE proportion_status=1 ) "; $this->select(); $this->setRows(); $data_response['sum_score_total_before']=$this->rows[0]['sum_score_total_before']; $this->sql ="SELECT SUM(score) as sum_score_total_after FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$std_ID' AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude WHERE proportion_status=2 ) "; $this->select(); $this->setRows(); $data_response['sum_score_total_after']=$this->rows[0]['sum_score_total_after']; return $data_response; } public function get_mid_exam_score($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_final_exam_score($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_propotion_total($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val"; $this->select(); $this->setRows(); $data_response['cumulative_before_mid']=$this->rows[0]['cumulative_before_mid']; $data_response['cumulative_after_mid']=$this->rows[0]['cumulative_after_mid']; $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; $data_response['total']=$mid_exam+$final_exam; return $data_response; } public function search_course_detail($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level_co']=$class_level.'/'.$room_search; $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; //$attend_class_std_list=$this->get_attend_class_std_list($std_ID,$coures_id_list_val); $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); //$data_response['score_attend_class']=$score_attend_class; if ($score_exam=='i' || $score_pick=='i' || $score_attend_class=='nopass') { if ($score_exam=='i' || $score_pick=='i') { $data_i++; } if ($score_attend_class=='nopass') { $data_atte++; } }else{ $grade=$this->get_grade($score_exam,$score_pick); $data_response['exam'].=$grade.'-'; if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } $number++; } $data_response['attend_class_std_list']=$attend_class_std_list; $data_response['number']=$number; $data_response['data_i']=$data_i; $data_response['data_atte']=$data_atte; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; echo json_encode($data_response); } public function get_read_think_write($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; $score_read=0; $score_think=0; $score_write=0; $this->sql ="SELECT * FROM tbl_read_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_read=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_think_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_think=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_write_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_write=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_4=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_5=$this->rows[0]['score']; $score_total=($score_read+$score_think+$score_write+$score_rtw_4+$score_rtw_5)/5; if ($score_total<1) { $data='nopass'; }elseif($score_total<1.5){ $data='pass'; }elseif($score_total<2.5){ $data='good'; }elseif($score_total>=2.5){ $data='verygood'; } return $data; } public function get_desirable($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; for ($i=1; $i <= 8 ; $i++) { $this->sql ="SELECT * FROM tbl_desirable_$i WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score=$this->rows[0]['score']; $score_total=$score_total+$score; } $evaluation_score=$score_total/8; if ($evaluation_score<1) { $data='nopass'; }elseif($evaluation_score<1.5){ $data='pass'; }elseif($evaluation_score<2.5){ $data='good'; }elseif($evaluation_score>=2.5){ $data='verygood'; } return $data; } public function get_registed_courseID($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' || $status==2) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_grade($score_exam,$score_pick){ $total=$score_exam+$score_pick; if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_score_attend_class($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT COUNT(course_teaching_std_id) as sum_no_come FROM tbl_attend_class_std WHERE course_teaching_std_id IN( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID=$std_ID ) AND set_attend_day_id IN( SELECT DataID FROM tbl_set_attend_day WHERE registed_course_teachingID IN( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) ) "; $this->select(); $this->setRows(); $sum_no_come=$this->rows[0]['sum_no_come']; $registed_course_teaching_id=$this->get_registed_course_id($coures_id_list_val); $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id "; $this->select(); $this->setRows(); $num_hr=$this->rows[0]['num_hr']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $week_all=40; }else{ $week_all=20; } $total_day=$num_hr*$week_all; $total_attend_per=round((($total_day-$sum_no_come)*100)/$total_day); if ($total_attend_per>=80) { $find_80_per='pass'; }else{ $find_80_per='nopass'; } /* $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; $this->sql ="SELECT SUM(score_status) as sum_score FROM tbl_attend_class WHERE week BETWEEN 1 AND $week_name AND course_teaching_stdID in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $sum_score=$this->rows[0]['sum_score']; $data_must_pass=floor((80*$week_name)/100); if ($sum_score>=$data_must_pass) { $find_80_per='pass'; }else{ $find_80_per='nopass'; }*/ return $find_80_per; } public function get_registed_course_id($coures_id_list){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' || $status==2) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$coures_id_list ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ||$status==2) { $data='p'; }else{ $data='m'; } return $data; } public function get_score_pick($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $num_of_i=0; $this->sql ="SELECT COUNT(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1 "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($num_of_i>0) { $total='i'; }else{ $total=$score_total_data; } return $total; } public function get_score_exam($std_ID,$coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $mid_status=0; $final_status=0; $this->sql ="SELECT COUNT(score) as num_of_i_mid FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_mid=$this->rows[0]['num_of_i_mid']; if ($num_of_i_mid>0) { $mid_status=-1; } $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $mid_exam_score=$this->rows[0]['score']; $this->sql ="SELECT COUNT(score) as num_of_i_final FROM tbl_final_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_final=$this->rows[0]['num_of_i_final']; if ($num_of_i_final>0) { $final_status=-1; } $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $final_exam_score=$this->rows[0]['score']; if ($mid_status==-1 || $final_status==-1) { $total='i'; }else{ $total=$mid_exam_score+$final_exam_score; } return $total; } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $data_response['status']=$status; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' || $status==2) { $term_set='1,2'; } $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option value='.$room.'>'.$room.'</option>'; } return json_encode($data_response); } public function get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' || $status==2) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; }else{ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row==1) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; } } return $data_response; } public function get_coures_id_list($data_id,$data_room){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; $data_dicision=$this->get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set); $data_response['coures_id_list'].=$data_dicision; } return json_encode($data_response); } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/profile/changepass.js var opPage = 'profile'; $(document).ready(function() { get_img() }); function get_img(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_img" }); formData.push({ "name": "status_get", "value": "index" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus) { // console.log(data); $("#get_profile_img").html(data.get_profile_img); }); } function form_reset(form_se) { $("#"+form_se)[0].reset(); } $(document).delegate('#btn__save', 'click', function(event) { var new_password =$("#<PASSWORD>").val(); var new_password_again =$("#new_password_again").val(); if(new_password===new_password_again) { if(new_password.length<6){ $(".modal").modal("hide"); $("#new_password").val(''); $("#new_password_again").val(''); $("#new_password").attr( "placeholder", "ใส่รหัสผ่านอย่างน้อย 6 ตั<PASSWORD>" ); $("#new_password_again").attr( "placeholder", "ใส่รหัสผ่านอย่างน้อย 6 ต<PASSWORD>" ); }else{ var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "update_new_pass" }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); if (data==0) { $(".modal").modal("hide"); $("#old_password").val(''); $("#profile-edit-box_chk").removeClass("profile-edit-box"); $("#profile-edit-box_chk").addClass("profile-edit-box-null-data"); $("#old_password").attr( "placeholder", "<PASSWORD>" ); }else{ $("#modalChangedPass").modal("show"); form_reset("frm_data"); } }); } }else{ $(".modal").modal("hide"); $("#new_password").val(''); $("#new_password_again").val(''); $("#new_password").attr( "placeholder", "<PASSWORD>" ); $("#new_password_again").attr( "placeholder", "<PASSWORD> <PASSWORD>" ); } }); <file_sep>/modules/print/class_modules.php <?php set_time_limit(120); class ClassData extends Databases { public function get_count_std_dev($registed_courseID){ $this->sql =" SELECT COUNT(stdID) AS count_std FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID in( SELECT std_ID FROM tbl_student ) "; $this->select(); $this->setRows(); return $this->rows[0]['count_std']; } public function get_dev_summary($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $status_form=$this->rows[0]['status_form']; if ($status_form==25 ||$status_form==26|| $status_form==27) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition="WHERE"; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT count(*) as num_row_std FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $count_std=$this->get_count_std_dev($registed_courseID); $set_loop_html=ceil($count_std/30); for ($i=1; $i <=$set_loop_html ; $i++) { $std_dev_summary=$this->get_std_dev_summary($coures_id_list_val,$i,$registed_courseID,$room_search,$year_set,$sql_condition); $data_html_dev.=' <div style="page-break-after:always; "> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;border: 1px solid black;"> <caption style="font-size:28px ;margin-left: 30px;margin-top: 80px;">สรุปผลการเรียน</caption> <thead> <tr> <td rowspan="2" style="width: 20%;">เลขที่</td> <td rowspan="2" style="width: 50%;">ชื่อ-สกุล</td> <td colspan="2" style="width: 30%;">สรุปผลการเรียน</td> </tr> <tr> <td style="width:13%;">ผ่าน</td> <td style="width:13%;">ไม่ผ่าน</td> </tr> </thead> <tbody> '.$std_dev_summary['std_list'].' </tbody> </table> </div> '; } $data_response['data_atte_nopass']=$std_dev_summary['data_atte_nopass']; $data_response['data_atte_pass']=$std_dev_summary['data_atte_pass']; $data_response['data_desirable_nopass']=$std_dev_summary['data_desirable_nopass']; $data_response['data_desirable_pass']=$std_dev_summary['data_desirable_pass']; $data_response['data_desirable_good']=$std_dev_summary['data_desirable_good']; $data_response['data_desirable_verygood']=$std_dev_summary['data_desirable_verygood']; $data_response['data_read_think_write_nopass']=$std_dev_summary['data_read_think_write_nopass']; $data_response['data_read_think_write_pass']=$std_dev_summary['data_read_think_write_pass']; $data_response['data_read_think_write_good']=$std_dev_summary['data_read_think_write_good']; $data_response['data_read_think_write_verygood']=$std_dev_summary['data_read_think_write_verygood']; $data_response['data_html_dev']=$data_html_dev; return $data_response; } public function get_std_dev_summary($coures_id_list_val,$i,$registed_courseID,$room_search,$year_set,$sql_condition){ $find_start=($i-1)*30; $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID = $registed_courseID ) ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END LIMIT $find_start,30 "; $this->select(); $this->setRows(); $data_atte_nopass=0; $data_atte_pass=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=$find_start+1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); if ($score_attend_class=='nopass') { $data_atte_nopass++; }else{ $data_atte_pass++; } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } include('checked.php'); if ($score_attend_class=='pass') { $pass_status='<td><img style="width:22px;" src="../../assets/images/checked.png"></td> <td></td>'; }else{ $pass_status='<td></td> <td><img style="width:22px;" src="../../assets/images/checked.png"></td>'; } $data_response['std_list'].=' <tr> <td>'.$number.'</td> <td style="text-align:left;padding-left:140px;">'.$name_title.$fname.' '.$lname.'</td> '.$pass_status.' </tr> '; $number++; } $data_response['data_atte_nopass']=$data_atte_nopass; $data_response['data_atte_pass']=$data_atte_pass; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; return $data_response; } public function get_std_desirable($coures_id_list_val,$room_search){ $course_teachingID=$this->get_registed_course_id($coures_id_list_val); $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $count_std=$this->get_count_std($registed_courseID); $set_loop_html=ceil($count_std/30); for ($i=1; $i <=$set_loop_html ; $i++) { $stdlist_desirable=$this->get_stdlist_desirable($i,$registed_courseID,$course_teachingID,$coures_id_list_val,$room_search); $data_response.=' <div style="page-break-after:always;"> <page orientation="portrait"> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 24px;margin-left: 30px;"> <caption style="font-size:28px ;margin-left: 30px;margin-top: 80px;">การประเมินคุณลักษณะอันพึงประสงค์และการอ่าน คิดวิเคราะห์ และเขียน</caption> <thead> <tr class=""> <td rowspan="2" style="vertical-align: middle;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;">เลขที่</div> </td> <td rowspan="2" style="vertical-align: middle;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;">รหัส</div> </td> <td rowspan="2" style="vertical-align: middle;width: 20%;text-align: center;">ชื่อ-สกุล</td> <td colspan="10" style="width: 18%;padding: 5px;text-align: center;">คุณลักษณะอันพึงประสงค์</td> <td colspan="7" style="vertical-align: middle;width: 22%;text-align: center;">การอ่าน คิดวิเคราะห์ และเขียน</td> </tr> <tr> <td class="rotate" style="border-left: none;height: 60px;width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;1</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;2</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;3</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;4</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;5</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;6</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;7</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ข้อที่&nbsp;&nbsp;8</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">คะแนนรวม</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">คะแนนเฉลี่ย</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;1</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;2</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;3</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;4</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">ตัวชี้วัดที่&nbsp;&nbsp;5</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">คะแนนรวม</div></td> <td class="rotate" style="width: 0.1%;"><div style="margin-top: 10px;">คะแนนเฉลี่ย</div></td> </tr> </thead> <tbody> '.$stdlist_desirable.' </tbody> </table> </page> </div> '; } return $data_response; } public function get_stdlist_desirable($i,$registed_courseID,$course_teachingID,$coures_id_list_val,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $term_set='1,2'; } if ($status==1) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) AND "; } } $find_start=($i-1)*30; $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID = $registed_courseID ) ORDER BY std_ID ASC LIMIT $find_start,30 "; $this->select(); $this->setRows(); $num_set=$find_start+1; $loo_no=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_desirable_1=$this->get_score_desirable_1($std_ID,$course_teachingID); $score_desirable_2=$this->get_score_desirable_2($std_ID,$course_teachingID); $score_desirable_3=$this->get_score_desirable_3($std_ID,$course_teachingID); $score_desirable_4=$this->get_score_desirable_4($std_ID,$course_teachingID); $score_desirable_5=$this->get_score_desirable_5($std_ID,$course_teachingID); $score_desirable_6=$this->get_score_desirable_6($std_ID,$course_teachingID); $score_desirable_7=$this->get_score_desirable_7($std_ID,$course_teachingID); $score_desirable_8=$this->get_score_desirable_8($std_ID,$course_teachingID); $score_total_sum=$score_desirable_1['score']+$score_desirable_2['score']+$score_desirable_3['score']+$score_desirable_4['score']+$score_desirable_5['score']+$score_desirable_6['score']+$score_desirable_7['score']+$score_desirable_8['score']; $score_total=round(($score_total_sum)/8,2); $get_score_read=$this->get_score_read($std_ID,$course_teachingID); $get_score_write=$this->get_score_write($std_ID,$course_teachingID); $get_score_think=$this->get_score_think($std_ID,$course_teachingID); $get_score_rtw_4=$this->get_score_rtw_4($std_ID,$course_teachingID); $get_score_rtw_5=$this->get_score_rtw_5($std_ID,$course_teachingID); $score_total_rwt_sum=$get_score_read['score']+$get_score_write['score']+$get_score_think['score']+$get_score_rtw_4['score']+$get_score_rtw_5['score']; $score_total_rwt=round(($score_total_rwt_sum)/5,2); $fname=$value['fname']; $lname=$value['lname']; $data_response.=' <tr> <td>'.$num_set.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> <td>'.$score_desirable_1['score'].'</td> <td>'.$score_desirable_2['score'].'</td> <td>'.$score_desirable_3['score'].'</td> <td>'.$score_desirable_4['score'].'</td> <td>'.$score_desirable_5['score'].'</td> <td>'.$score_desirable_6['score'].'</td> <td>'.$score_desirable_7['score'].'</td> <td>'.$score_desirable_8['score'].'</td> <td>'.$score_total_sum.'</td> <td>'.$score_total.'</td> <td>'.$get_score_read['score'].'</td> <td>'.$get_score_write['score'].'</td> <td>'.$get_score_think['score'].'</td> <td>'.$get_score_rtw_4['score'].'</td> <td>'.$get_score_rtw_5['score'].'</td> <td>'.$score_total_rwt_sum.'</td> <td>'.$score_total_rwt.'</td> </tr> '; $num_set++; } return $data_response; } public function get_score_read($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_read_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_write($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_write_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_think($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_think_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_rtw_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_rtw_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_1($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_1 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_2($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_2 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_3($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_3 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_4 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_5 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_6($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_6 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_7($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_7 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_8($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_8 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_count_std($registed_courseID,$room_search,$status,$status_form){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; if ($status==1) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) "; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) "; }else{ $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) "; } } $this->sql =" SELECT COUNT(stdID) AS count_std FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID in( SELECT std_ID FROM tbl_student $sql_condition ) "; $this->select(); $this->setRows(); return $this->rows[0]['count_std']; } public function get_attend($coures_id_list,$status,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_status='p'; }else{ $class_status='m'; } $registed_course_id=$this->get_registed_course_id($coures_id_list); if ($status==1) { $sql_condition="AND room='$room_search'"; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="AND room='$room_search'"; }else{ $sql_condition=""; } } $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id $sql_condition ORDER BY attend_class_week_listID ASC "; $this->select(); $this->setRows(); $num_day=$this->rows[0]['num_hr']; if ($class_status=='m') { //p and m $total_hr=20*$num_day; $set_page='port'; $registed_courseID=$this->get_registed_courseID($coures_id_list); $count_std=$this->get_count_std($registed_courseID,$room_search,$status,$status_form); $set_loop_html=ceil($count_std/30); for ($i=1; $i <=$set_loop_html ; $i++) { $detail_std_attend_m=$this->get_detail_std_attend_m($coures_id_list,$room_search,$status,$num_day,$set_page,$i,$registed_courseID); $data_html.=' <div style="page-break-after:always;"> <page> <p style="font-size:28px ;margin-left: 30px;margin-top: 80px;">บันทึกเวลาเข้าเรียน</p> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="3" style="width: 5%;"><div style="transform: rotate(-90deg);white-space: nowrap;">เลขที่</div></td> <td rowspan="3" style="width: 5%;"><div style="transform: rotate(-90deg);white-space: nowrap;">รหัส</div></td> <td rowspan="3" style="width: 22%;vertical-align: middle;">ชื่อ-สกุล</td> <td colspan="20" style="width: 60%;padding: 5px;">'.$num_day.' ชั่วโมง/สัปดาห์</td> <td rowspan="3" style="width: 5%;"><div >รวม <br>'.$total_hr.'<br> ชั่วโมง</div></td> <td rowspan="3" style="width: 5%;"><div style="transform: rotate(-90deg);white-space: nowrap;">ร้อยละ</div></td> </tr> <tr> <td colspan="20" style="width: 60%;padding: 5px;border-left:none;">สัปดาห์ที่</td> </tr> <tr> <td style="border-left: none;width: 3%;">1</td> <td style="width: 3%;">2</td> <td style="width: 3%;">3</td> <td style="width: 3%;">4</td> <td style="width: 3%;">5</td> <td style="width: 3%;">6</td> <td style="width: 3%;">7</td> <td style="width: 3%;">8</td> <td style="width: 3%;">9</td> <td style="width: 3%;">10</td> <td style="width: 3%;">11</td> <td style="width: 3%;">12</td> <td style="width: 3%;">13</td> <td style="width: 3%;">14</td> <td style="width: 3%;">15</td> <td style="width: 3%;">16</td> <td style="width: 3%;">17</td> <td style="width: 3%;">18</td> <td style="width: 3%;">19</td> <td style="width: 3%;">20</td> </tr> </thead> <tbody > '.$detail_std_attend_m['detail_std'].' </tbody> </table> </page> </div> '; } }elseif($status==2 || $class_status=='p'){ $total_hr=40*$num_day; $set_page='land'; $registed_courseID=$this->get_registed_courseID($coures_id_list); $count_std=$this->get_count_std($registed_courseID,$room_search,$status,$status_form); $set_loop_html=ceil($count_std/20); for ($i=1; $i <=$set_loop_html ; $i++) { $detail_std_attend_p=$this->get_detail_std_attend_p($coures_id_list,$room_search,$status,$num_day,$set_page,$i,$registed_courseID); $data_html.=' <div style="page-break-after:always;"> <page > <div class="wrapper-page-attend-p-print" > <table cellspacing="0" style=" text-align: center; font-size: 22px;width:142%;"> <caption style="font-size:28px ;margin-left: 30px;margin-top: 0px;">บันทึกเวลาเข้าเรียน</caption> <thead> <tr class="text-middle"> <td rowspan="3" class="rotate" style="width: 0.1%;font-size: 22px;height: 0px;"><div >เลขที่</div></td> <td rowspan="3" class="rotate" style="width: 0.1%;font-size: 22px;height: 0px;"><div >รหัส</div></td> <td rowspan="3" style="width: 10%;vertical-align: middle;font-size: 22px;">ชื่อ-สกุล</td> <td colspan="40" style="width: 50%;padding: 5px;font-size: 22px;">'.$num_day.' ชั่วโมง/สัปดาห์</td> <td rowspan="3" class="rotate" style="width: 0.1%;height: 0px;"><div style="margin-top: 30px;">รวม '.$total_hr.' ชั่วโมง</div></td> <td rowspan="3" class="rotate" style="width: 0.1%;height: 0px;"><div style="margin-top: 30px;">ร้อยละ</div></td> </tr> <tr> <td colspan="40" style="width: 60%;padding: 5px;border-left:none;font-size: 22px;">สัปดาห์ที่</td> </tr> <tr> <td style="border-left: none;width: 0.5%;">1</td> <td style="width: 0.5%;">2</td> <td style="width: 0.5%;">3</td> <td style="width: 0.5%;">4</td> <td style="width: 0.5%;">5</td> <td style="width: 0.5%;">6</td> <td style="width: 0.5%;">7</td> <td style="width: 0.5%;">8</td> <td style="width: 0.5%;">9</td> <td style="width: 0.5%;">10</td> <td style="width: 0.5%;">11</td> <td style="width: 0.5%;">12</td> <td style="width: 0.5%;">13</td> <td style="width: 0.5%;">14</td> <td style="width: 0.5%;">15</td> <td style="width: 0.5%;">16</td> <td style="width: 0.5%;">17</td> <td style="width: 0.5%;">18</td> <td style="width: 0.5%;">19</td> <td style="width: 0.5%;">20</td> <td style="width: 0.5%;">21</td> <td style="width: 0.5%;">22</td> <td style="width: 0.5%;">23</td> <td style="width: 0.5%;">24</td> <td style="width: 0.5%;">25</td> <td style="width: 0.5%;">26</td> <td style="width: 0.5%;">27</td> <td style="width: 0.5%;">28</td> <td style="width: 0.5%;">29</td> <td style="width: 0.5%;">30</td> <td style="width: 0.5%;">31</td> <td style="width: 0.5%;">32</td> <td style="width: 0.5%;">33</td> <td style="width: 0.5%;">34</td> <td style="width: 0.5%;">35</td> <td style="width: 0.5%;">36</td> <td style="width: 0.5%;">37</td> <td style="width: 0.5%;">38</td> <td style="width: 0.5%;">39</td> <td style="width: 0.5%;">40</td> </tr> </thead> <tbody > '.$detail_std_attend_p['detail_std'].' </tbody> </table> </div> </page> </div> '; } /*for ($i=1; $i <= 40; $i++) { if ($i==1) { $data_response['num_day'].='<td style="border-left:none;">'.$num_day.'</td>'; }else{ $data_response['num_day'].='<td>'.$num_day.'</td>'; } }*/ } /*$detail_std=$this->get_detail_std_attend($coures_id_list,$room_search,$status,$num_day,$set_page); $data_response['detail_std']=$detail_std['detail_std'];*/ $data_response['data_html']=$data_html; $data_response['class_status']=$class_status; $data_response['set_page']=$set_page; $data_response['total_hr']=$total_hr; $data_response['num_day']=$num_day; return $data_response; } public function get_detail_std_attend_m($coures_id_list_val,$room_search,$status,$num_day,$set_page,$i,$registed_courseID){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val); if ($status==1) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) AND "; } } $find_start=($i-1)*30; $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END LIMIT $find_start,30 "; $this->select(); $this->setRows(); $no_std=$find_start+1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); // $attend_data=$this->get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status); $attend_data=$this->get_attend_data($std_ID,$registed_courseID,$status,$num_day,$set_page); $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data['total_attend_list'].' <td>'.$attend_data['sum_attend'].'</td> <td>'.round($attend_data['sum_attend_per'],2).'</td> </tr> '; $no_std++; } return $data_response; } public function get_detail_std_attend_p($coures_id_list_val,$room_search,$status,$num_day,$set_page,$i,$registed_courseID){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } if ($status==1) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) AND "; } $find_start=($i-1)*20; $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) ORDER BY room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END LIMIT $find_start,20 "; $this->select(); $this->setRows(); $no_std=$find_start+1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); // $attend_data=$this->get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status); $attend_data=$this->get_attend_data($std_ID,$registed_courseID,$status,$num_day,$set_page); $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data['total_attend_list'].' <td>'.$attend_data['sum_attend'].'</td> <td>'.round($attend_data['sum_attend_per'],2).'</td> </tr> '; $no_std++; } return $data_response; } public function get_attend_data($std_ID,$registed_courseID,$status,$num_day,$set_page){ if ($set_page=='port') { $count_no_attend=0; for ($i=1; $i <=20 ; $i++) { $this->sql ="SELECT COUNT(*) as num_no_attend FROM tbl_attend_class_std WHERE week=$i AND course_teaching_std_id in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $num_no_attend=$this->rows[0]['num_no_attend']; $total_attend=$num_day-$num_no_attend; $data_response['total_attend_list'].='<td>'.$total_attend.'</td>'; $count_no_attend=$count_no_attend+$num_no_attend; } $all_day=$num_day*20; $sum_attend=$all_day-$count_no_attend; $data_response['sum_attend']=$sum_attend; $data_response['sum_attend_per']=($sum_attend*100)/$all_day; }else{ $count_no_attend=0; for ($i=1; $i <=40 ; $i++) { $this->sql ="SELECT COUNT(*) as num_no_attend FROM tbl_attend_class_std WHERE week=$i AND course_teaching_std_id in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $num_no_attend=$this->rows[0]['num_no_attend']; $total_attend=$num_day-$num_no_attend; $data_response['total_attend_list'].='<td>'.$total_attend.'</td>'; $count_no_attend=$count_no_attend+$num_no_attend; } $all_day=$num_day*40; $sum_attend=$all_day-$count_no_attend; $data_response['sum_attend']=$sum_attend; $data_response['sum_attend_per']=($sum_attend*100)/$all_day; } return $data_response; } public function get_objective_list($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT COUNT(*) as find_end FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); $find_end=$this->rows[0]['find_end']; $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val ORDER BY no_order ASC "; $this->select(); $this->setRows(); $chk_loop=1; $sum_score_main=0; foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $no_order=$value['no_order']; $detail=$value['detail']; $score=$value['score']; $objective_conclude_detail.=' <tr> <td style="border: none;width:12%;"> ตัวชี้วัดที่ '.$no_order.' </td> <td style="border: none;"> '.$detail.' </td> </tr> '; if ($chk_loop==1) { $ob_title_table_col.=' <td style="border-left:none;">'.$no_order.'</td>'; $score_title_table_col.=' <td style="border-left:none;width: 1%;">'.$score.'</td>'; }else{ $ob_title_table_col.=' <td >'.$no_order.'</td>'; $score_title_table_col.=' <td style="width: 1%;">'.$score.'</td>'; } if ($find_end==$chk_loop) { $data_objective.=$DataID; }else{ $data_objective.=$DataID.'-'; } $sum_score_main=$sum_score_main+$score; $chk_loop++; } $data_response['objective_conclude_detail']=$objective_conclude_detail; //$data_response['chk_loop']=$chk_loop; $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; $total_score_exam=$sum_score_main+$mid_exam+$final_exam; $chk_loop_set=$chk_loop-1; $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $count_std=$this->get_count_std($registed_courseID,$room_search,1); if ($find_end<=10) { $set_loop_html=ceil($count_std/30); }else{ $set_loop_html=ceil($count_std/20); } for ($i=1; $i <=$set_loop_html ; $i++) { $detail_std=$this->get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$room_search,$i,$find_end); if ($find_end<=10) { if ($i==$set_loop_html) { $data_objective_list_box=' <div style="top: 80px;position: relative;"> <p style="margin-left: 30px;font-size: 24px;">คำอธิบายตัวชี้วัด</p> <table style="width: 80%;margin-left: 50px;margin-top: -10px;" > <tbody style="border: none;font-size: 22px;line-height: 0.9"> '.$objective_conclude_detail.' </tbody> </table> </div> '; } $data_response['data_html'].=' <div style="page-break-after:always; position:relative;top: 80px;"> <p style="font-size:28px ;margin-left: 30px;">การประเมินผลการเรียน</p> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;"> <thead> <tr class="text-middle"> <td rowspan="3" style="vertical-align: middle;width: 2%;">เลขที่</td> <td rowspan="3" style="vertical-align: middle;width: 2%;">รหัส</td> <td rowspan="3" style="vertical-align: middle;width: 20%;">ชื่อ-สกุล</td> <td colspan="'.$chk_loop_set.'" style="width: 50%">ตัวชี้วัดข้อที่</td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">สอบกลางภาค</div></td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">สอบปลายภาค</div></td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">คะแนนรวม</div></td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">GPA</div></td> </tr> <tr> '.$ob_title_table_col.' </tr> <tr> '.$score_title_table_col.' <td>'.$mid_exam.'</td> <td>'.$final_exam.'</td> <td>'.$total_score_exam.'</td> <td>4.0</td> </tr> </thead> <tbody > '.$detail_std.' </tbody> </table> '.$data_objective_list_box.' </div> '; }else{ $data_response['data_html'].=' <div style="page-break-after:always;"> <page > <div class="wrapper-page-ob table_original_long" > <table cellspacing="0" style="width: 140%; text-align: center; font-size: 24px;margin-left: 30px;"> <caption style="font-size:28px ;margin-left: 30px;margin-top: 0px;">การประเมินผลการเรียน</caption> <thead> <tr class="text-middle"> <td rowspan="3" style="text-align:center;vertical-align: middle;width: 0.1%;"> <div style="transform: rotate(-90deg);white-space: nowrap;">เลขที่</div> </td> <td rowspan="3" style="text-align:center;vertical-align: middle;width: 0.1%;"> <div style="transform: rotate(-90deg);white-space: nowrap;">รหัสนักเรียน</div> </td> <td rowspan="3" style="vertical-align: middle;width: 10%;">ชื่อ-สกุล</td> <td colspan="'.$chk_loop_set.'" style="width: 65%">ตัวชี้วัดข้อที่</td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">สอบกลางภาค</div></td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">สอบปลายภาค</div></td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">คะแนนรวม</div></td> <td class="rotate" rowspan="2" style="width: 0.1%;"><div style="margin-bottom: -24px;">GPA</div></td> </tr> <tr> '.$ob_title_table_col.' </tr> <tr> '.$score_title_table_col.' <td>'.$mid_exam.'</td> <td>'.$final_exam.'</td> <td>'.$total_score_exam.'</td> <td>4.0</td> </tr> </thead> <tbody > '.$detail_std.' </tbody> </table> </div> </page> </div> '; } } if ($find_end>10) { $data_response['data_html'].=' <div style="page-break-after:always;margin-top: 20px;"> <page> <div style="top: 80px;position: relative;"> <p style="margin-left: 30px;font-size: 24px;">คำอธิบายตัวชี้วัด</p> <table style="width: 80%;margin-left: 50px;margin-top: -10px;" > <tbody style="border: none;font-size: 22px;line-height: 0.9"> '.$objective_conclude_detail.' </tbody> </table> </div> </page> </div> '; } $data_response['data_html'].=$room_search; return $data_response; } public function get_course_teachingID($DataID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$room_search,$i,$find_end){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } if ($find_end<=10) { $find_start=($i-1)*30; $sql_condition="LIMIT $find_start,30"; }else{ $find_start=($i-1)*20; $sql_condition="LIMIT $find_start,20"; } $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID = $registed_courseID ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END $sql_condition "; $this->select(); $this->setRows(); $no_std=$find_start+1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); $score_col=$this->get_score_col($std_ID,$data_objective,$registed_courseID); $score_col_total=$this->get_score_col_total($std_ID,$registed_courseID); $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $score_mid_exam=$this->get_score_mid_exam($std_ID,$course_teachingID); $score_final_exam=$this->get_score_final_exam($std_ID,$course_teachingID); $sum_score=$score_col_total+$score_mid_exam['score']+$score_final_exam['score']; $score_exam=$score_mid_exam['score']+$score_final_exam['score']; $grade=$this->get_grade($score_exam,$score_col_total); $data_response.='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;">'.$name_title.$fname.' '.$lname.'</td> '.$score_col.' <td>'.$score_mid_exam['score'].'</td> <td>'.$score_final_exam['score'].'</td> <td>'.$sum_score.'</td> <td>'.$grade.'</td> </tr> '; $no_std++; } return $data_response; } public function get_score_final_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_score_mid_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_score_col_total($std_ID,$registed_courseID){ $num_of_i=0; $this->sql ="SELECT count(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1; "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($score_total_data==0) { $score_total=0; }else{ $score_total=$score_total_data; } return $score_total+$num_of_i; } public function get_score_col($std_ID,$data_objective,$registed_courseID){ $arr_id = explode("-", $data_objective); for ($i=0; $i < count($arr_id) ; $i++) { if ($arr_id[$i]=='') { $arr_id[$i]=0; }else{ $arr_id[$i]=$arr_id[$i]; } $total_ob_conclude=$this->get_total_ob_conclude($arr_id[$i]); $this->sql ="SELECT * FROM tbl_objective_score_std WHERE staID='$std_ID' AND objectiveID={$arr_id[$i]} AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $score=0; }else{ if ($score==-1) { $score='ร'; }else{ $score=$score; } } $data_response.='<td>'.$score.'</td>'; $start_data++; } return $data_response; } public function get_total_ob_conclude($data_objective_ob){ $this->sql ="SELECT score FROM tbl_objective_conclude WHERE DataID=$data_objective_ob "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_grade_summary($coures_id_list_val,$room_search,$status){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; $registed_courseID=$this->get_registed_courseID($coures_id_list_val); if ($status==1) { $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition="WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) AND "; } $this->sql ="SELECT count(*) as num_row_std FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; if ($num_row_std!=0) { $data_response['num_all_std']=$this->rows[0]['num_row_std']; }else{ $data_response['num_all_std']='-'; } $this->sql ="SELECT * FROM tbl_student $sql_condition std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID =$registed_courseID ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $comulative_score=$this->get_comulative_score($std_ID,$coures_id_list_val); $mid_exam_score=$this->get_mid_exam_score($std_ID,$coures_id_list_val); $final_exam_score=$this->get_final_exam_score($std_ID,$coures_id_list_val); $total_score_std=$comulative_score['sum_score_total_before']+$comulative_score['sum_score_total_after']+$mid_exam_score+$final_exam_score; $comulative_score_sum=$comulative_score['sum_score_total_before']+$comulative_score['sum_score_total_after']; $score_exam=$mid_exam_score+$final_exam_score; $grade_data=$this->get_grade($score_exam,$comulative_score_sum); $data_response['std_list'].=' <tr> <td>'.$number.'</td> <td>'.$name_title.$fname.' '.$lname.'</td> <td>'.$comulative_score['sum_score_total_before'].'</td> <td>'.$comulative_score['sum_score_total_after'].'</td> <td>'.$mid_exam_score.'</td> <td>'.$final_exam_score.'</td> <td>'.$total_score_std.'</td> <td>'.$grade_data.'</td> </tr> '; $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); //$data_response['score_attend_class']=$score_attend_class; if ($score_exam=='i' || $score_pick=='i' || $score_attend_class=='nopass') { if ($score_exam=='i' || $score_pick=='i') { $data_i++; } if ($score_attend_class=='nopass') { $data_atte++; } }else{ $grade=$this->get_grade($score_exam,$score_pick); $data_response['exam'].=$grade.'-'; if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } $number++; } $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_i']=$data_i; $data_response['data_atte']=$data_atte; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $propotion_total=$this->get_propotion_total($coures_id_list_val); $comulative_before_mid_title=$propotion_total['cumulative_before_mid']; $comulative_after_mid_title=$propotion_total['cumulative_after_mid']; $mid_exam_title=$propotion_total['mid_exam']; $final_exam_title=$propotion_total['final_exam']; $data_response['total_title']=$comulative_before_mid_title+$comulative_after_mid_title+$mid_exam_title+$final_exam_title; $data_response['comulative_before_mid_title']=$comulative_before_mid_title; $data_response['comulative_after_mid_title']=$comulative_after_mid_title; $data_response['mid_exam_title']=$mid_exam_title; $data_response['final_exam_title']=$final_exam_title; return $data_response; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="ด.ช."; }elseif($name_title_data=="dekying"){ $name_title="ด.ญ."; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="น.ส."; } return $name_title; } public function get_comulative_score($std_ID,$coures_id_list_val){ $data_response = array(); $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT SUM(score) as sum_score_total_before FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$std_ID' AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude WHERE proportion_status=1 ) "; $this->select(); $this->setRows(); $data_response['sum_score_total_before']=$this->rows[0]['sum_score_total_before']; $this->sql ="SELECT SUM(score) as sum_score_total_after FROM tbl_objective_score_std WHERE registed_courseID=$registed_courseID AND staID='$std_ID' AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude WHERE proportion_status=2 ) "; $this->select(); $this->setRows(); $data_response['sum_score_total_after']=$this->rows[0]['sum_score_total_after']; return $data_response; } public function get_mid_exam_score($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_final_exam_score($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_propotion_total($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val"; $this->select(); $this->setRows(); $data_response['cumulative_before_mid']=$this->rows[0]['cumulative_before_mid']; $data_response['cumulative_after_mid']=$this->rows[0]['cumulative_after_mid']; $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; $data_response['total']=$mid_exam+$final_exam; return $data_response; } public function search_course_detail($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level_co']=$class_level.'/'.$room_search; $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) ORDER BY std_ID ASC "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; //$attend_class_std_list=$this->get_attend_class_std_list($std_ID,$coures_id_list_val); $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); //$data_response['score_attend_class']=$score_attend_class; if ($score_exam=='i' || $score_pick=='i' || $score_attend_class=='nopass') { if ($score_exam=='i' || $score_pick=='i') { $data_i++; } if ($score_attend_class=='nopass') { $data_atte++; } }else{ $grade=$this->get_grade($score_exam,$score_pick); $data_response['exam'].=$grade.'-'; if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } $number++; } $data_response['attend_class_std_list']=$attend_class_std_list; $data_response['number']=$number; $data_response['data_i']=$data_i; $data_response['data_atte']=$data_atte; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; echo json_encode($data_response); } public function get_read_think_write($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; $score_read=0; $score_think=0; $score_write=0; $this->sql ="SELECT * FROM tbl_read_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_read=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_think_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_think=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_write_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_write=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_4=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_rtw_5=$this->rows[0]['score']; $score_total=($score_read+$score_think+$score_write+$score_rtw_4+$score_rtw_5)/5; if ($score_total<1) { $data='nopass'; }elseif($score_total<1.5){ $data='pass'; }elseif($score_total<2.5){ $data='good'; }elseif($score_total>=2.5){ $data='verygood'; } return $data; } public function get_desirable($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; for ($i=1; $i <= 8 ; $i++) { $this->sql ="SELECT * FROM tbl_desirable_$i WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score=$this->rows[0]['score']; $score_total=$score_total+$score; } $evaluation_score=$score_total/8; if ($evaluation_score<1) { $data='nopass'; }elseif($evaluation_score<1.5){ $data='pass'; }elseif($evaluation_score<2.5){ $data='good'; }elseif($evaluation_score>=2.5){ $data='verygood'; } return $data; } public function get_registed_courseID($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_grade($score_exam,$score_pick){ $total=$score_exam+$score_pick; if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_score_attend_class($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT COUNT(course_teaching_std_id) as sum_no_come FROM tbl_attend_class_std WHERE course_teaching_std_id IN( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID=$std_ID ) AND set_attend_day_id IN( SELECT DataID FROM tbl_set_attend_day WHERE registed_course_teachingID IN( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) ) "; $this->select(); $this->setRows(); $sum_no_come=$this->rows[0]['sum_no_come']; $registed_course_teaching_id=$this->get_registed_course_id($coures_id_list_val); $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id "; $this->select(); $this->setRows(); $num_hr=$this->rows[0]['num_hr']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $week_all=40; }else{ $week_all=20; } $total_day=$num_hr*$week_all; $total_attend_per=round((($total_day-$sum_no_come)*100)/$total_day); if ($total_attend_per>=80) { $find_80_per='pass'; }else{ $find_80_per='nopass'; } /* $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; $this->sql ="SELECT SUM(score_status) as sum_score FROM tbl_attend_class WHERE week BETWEEN 1 AND $week_name AND course_teaching_stdID in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $sum_score=$this->rows[0]['sum_score']; $data_must_pass=floor((80*$week_name)/100); if ($sum_score>=$data_must_pass) { $find_80_per='pass'; }else{ $find_80_per='nopass'; }*/ return $find_80_per; } public function get_registed_course_id($coures_id_list){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$coures_id_list ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data='p'; }else{ $data='m'; } return $data; } public function get_score_pick($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $num_of_i=0; $this->sql ="SELECT COUNT(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1 "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($num_of_i>0) { $total='i'; }else{ $total=$score_total_data; } return $total; } public function get_score_exam($std_ID,$coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $mid_status=0; $final_status=0; $this->sql ="SELECT COUNT(score) as num_of_i_mid FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_mid=$this->rows[0]['num_of_i_mid']; if ($num_of_i_mid>0) { $mid_status=-1; } $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $mid_exam_score=$this->rows[0]['score']; $this->sql ="SELECT COUNT(score) as num_of_i_final FROM tbl_final_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_final=$this->rows[0]['num_of_i_final']; if ($num_of_i_final>0) { $final_status=-1; } $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $final_exam_score=$this->rows[0]['score']; if ($mid_status==-1 || $final_status==-1) { $total='i'; }else{ $total=$mid_exam_score+$final_exam_score; } return $total; } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; $data_response['status']=$status; $data_response['status_form']=$status_form; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $user_status=$_SESSION['ss_status']; $user_id=$_SESSION['ss_user_id']; if ($user_status==1) { $this->sql ="SELECT room FROM tbl_room_teacher WHERE course_teacherID in( SELECT DataID FROM tbl_course_teacher WHERE teacher_id=$user_id AND regis_course_id in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; }else{ $this->sql =" SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT std_ID FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ) ORDER BY room ASC "; } $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option value='.$room.'>'.$room.'</option>'; } return json_encode($data_response); } public function get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6' ) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; }else{ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row==1) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; } } return $data_response; } public function get_coures_id_list($data_id,$data_room){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) AND DataID in( SELECT regis_course_id FROM tbl_course_teacher WHERE teacher_id=$user_id ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; $data_dicision=$this->get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set); $data_response['coures_id_list'].=$data_dicision; } return json_encode($data_response); } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/report/major_form.php <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/custom.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); ?> <page orientation="landscape"> <img style="margin :10px 0px 10px 495px;display:block;width: 80px;height: 80px;"src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 22px;margin-top: -5px;"> <p style="margin-top: -8px;"><span class="text-bold">รายงานการประเมินผลการเรียน กลุ่มสาระการเรียนรู้</span> ภาษาไทย</p> <p class="text-bold " style="margin-top: -8px;">โรงเรียนเทศบาลวัดสระทอง</p> <p style="margin-top: -8px;"> <span class="text-bold">ภาคเรียนที่ </span> 1 <span class="text-bold">ปีการศึกษา</span> 2560</p> </div> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 50px;border: 1px solid black;margin-top: 35px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;font-weight: bold;">ระดับชั้น</td> <td rowspan="2" style=" vertical-align: middle;width: 12%;font-weight: bold;">รหัสวิชา</td> <td colspan="10" style="width: 35%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="4" style="width:17%;padding: 5px;font-weight: bold;">คุณลักษณะฯ</td> <td colspan="4" style="width: 17%;padding: 5px;font-weight: bold;">อ่าน เขียน คิดฯ</td> <td rowspan="2" style=" vertical-align: middle;width: 15px;font-weight: bold;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3.5%;border-left: none;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> </tr> </thead> <tbody> <tr> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 50px;border: 1px solid black;margin-top: 35px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;font-weight: bold;">ระดับชั้น</td> <td rowspan="2" style=" vertical-align: middle;width: 12%;font-weight: bold;">รหัสวิชา</td> <td colspan="10" style="width: 35%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="4" style="width:17%;padding: 5px;font-weight: bold;">คุณลักษณะฯ</td> <td colspan="4" style="width: 17%;padding: 5px;font-weight: bold;">อ่าน เขียน คิดฯ</td> <td rowspan="2" style=" vertical-align: middle;width: 15px;font-weight: bold;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3.5%;border-left: none;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> </tr> </thead> <tbody> <tr> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 50px;border: 1px solid black;margin-top: 35px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;font-weight: bold;">ระดับชั้น</td> <td rowspan="2" style=" vertical-align: middle;width: 12%;font-weight: bold;">รหัสวิชา</td> <td colspan="10" style="width: 35%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="4" style="width:17%;padding: 5px;font-weight: bold;">คุณลักษณะฯ</td> <td colspan="4" style="width: 17%;padding: 5px;font-weight: bold;">อ่าน เขียน คิดฯ</td> <td rowspan="2" style=" vertical-align: middle;width: 15px;font-weight: bold;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3.5%;border-left: none;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> </tr> </thead> <tbody> <tr> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 50px;border: 1px solid black;margin-top: 35px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;font-weight: bold;">ระดับชั้น</td> <td rowspan="2" style=" vertical-align: middle;width: 12%;font-weight: bold;">รหัสวิชา</td> <td colspan="10" style="width: 35%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="4" style="width:17%;padding: 5px;font-weight: bold;">คุณลักษณะฯ</td> <td colspan="4" style="width: 17%;padding: 5px;font-weight: bold;">อ่าน เขียน คิดฯ</td> <td rowspan="2" style=" vertical-align: middle;width: 15px;font-weight: bold;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3.5%;border-left: none;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> </tr> </thead> <tbody> <tr> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 50px;border: 1px solid black;margin-top: 35px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;font-weight: bold;">ระดับชั้น</td> <td rowspan="2" style=" vertical-align: middle;width: 12%;font-weight: bold;">รหัสวิชา</td> <td colspan="10" style="width: 35%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="4" style="width:17%;padding: 5px;font-weight: bold;">คุณลักษณะฯ</td> <td colspan="4" style="width: 17%;padding: 5px;font-weight: bold;">อ่าน เขียน คิดฯ</td> <td rowspan="2" style=" vertical-align: middle;width: 15px;font-weight: bold;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3.5%;border-left: none;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> </tr> </thead> <tbody> <tr> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 11pt;margin-left: 50px;border: 1px solid black;margin-top: 35px;"> <thead > <tr class="text-middle" style="background-color: #e0e0e0;"> <td rowspan="2" style=" vertical-align: middle;width: 6px;font-weight: bold;">ที่</td> <td rowspan="2" style=" vertical-align: middle;width: 8%;font-weight: bold;">ระดับชั้น</td> <td rowspan="2" style=" vertical-align: middle;width: 12%;font-weight: bold;">รหัสวิชา</td> <td colspan="10" style="width: 35%;padding: 5px;font-weight: bold;">ระดับผลการเรียน</td> <td colspan="4" style="width:17%;padding: 5px;font-weight: bold;">คุณลักษณะฯ</td> <td colspan="4" style="width: 17%;padding: 5px;font-weight: bold;">อ่าน เขียน คิดฯ</td> <td rowspan="2" style=" vertical-align: middle;width: 15px;font-weight: bold;">รวม</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 3.5%;border-left: none;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> <td style="width: 3.5%;">1</td> </tr> </thead> <tbody> <tr> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">รวม</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td colspan="3" class="text-bold">ร้อยละ</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <div style="margin-left: 740px;margin-top: 60px;"> <p>.................................................................หัวหน้ากลุ่มสาระ </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> </page><file_sep>/modules/print_tset/class_modules.php <?php class ClassData extends Databases { public function get_attend_class_std_list($std_ID,$coures_id_list_val){ $data_response=" "; return $data_response; } public function search_course_detail($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level_co']=$class_level.'/'.$room_search; $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_response['num_all_std']=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $data_i=0; $data_atte=0; $data_00=0; $data_10=0; $data_15=0; $data_20=0; $data_25=0; $data_30=0; $data_35=0; $data_40=0; $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; $data_read_think_write_nopass=0; $data_read_think_write_pass=0; $data_read_think_write_good=0; $data_read_think_write_verygood=0; $number=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; //$attend_class_std_list=$this->get_attend_class_std_list($std_ID,$coures_id_list_val); $score_exam=$this->get_score_exam($std_ID,$coures_id_list_val); $score_pick=$this->get_score_pick($std_ID,$coures_id_list_val); $score_attend_class=$this->get_score_attend_class($std_ID,$coures_id_list_val); //$data_response['score_attend_class']=$score_attend_class; if ($score_exam=='i' || $score_pick=='i' || $score_attend_class=='nopass') { if ($score_exam=='i' || $score_pick=='i') { $data_i++; } if ($score_attend_class=='nopass') { $data_atte++; } }else{ $grade=$this->get_grade($score_exam,$score_pick); $data_response['exam'].=$grade.'-'; if ($grade=='0.0') { $data_00++; }elseif($grade=='1.0'){ $data_10++; }elseif($grade=='1.5'){ $data_15++; }elseif($grade=='2.0'){ $data_20++; }elseif($grade=='2.5'){ $data_25++; }elseif($grade=='3.0'){ $data_30++; }elseif($grade=='3.5'){ $data_35++; }elseif($grade=='4.0'){ $data_40++; } } $desirable=$this->get_desirable($std_ID,$coures_id_list_val); if ($desirable=='nopass') { $data_desirable_nopass++; }elseif($desirable=='pass'){ $data_desirable_pass++; }elseif($desirable=='good'){ $data_desirable_good++; }elseif($desirable=='verygood'){ $data_desirable_verygood++; } $read_think_write=$this->get_read_think_write($std_ID,$coures_id_list_val); if ($read_think_write=='nopass') { $data_read_think_write_nopass++; }elseif($read_think_write=='pass'){ $data_read_think_write_pass++; }elseif($read_think_write=='good'){ $data_read_think_write_good++; }elseif($read_think_write=='verygood'){ $data_read_think_write_verygood++; } $number++; } $data_response['attend_class_std_list']=$attend_class_std_list; $data_response['number']=$number; $data_response['data_i']=$data_i; $data_response['data_atte']=$data_atte; $data_response['data_00']=$data_00; $data_response['data_10']=$data_10; $data_response['data_15']=$data_15; $data_response['data_20']=$data_20; $data_response['data_25']=$data_25; $data_response['data_30']=$data_30; $data_response['data_35']=$data_35; $data_response['data_40']=$data_40; $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; $data_response['data_read_think_write_nopass']=$data_read_think_write_nopass; $data_response['data_read_think_write_pass']=$data_read_think_write_pass; $data_response['data_read_think_write_good']=$data_read_think_write_good; $data_response['data_read_think_write_verygood']=$data_read_think_write_verygood; echo json_encode($data_response); } public function get_read_think_write($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; $score_read=0; $score_think=0; $score_write=0; $this->sql ="SELECT * FROM tbl_read_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_read=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_think_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_think=$this->rows[0]['score']; $this->sql ="SELECT * FROM tbl_write_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score_write=$this->rows[0]['score']; $score_total=($score_read+$score_think+$score_write)/3; if ($score_total<1) { $data='nopass'; }elseif($score_total<1.5){ $data='pass'; }elseif($score_total<2.5){ $data='good'; }elseif($score_total>=2.5){ $data='verygood'; } return $data; } public function get_desirable($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $score_total=0; for ($i=1; $i <= 8 ; $i++) { $this->sql ="SELECT * FROM tbl_desirable_$i WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $score=$this->rows[0]['score']; $score_total=$score_total+$score; } $evaluation_score=$score_total/8; if ($evaluation_score<1) { $data='nopass'; }elseif($evaluation_score<1.5){ $data='pass'; }elseif($evaluation_score<2.5){ $data='good'; }elseif($evaluation_score>=2.5){ $data='verygood'; } return $data; } public function get_registed_courseID($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_grade($score_exam,$score_pick){ $total=$score_exam+$score_pick; if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_score_attend_class($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; $this->sql ="SELECT SUM(score_status) as sum_score FROM tbl_attend_class WHERE week BETWEEN 1 AND $week_name AND course_teaching_stdID in( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $sum_score=$this->rows[0]['sum_score']; $data_must_pass=floor((80*$week_name)/100); if ($sum_score>=$data_must_pass) { $find_80_per='pass'; }else{ $find_80_per='nopass'; } return $find_80_per; } public function get_score_pick($std_ID,$coures_id_list_val){ $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $num_of_i=0; $this->sql ="SELECT COUNT(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1 "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($num_of_i>0) { $total='i'; }else{ $total=$score_total_data; } return $total; } public function get_score_exam($std_ID,$coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $mid_status=0; $final_status=0; $this->sql ="SELECT COUNT(score) as num_of_i_mid FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_mid=$this->rows[0]['num_of_i_mid']; if ($num_of_i_mid>0) { $mid_status=-1; } $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $mid_exam_score=$this->rows[0]['score']; $this->sql ="SELECT COUNT(score) as num_of_i_final FROM tbl_final_exam_score WHERE stdID='$std_ID' AND score=-1 AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_of_i_final=$this->rows[0]['num_of_i_final']; if ($num_of_i_final>0) { $final_status=-1; } $this->sql ="SELECT * FROM tbl_final_exam_score WHERE stdID='$std_ID' AND course_teachingID in( SELECT DataID FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $final_exam_score=$this->rows[0]['score']; if ($mid_status==-1 || $final_status==-1) { $total='i'; }else{ $total=$mid_exam_score+$final_exam_score; } return $total; } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option value='.$room.'>'.$room.'</option>'; } return json_encode($data_response); } public function get_coures_id_list($data_id,$data_room){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$DataID.'">'.$courseID_long.'</option> '; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='1,2' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$DataID.'">'.$courseID_long.'</option> '; } return json_encode($data_response); } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/regis_teacher/edit.js var opPage = 'regis_teacher'; $(document).ready(function() { get_day_edit(1); years_set(); get_data_edit(); }); function years_set() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_years" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#years_set").html(data.set_years); }); } function get_day_edit(mouth) { //var formData = $( "#frm_data" ).serializeArray(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_day_edit" }); formData.push({ "name": "mouth", "value": mouth }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { console.log(data.day_set) $("#day_set").html(data.day_set); }); } function edit_teacher() { var id=_get.id; var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "edit_teacher" }); formData.push({ "name": "data_id", "value": id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); $("#modalEdited").modal("show"); }); } function get_data_edit() { var id=_get.id; var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_data_edit" }); formData.push({ "name": "data_id", "value": id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#positionID").val(data.positionID); $("#position_name").val(data.position_name); $("#fname_th").val(data.fname_th); $("#lname_th").val(data.lname_th); $("#fname_en").val(data.fname_en); $("#lname_en").val(data.lname_en); $("#blood_group").val(data.blood_group); $("#years_set").val(data.year); $("#mouth").val(data.month); $("#day_set").val(data.day); $("#gender").val(data.gender); $("#tell").val(data.tell); $("#email").val(data.email); $("#address").val(data.address); $("#status_alive").val(data.status_alive); //$("#modalRegistered").modal("show"); }); }<file_sep>/modules/menu/upload_keyword.js var data_id = (typeof _get.id === 'undefined') ? 0 : _get.id; $(document).delegate('#bt_add_keyword', 'click', function(event) { var KeyName = $('#KeyName').val(); $.post('modules/contact/process.php', { 'acc_action' : 'add_keyword', 'contactID' : data_id, 'key_name': KeyName }, function(data) { $('#KeyName').val(""); get_keyword(); }); }); function get_keyword(){ $.post('modules/contact/process.php', {acc_action: 'get_keyword','data_id':data_id}, function(data) { $('#tb_keyword').html(data); }); } $(document).delegate('.btn_remove_key', 'click', function(event) { key_id = $(this).attr('data-id'); $('#modal_key_cancel').modal('show'); }); $(document).delegate('#btn__key_remove', 'click', function(event) { $.post('modules/contact/process.php', { 'acc_action' : 'remove_keyword', 'data_id' : key_id }, function(response) { $('#modal_key_cancel').modal('hide'); get_keyword(); }); return false; });<file_sep>/modules/conclusion/form/learning_result_footer.php <?php $footer_text=' <div style="line-height:0.5;margin-top:10px;"> <p style="font-size:14px;"> <span>หมายเหตุ : วิชากิจกรรมพัฒนาผู้เรียน ผ หมายถึง ผ่าน, มผ หมายถึง ไม่ผ่าน | </span> <span>การประเมินผลคุณลักษณะอันพึงประสงค์ 3 หมายถึง ดีเยี่ยม, 2 หมายถึง ดี, 1 หมายถึง ผ่าน | </span> <span>การประเมินผลการอ่าน เขียน คิด วิเคราะห์3 หมายถึง ดีเยี่ยม, 2 หมายถึง ดี, 1 หมายถึง ผ่าน</span> </p> </div> <div style="margin-left:10%;margin-top:20px;font-size:14px"> <div style="line-height:0.5;"> <p> ................................................................. ครูประจำชั้น </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. รองผู้อำนวยการฝ่ายวิชาการ </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> </div> <div style="margin-left:60%;margin-top:-122px;font-size:14px"> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. หัวหน้างานวัดผล </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. ผู้อำนวยการสถานศึกษา </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> </div> '; $footer_text_detail=' <div style="line-height:0.5;margin-top:10px;"> <p style="font-size:14px;"> <span>หมายเหตุ : วิชากิจกรรมพัฒนาผู้เรียน ผ หมายถึง ผ่าน, มผ หมายถึง ไม่ผ่าน | </span> <span>การประเมินผลคุณลักษณะอันพึงประสงค์ 3 หมายถึง ดีเยี่ยม, 2 หมายถึง ดี, 1 หมายถึง ผ่าน |</span> <span>การประเมินผลการอ่าน เขียน คิด วิเคราะห์3 หมายถึง ดีเยี่ยม, 2 หมายถึง ดี, 1 หมายถึง ผ่าน</span> </p> </div> '; $footer_text_cen=' <div style="margin-left:10%;margin-top:20px;font-size:14px"> <div style="line-height:0.5;"> <p> ................................................................. ครูประจำชั้น </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. รองผู้อำนวยการฝ่ายวิชาการ </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> </div> <div style="margin-left:60%;margin-top:-122px;font-size:14px"> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. หัวหน้างานวัดผล </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. ผู้อำนวยการสถานศึกษา </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> </div> '; $footer_text_cen_normal=' <div style="margin-left:10%;margin-top:20px;font-size:14px"> <div style="line-height:0.5;"> <p> ................................................................. ครูประจำชั้น </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> <div style="line-height:0.5;margin-top:40px;"> <p> ................................................................. รองผู้อำนวยการฝ่ายวิชาการ </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> </div> <div style="margin-left:60%;margin-top:-142px;font-size:14px"> <div style="line-height:0.5;margin-top:20px;"> <p> ................................................................. หัวหน้างานวัดผล </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> <div style="line-height:0.5;margin-top:40px;"> <p> ................................................................. ผู้อำนวยการสถานศึกษา </p> <p> <span>(</span><span style="margin-left:170px;">)</span> </p> <p> ...................../...................../..................... </p> </div> </div> '; ?><file_sep>/modules/news/class_modules.php <?php class ClassData extends Databases { public function update_news($update,$data_id){ $this->sql = "UPDATE tbl_news SET ".implode(",",$update)." WHERE DataID='".$data_id."'"; $this->query(); $new_id = $this->insertID(); return json_encode($new_id); } public function delete_img_file($data_id,$set_type){ if ($set_type==1) { $this->sql ="SELECT file_name FROM tbl_news_gallery WHERE DataID=$data_id "; $this->select(); $this->setRows(); $file_name=$this->rows[0]['file_name']; @unlink("../../file_managers/news/".$file_name); $sql = "DELETE FROM tbl_news_gallery WHERE DataID=$data_id "; $this->sql = $sql; $this->query(); }else{ $this->sql ="SELECT file_name FROM tbl_news_gallery_sub WHERE DataID=$data_id "; $this->select(); $this->setRows(); $file_name=$this->rows[0]['file_name']; @unlink("../../file_managers/news_sub/".$file_name); $sql = "DELETE FROM tbl_news_gallery_sub WHERE DataID=$data_id "; $this->sql = $sql; $this->query(); } return json_encode('1'); } public function delete_news($data_id){ $sql = "DELETE FROM tbl_news WHERE DataID=$data_id "; $this->sql = $sql; $this->query(); return json_encode('1'); } public function insert_news($insert){ $this->sql = "INSERT INTO tbl_news(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); return $this->insertID(); } public function get_author($authorID){ $this->sql ="SELECT * FROM tbl_regis_teacher WHERE DataID=$authorID "; $this->select(); $this->setRows(); $fname_th=$this->rows[0]['fname_th']; $lname_th=$this->rows[0]['lname_th']; return $fname_th.' '.$lname_th; } public function get_news_detail($news_id){ $this->sql ="SELECT * FROM tbl_news WHERE DataID=$news_id "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $data_response['title']=$this->rows[0]['title']; $data_response['detail']=(unchkhtmlspecialchars($this->rows[0]['detail'])); $img_list=$this->get_img($DataID); $data_response['img_list']=$img_list; return json_encode($data_response); } public function get_img($news_id){ $this->sql ="SELECT COUNT(*) AS num_row_img_main,file_name,DataID FROM tbl_news_gallery WHERE newsID=$news_id "; $this->select(); $this->setRows(); $num_row_img_main=$this->rows[0]['num_row_img_main']; $DataID=$this->rows[0]['DataID']; $file_name=$this->rows[0]['file_name']; if ($num_row_img_main>0) { $data_response=' <div class="row"> <div class="col-sm-3" style="text-align:right"> <div class="delete_img_set" set-type="1" data-id="'.$DataID.'" aria-hidden="true" data-toggle="modal" data-target="#modalDeleteImg"> <span class="glyphicon glyphicon-remove-circle edit-icon-table"></span> </div> </div> <div class="col-sm-9 mb-10"> <img src="file_managers/news/'.$file_name.'" style="width: 80%" id="output1"/> </div> </div> '; }else{ $data_response.=' <div class="row"> <div class="col-sm-3"> <input name="img1" type="file" accept="image/*" onchange="loadFile1()"> </div> <div class="col-sm-9 mb-10"> <img style="width:80%" id="output1"/> </div> </div> '; } $this->sql ="SELECT COUNT(*) AS num_row_img_sub FROM tbl_news_gallery_sub WHERE newsID=$news_id "; $this->select(); $this->setRows(); $num_row_img_sub=$this->rows[0]['num_row_img_sub']; if ($num_row_img_sub>0) { $this->sql ="SELECT * FROM tbl_news_gallery_sub WHERE newsID=$news_id "; $this->select(); $this->setRows(); $amount_set_tag=2; foreach($this->rows as $key => $value) { $file_name=$value['file_name']; $DataID=$value['DataID']; $data_response.=' <div class="row"> <div class="col-sm-3" style="text-align:right"> <div class="delete_img_set" set-type="2" data-id="'.$DataID.'" aria-hidden="true" data-toggle="modal" data-target="#modalDeleteImg"> <span class="glyphicon glyphicon-remove-circle edit-icon-table"></span> </div> </div> <div class="col-sm-9 mb-10"> <img src="file_managers/news_sub/'.$file_name.'" style="width:80%" id="output'.$amount_set_tag.'"/> </div> </div> '; $amount_set_tag++; } } $amount_start_loop=$num_row_img_sub+2; for ($i=$amount_start_loop; $i <= 5; $i++) { $data_response.=' <div class="row"> <div class="col-sm-3"> <input name="img'.$i.'" type="file" accept="image/*" onchange="loadFile'.$i.'()"> </div> <div class="col-sm-9 mb-10"> <img style="width:80%" id="output'.$i.'"/> </div> </div> '; } return $data_response; } public function get_news_list(){ $this->sql ="SELECT * FROM tbl_news ORDER BY date DESC,DataID DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $title=$value['title']; $authorID=$value['author']; $author_name=$this->get_author($authorID); $date_form = strtotime($value['date']); $date_set=date('d-m-Y', $date_form); $data_response.=' <tr> <td style="text-align: center;">'.$date_set.'</td> <td style="text-align: left;padding-left: 2%">'.$title.'</td> <td style="text-align: center;">'.$author_name.'</td> <td style="text-align: center;"> <a href="index.php?op=news-edit&id='.$DataID.'"> <div class="icon-circle-edit bt_delete" data-id="285-1" aria-hidden="true" data-toggle="modal" data-target="#modalConfirm"> <span class="glyphicon glyphicon-edit edit-icon-table"></span> </div> </a> </td> <td style="text-align: center;"> <div class="bt_delete" data-id="'.$DataID.'" aria-hidden="true" data-toggle="modal" data-target="#modalDelete"> <span class="glyphicon glyphicon-trash edit-icon-table"></span> </div> </td> </tr> '; } return json_encode($data_response); } }<file_sep>/modules/regis_teacher/class_modules.php <?php class ClassData extends Databases { public function get_data_edit($data_id){ $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID=$data_id "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['positionID']=$this->rows[0]['positionID']; $data_response['position_name']=$this->rows[0]['position_name']; $data_response['fname_th']=$this->rows[0]['fname_th']; $data_response['lname_th']=$this->rows[0]['lname_th']; $data_response['fname_en']=$this->rows[0]['fname_en']; $data_response['lname_en']=$this->rows[0]['lname_en']; $birthday_data=$this->rows[0]['birthday']; $data_response['blood_group']=$this->rows[0]['blood_group']; $data_response['gender']=$this->rows[0]['gender']; $data_response['tell']=$this->rows[0]['tell']; $data_response['email']=$this->rows[0]['email']; $data_response['address']=$this->rows[0]['address']; $data_response['status_alive']=$this->rows[0]['status_alive']; $birthday=$this->get_birthday($birthday_data); $data_response['day']=$birthday['day']; $data_response['month']=$birthday['month']; $data_response['year']=$birthday['year']; return json_encode($data_response); } public function get_birthday($birthday){ $time = strtotime($birthday); $birthday_result['day'] = date('d',$time); $birthday_result['month'] = date('m',$time); $birthday_result['year'] = date('Y',$time)+543; return $birthday_result; } public function get_teacher($status,$data_search){ $sql_condition = " DataID is not null "; if ($status=='id') { if (isset($data_search) && $data_search != "") { $sql_condition .= " AND ( positionID LIKE '%{$data_search}%') "; } }elseif($status=='name'){ if (isset($data_search) && $data_search != "") { $sql_condition .= " AND ( fname_th LIKE '%{$data_search}%') OR ( lname_th LIKE '%{$data_search}%')"; } } $sql = "SELECT DataID,positionID,fname_th,lname_th ,status_alive FROM tbl_regis_teacher WHERE $sql_condition ORDER BY fname_th "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $positionID= $value['positionID']; $fname_th= $value['fname_th']; $lname_th= $value['lname_th']; $status_alive= $value['status_alive']; $status_text=$this->get_status_text($status_alive); $data_response.=' <tr> <td ></td> <td style="text-align: center;">'.$positionID.'</td> <td style="text-align: left;padding-left:10%;">'.$fname_th.'</td> <td style="text-align: left;padding-left:10%;">'.$lname_th.'</td> <td style="text-align: center;">'.$status_text.'</td> <td style="text-align:center;"> <a href="index.php?op=regis_teacher-edit&id='.$DataID.'"> <span class="glyphicon glyphicon-edit edit-icon-table" ari="" a-hidden="true"></span> </a> </td> <td style="text-align:center;"> <div data-id="'.$DataID.'" class="bt_change_pass" aria-hidden="true" data-toggle="modal" data-target="#modalChangePass"> <span class="glyphicon glyphicon-refresh edit-icon-table" ari="" a-hidden="true"></span> </div> </td> </tr> '; } echo json_encode($data_response); } public function get_status_text($status_alive){ switch($status_alive){ case '1': $data_response='ปกติ'; break; case '2': $data_response='ย้าย'; break; case '3': $data_response='เสียชีวิต'; break; case '4': $data_response='เกษียณ'; break; case '5': $data_response='ยกเลิกการใช้งาน'; break; default : $data_response=''; break; } return $data_response; } public function change_pass($data_val){ $sql = "SELECT birthday FROM tbl_regis_teacher WHERE DataID=$data_val "; $this->sql = $sql; $this->select(); $this->setRows(); $birthday_set=$this->rows[0]['birthday']; list($year_set,$month,$day) = split('[-]', $birthday_set); $year_set=$year_set+543; $password_set=MD5($day.$month.$year_set); $this->sql = "UPDATE tbl_regis_teacher SET password='$<PASSWORD>' WHERE DataID=$data_val"; $this->query(); return json_encode($password_set); } public function get_data_delete($data_val){ $arr_id = explode(",", $data_val); $num=0; for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="DELETE FROM tbl_regis_teacher WHERE DataID = '{$arr_id[$i]}'"; $this->query(); $num=$num+$i; } return $num; } public function update_data($update,$user_id){ $this->sql = "UPDATE tbl_regis_teacher SET ".implode(",",$update)." WHERE DataID='".$user_id."'"; $this->query(); } public function insert_data($insert){ $this->sql = "INSERT INTO tbl_regis_teacher(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $new_id = $this->insertID(); } public function get_years(){ $data_response = array(); $years_now=intval(date("Y"));+ $years_now=$years_now+543; $data_response['set_years']='<option value="0">ปี</option>'; for ($i=$years_now; $i >= 2480 ; $i--) { $data_response['set_years'].='<option value="'.$i.'">'.$i.'</option>'; } echo json_encode($data_response); } public function get_day_edit($mouth){ $data_response = array(); for ($i=1; $i <= 29 ; $i++) { if ($i<=9) { $day_make_29.='<option value="0'.$i.'">'.$i.'</option>'; }else{ $day_make_29.='<option value="'.$i.'">'.$i.'</option>'; } } for ($i=1; $i <= 30 ; $i++) { if ($i<=9) { $day_make_30.='<option value="0'.$i.'">'.$i.'</option>'; }else{ $day_make_30.='<option value="'.$i.'">'.$i.'</option>'; } } for ($i=1; $i <= 31 ; $i++) { if ($i<=9) { $day_make_31.='<option value="0'.$i.'">'.$i.'</option>'; }else{ $day_make_31.='<option value="'.$i.'">'.$i.'</option>'; } } if ($mouth==1 || $mouth==3 || $mouth==5 || $mouth==7 || $mouth==8 || $mouth==10 || $mouth==12) { $data_response['day_set']=$day_make_31; }elseif($mouth==4 || $mouth==6 || $mouth==9 || $mouth==11){ $data_response['day_set']=$day_make_30; }else{ $data_response['day_set']=$day_make_29; } echo json_encode($data_response); } public function get_day($mouth){ $data_response = array(); $day_make_29.='<option value="0">วัน</option>'; $day_make_30.='<option value="0">วัน</option>'; $day_make_31.='<option value="0">วัน</option>'; for ($i=1; $i <= 29 ; $i++) { $day_make_29.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 30 ; $i++) { $day_make_30.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 31 ; $i++) { $day_make_31.='<option value="'.$i.'">'.$i.'</option>'; } if ($mouth==1 || $mouth==3 || $mouth==5 || $mouth==7 || $mouth==8 || $mouth==10 || $mouth==12) { $data_response['day_set']=$day_make_31; }elseif($mouth==4 || $mouth==6 || $mouth==9 || $mouth==11){ $data_response['day_set']=$day_make_30; }else{ $data_response['day_set']=$day_make_29; } echo json_encode($data_response); } }<file_sep>/login.php <?php @ob_start(); @session_start(); require_once('init.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>ระบบวัดและประเมินผล</title> <!-- Bootstrap --> <link href="assets/css/bootstrap.min.css" rel="stylesheet"> <link href="assets/css/custom.css" rel="stylesheet"> <link href="assets/css/margin-padding.css" rel="stylesheet"> <link rel="icon" type="image/gif/png" href="assets/images/logo.png"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" media="screen and (max-width:768px)" href="assets/css/extrasmall.css"> <link rel="stylesheet" type="text/css" media="screen and (min-width:768px)" href="assets/css/small.css"> <link rel="stylesheet" type="text/css" media="screen and (min-width:992px)" href="assets/css/medium.css"> <link rel="stylesheet" type="text/css" media="screen and (min-width:1200px)" href="assets/css/large.css"> <!--[if lte IE 9]> <link href="assets/pages/css/ie9.css" rel="stylesheet" type="text/css" /> <![endif]--> <style> .my-modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 999; /* Sit on top */ padding-top: 130px; /* Location of the box */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: auto; /* Enable scroll if needed */ background-color: rgb(0,0,0); /* Fallback color */ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */ } /* Modal Content */ .my-modal-content { border-radius: 10px; background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 40%; } /* The Close Button */ .my-close { color: #aaaaaa; float: right; font-size: 28px; margin-top: -20px; font-weight: bold; } .my-close:hover, .my-close:focus { color: #000; text-decoration: none; cursor: pointer; } </style> <script type="text/javascript"> window.onload = function() { // fix for windows 8 if (navigator.appVersion.indexOf("Windows NT 6.2") != -1) document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="assets/pages/css/windows.chrome.fix.css" />' } </script> </head> <body class="fixed-header "> <section class="section-index"> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-offset-4"> <img class="logo-index" src="assets/images/logo.png"> </div> </div> <div class="row"> <div class="text-header-index"> <div class="text-first-index"> <h1>ระบบวัดและประเมินผล</h1> </div> <div class="text-second-index"> <h3>โรงเรียนเทศบาลวัดสระทอง</h3> </div> </div> </div> <div class="mt-20"> <form id="form__data" class="form-horizontal"> <div class="form-group"> <div class="col-sm-4 col-sm-offset-4" > <center> <div class="input-group edit-size-form-icon" > <div class="input-group-addon edit-line-form"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></div> <input name="username" id="username" type="text" class="form-control edit-line-form edit-size-form-input" id="exampleInputAmount" placeholder="Username" > </div> </center> </div> <div class="col-sm-4 col-sm-offset-4 mt-20"> <center> <div class="input-group edit-size-form-icon" > <div class="input-group-addon edit-line-form"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></div> <input name="<PASSWORD>" id="<PASSWORD>" type="<PASSWORD>" class="form-control edit-line-form edit-size-form-input" id="exampleInputAmount" placeholder="<PASSWORD>" > </div> </center> </div> </div> <div class="col-sm-3 col-sm-offset-4" style="text-align: center;"> <a class="text-forget" id="myBtn" style="color: #777;" href="#">Forgot your password ?</a> </div> <div class="col-sm-3 col-sm-offset-4 mt-15"> <div id="submit__data" class="edit-btn-login"> เข้าสู่ระบบ </div> </div> </form> </div> </div> <div class="row"> <div class="col-md-4 col-sm-offset-4 mt-20" style="text-align: center;"> <div id="alert__panel" class="alert alert-danger" style="display:none;"> <strong>Username or password incorrect</strong> </div> </div> </div> <div class="tab-footer"> </div> <div id="myModal" class="my-modal"> <!-- Modal content --> <div class="my-modal-content" style="text-align: center;"> <span class="my-close" >&times;</span> <p style="font-size: 18px;">กรุณาติดต่อ</p> <p style="font-size: 24px;font-weight: bold;">ผู้รับผิดชอบงานวัดผล</p> <p style="font-size: 18px;">โรงเรียนเทศบาลวัดสระทอง</p> </div> </section> <!-- END PAGE CONTAINER --> <!-- BEGIN VENDOR JS --> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script type="text/javascript" src="assets/js/jquery.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="assets/js/bootstrap.min.js"></script> <script src="modules/login/login.js?<?=time();?>" type="text/javascript"></script> <!-- END PAGE LEVEL JS --> <script> // Get the modal var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("my-close")[0]; // When the user clicks the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> </html><file_sep>/modules/save_score/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_read_score_std"){ $value_score_read=$_POST['value_score_read']; $value_score_write=$_POST['value_score_write']; $value_score_think=$_POST['value_score_think']; $value_score_rtw_4=$_POST['value_score_rtw_4']; $value_score_rtw_5=$_POST['value_score_rtw_5']; $std_id_all_read=$_POST['std_id_all_read']; $arr_id_value_score_read = explode("-", $value_score_read); $arr_id_value_score_write = explode("-", $value_score_write); $arr_id_value_score_think = explode("-", $value_score_think); $arr_id_value_score_rtw_4 = explode("-", $value_score_rtw_4); $arr_id_value_score_rtw_5 = explode("-", $value_score_rtw_5); $teaching_id_find=$_POST['teaching_id_find']; $arr_std_id_all_read = explode("-", $std_id_all_read); $num_1=0; for ($i=0; $i <count($arr_std_id_all_read) ; $i++) { $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_read_score WHERE stdID='{$arr_std_id_all_read[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_read_score(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_read[$i]}',$arr_id_value_score_read[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_read_score SET score=$arr_id_value_score_read[$num_1] WHERE stdID='$arr_std_id_all_read[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_write_score WHERE stdID='{$arr_std_id_all_read[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_write_score(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_read[$i]}',$arr_id_value_score_write[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_write_score SET score=$arr_id_value_score_write[$num_1] WHERE stdID='$arr_std_id_all_read[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_think_score WHERE stdID='{$arr_std_id_all_read[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_think_score(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_read[$i]}',$arr_id_value_score_think[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_think_score SET score=$arr_id_value_score_think[$num_1] WHERE stdID='$arr_std_id_all_read[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_rtw_4_score WHERE stdID='{$arr_std_id_all_read[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_rtw_4_score(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_read[$i]}',$arr_id_value_score_rtw_4[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_rtw_4_score SET score=$arr_id_value_score_rtw_4[$num_1] WHERE stdID='$arr_std_id_all_read[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_rtw_5_score WHERE stdID='{$arr_std_id_all_read[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_rtw_5_score(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_read[$i]}',$arr_id_value_score_rtw_5[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_rtw_5_score SET score=$arr_id_value_score_rtw_5[$num_1] WHERE stdID='$arr_std_id_all_read[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $num_1++; } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_desirable_score_std"){ $value_score_desirable_1=$_POST['value_score_desirable_1']; $value_score_desirable_2=$_POST['value_score_desirable_2']; $value_score_desirable_3=$_POST['value_score_desirable_3']; $value_score_desirable_4=$_POST['value_score_desirable_4']; $value_score_desirable_5=$_POST['value_score_desirable_5']; $value_score_desirable_6=$_POST['value_score_desirable_6']; $value_score_desirable_7=$_POST['value_score_desirable_7']; $value_score_desirable_8=$_POST['value_score_desirable_8']; $std_id_all_desirable=$_POST['std_id_all_desirable']; $arr_id_value_score_desirable_1 = explode("-", $value_score_desirable_1); $arr_id_value_score_desirable_2 = explode("-", $value_score_desirable_2); $arr_id_value_score_desirable_3 = explode("-", $value_score_desirable_3); $arr_id_value_score_desirable_4 = explode("-", $value_score_desirable_4); $arr_id_value_score_desirable_5 = explode("-", $value_score_desirable_5); $arr_id_value_score_desirable_6 = explode("-", $value_score_desirable_6); $arr_id_value_score_desirable_7 = explode("-", $value_score_desirable_7); $arr_id_value_score_desirable_8 = explode("-", $value_score_desirable_8); $teaching_id_find=$_POST['teaching_id_find']; $arr_std_id_all_desirable = explode("-", $std_id_all_desirable); $num_1=0; $num_2=0; for ($i=0; $i <count($arr_std_id_all_desirable) ; $i++) { $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_1 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_1(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_1[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_1 SET score=$arr_id_value_score_desirable_1[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_2 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_2(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_2[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_2 SET score=$arr_id_value_score_desirable_2[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_3 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_3(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_3[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_3 SET score=$arr_id_value_score_desirable_3[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_4 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_4(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_4[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_4 SET score=$arr_id_value_score_desirable_4[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_5 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_5(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_5[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_5 SET score=$arr_id_value_score_desirable_5[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_6 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_6(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_6[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_6 SET score=$arr_id_value_score_desirable_6[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_7 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_7(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_7[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_7 SET score=$arr_id_value_score_desirable_7[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_desirable_8 WHERE stdID='{$arr_std_id_all_desirable[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_desirable_8(course_teachingID,stdID,score) VALUES($teaching_id_find,'{$arr_std_id_all_desirable[$i]}',$arr_id_value_score_desirable_8[$num_1]) "; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_desirable_8 SET score=$arr_id_value_score_desirable_8[$num_1] WHERE stdID='$arr_std_id_all_desirable[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $num_1++; } echo $data; } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_exam_score_std"){ $value_score_mid=$_POST['value_score_mid']; $value_score_final=$_POST['value_score_final']; $std_id_all_exam=$_POST['std_id_all_exam']; $teaching_id_find=$_POST['teaching_id_find']; $arr_id_value_score_mid = explode(",", $value_score_mid); $arr_id_value_score_final = explode(",", $value_score_final); $arr_std_id_all_exam = explode("-", $std_id_all_exam); $num_mid=0; $num_final=0; for ($i=0; $i <count($arr_std_id_all_exam) ; $i++) { for ($j=0; $j < 1 ; $j++) { if ($arr_id_value_score_mid[$num_mid]=='ร') { $arr_id_value_score_mid[$num_mid]=-1; } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_mid_exam_score WHERE stdID='{$arr_std_id_all_exam[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_mid_exam_score(course_teachingID,stdID,score) VALUES($teaching_id_find, '{$arr_std_id_all_exam[$i]}', $arr_id_value_score_mid[$num_mid])"; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_mid_exam_score SET score=$arr_id_value_score_mid[$num_mid] WHERE stdID='{$arr_std_id_all_exam[$i]}' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $num_mid++; } for ($z=0; $z < 1 ; $z++) { if ($arr_id_value_score_final[$num_final]=='ร') { $arr_id_value_score_final[$num_final]=-1; } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_final_exam_score WHERE stdID='{$arr_std_id_all_exam[$i]}' AND course_teachingID=$teaching_id_find "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_final_exam_score(course_teachingID,stdID,score) VALUES($teaching_id_find, '{$arr_std_id_all_exam[$i]}', $arr_id_value_score_final[$num_final])"; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_final_exam_score SET score=$arr_id_value_score_final[$num_final] WHERE stdID='$arr_std_id_all_exam[$i]' AND course_teachingID=$teaching_id_find"; echo $class_data->query(); } $num_final++; } } echo json_encode($arr_id_value_score_mid); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_objective_score_std"){ $_SESSION['status_active']=$_POST['status']; $std_id_all=$_POST['std_id_all']; $registed_courseID=$_POST['registed_courseID']; //$length_list_val=$_POST['length_list_val']; $value_score=$_POST['value_score']; $data_objectiveID_of_title=$_POST['data_objectiveID_of_title']; //list($start_data,$end_data) = split('[-]', $length_list_val); $arr_id_value_score = explode(",", $value_score); $arr_data_objectiveID_of_title = explode("-", $data_objectiveID_of_title); $arr_std_id_all = explode("-", $std_id_all); $num_arr_id_value_score=count($arr_id_value_score); $num=0; for ($i=0; $i <count($arr_std_id_all) ; $i++) { for ($j=0; $j < count($arr_data_objectiveID_of_title) ; $j++) { if ($arr_id_value_score[$num]=='ร') { $arr_id_value_score[$num]=-1; } $class_data->sql ="SELECT count(*) as num_row_chk FROM tbl_objective_score_std WHERE staID='{$arr_std_id_all[$i]}' AND objectiveID=$arr_data_objectiveID_of_title[$j] AND registed_courseID=$registed_courseID "; $class_data->select(); $class_data->setRows(); $num_row_chk=$class_data->rows[0]['num_row_chk']; if ($num_row_chk==0) { $class_data->sql ="INSERT INTO tbl_objective_score_std(objectiveID,registed_courseID,staID,score) VALUES($arr_data_objectiveID_of_title[$j], $registed_courseID, '{$arr_std_id_all[$i]}', $arr_id_value_score[$num])"; echo $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_objective_score_std SET score=$arr_id_value_score[$num] WHERE staID='$arr_std_id_all[$i]' AND objectiveID=$arr_data_objectiveID_of_title[$j] AND registed_courseID=$registed_courseID"; echo $class_data->query(); } $num++; } } echo json_encode(); //echo $class_data->save_objective_score_std($objective_list); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "open_edit_score"){ $objective_list=$_GET['objective_list']; echo $class_data->open_edit_score($objective_list); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "set_col_header"){ $length_list_val=$_GET['length_list_val']; echo $class_data->set_col_header($length_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_objective_list"){ unset($_SESSION['status_active']); $room_search=$_GET['room_search']; $coures_id_list_val=$_GET['coures_id_list_val']; $length_list_val=$_GET['length_list_val']; $legth_score=$_GET['legth_score']; $user_status=$_SESSION['ss_status']; if ($user_status==1) { echo $class_data->get_objective_list($coures_id_list_val,$length_list_val,$room_search,$legth_score); }elseif($user_status==2){ $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_objective_list_admin($coures_id_list_val,$length_list_val,$room_search,$legth_score,$term_data,$year_data); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_config"){ $legth_score=$_GET['legth_score']; $coures_id_list_val=$_GET['coures_id_list_val']; $room_search=$_GET['room_search']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_config($legth_score,$coures_id_list_val,$room_search,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_detail"){ $coures_id_list=$_GET['coures_id_list']; $room_search=$_GET['room_search']; $room_search=$_GET['room_search']; echo $class_data->search_course_detail($coures_id_list,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_class_level"){ $coures_id_list_val=$_GET['coures_id_list_val']; $user_status=$_SESSION['ss_status']; if ($user_status==1) { echo $class_data->get_class_level($coures_id_list_val); }elseif($user_status==2){ $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_class_level_admin($coures_id_list_val,$term_data,$year_data); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list"){ $user_status=$_SESSION['ss_status']; if ($user_status==1) { echo $class_data->get_coures_id_list(); }elseif($user_status==2){ $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_coures_id_list_admin($term_data,$year_data); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); }<file_sep>/modules/news/add.js document.write(' <script type="text/javascript" src="assets/js/wyzz.php"></script>'); var opPage = 'news'; $(document).ready(function() { }); $(document).delegate('#btn_add_news', 'click', function(event) { $("#btn_submit").click(); }); function loadFile1() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output1'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile2() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output2'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile3() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output3'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile4() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output4'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile5() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output5'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; <file_sep>/modules/conclusion/form/header_table_department.php <?php $header_table=' <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 2%;height: 0px;text-align: center;"> <div >ที่</div> </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >ระดับชั้น</div> </th> <th rowspan="2" class="rotate" style="width: 12%;height: 0px;text-align: center;"> <div >รหัสวิชา</div> </th> <th colspan="10" class="rotate" style="height: 0px;text-align: center;"> <div >ระดับผลการเรียน</div> </th> <th colspan="4" class="rotate" style="height: 0px;text-align: center;"> <div >คุณลักษณะฯ</div> </th> <th colspan="4" class="rotate" style="height: 0px;text-align: center;"> <div >อ่าน เขียน คิดฯ</div> </th> <th rowspan="2" class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >รวม</div> </th> </tr> <tr class="text-middle"> <th style="width: 4%;height: 0px;text-align: center;">4</th> <th style="width: 4%;height: 0px;text-align: center;">3.5</th> <th style="width: 4%;height: 0px;text-align: center;">3</th> <th style="width: 4%;height: 0px;text-align: center;">2.5</th> <th style="width: 4%;height: 0px;text-align: center;">2</th> <th style="width: 4%;height: 0px;text-align: center;">1.5</th> <th style="width: 4%;height: 0px;text-align: center;">1</th> <th style="width: 4%;height: 0px;text-align: center;">0</th> <th style="width: 4%;height: 0px;text-align: center;">ร</th> <th style="width: 4%;height: 0px;text-align: center;">มส</th> <th style="width: 4%;height: 0px;text-align: center;">3</th> <th style="width: 4%;height: 0px;text-align: center;">2</th> <th style="width: 4%;height: 0px;text-align: center;">1</th> <th style="width: 4%;height: 0px;text-align: center;">0</th> <th style="width: 4%;height: 0px;text-align: center;">3</th> <th style="width: 4%;height: 0px;text-align: center;">2</th> <th style="width: 4%;height: 0px;text-align: center;">1</th> <th style="width: 4%;height: 0px;text-align: center;">0</th> </tr> </thead> '; <file_sep>/modules/maneger_student/class_modules.php <?php class ClassData extends Databases { public function chk_id($std_ID,$card_ID){ $data_response = array(); $sql = "SELECT count(*) as num_std_ID FROM tbl_student WHERE std_ID='$std_ID' "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['num_std_ID']=unchkhtmlspecialchars($this->rows[0]['num_std_ID']); $sql = "SELECT count(*) as num_card_ID FROM tbl_student WHERE card_ID='$card_ID' "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['num_card_ID']=unchkhtmlspecialchars($this->rows[0]['num_card_ID']); return json_encode($data_response); } public function update_data($update,$arr_sql_class_room,$data_id){ $this->sql = "UPDATE tbl_student SET ".implode(",",$update)." WHERE std_ID='".$data_id."'"; $this->query(); $new_id = $this->insertID(); $this->sql = "UPDATE tbl_std_class_room SET ".implode(",",$arr_sql_class_room)." WHERE std_ID='".$data_id."'"; $this->query(); return json_encode($new_id); } public function get_extra_data($data_id){ $data_response = array(); $sql = "SELECT * FROM tbl_student WHERE std_ID='$data_id' "; $this->sql = $sql; $this->select(); $this->setRows(); $birthday=unchkhtmlspecialchars($this->rows[0]['birthday']); $time = strtotime($birthday); $day = date('d',$time); $month = date('m',$time); $year = date('Y',$time)+543; if ($month==1 || $month==3 || $month==5 || $month==7 || $month==8 || $month==10 || $month==12) { for ($i=1; $i <=31 ; $i++) { if ($day==$i) { $day_data.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $day_data.='<option value="'.$i.'">'.$i.'</option> '; } } }elseif($month==4 || $month==6 || $month==9 || $month==11){ for ($i=1; $i <=30 ; $i++) { if ($day==$i) { $day_data.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $day_data.='<option value="'.$i.'">'.$i.'</option> '; } } }else{ for ($i=1; $i <=29 ; $i++) { if ($day==$i) { $day_data.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $day_data.='<option value="'.$i.'">'.$i.'</option> '; } } } $data_response['day']=$day_data; $data_response['month']=$month; $data_response['year']=$year; return $data_response; } public function get_data_form($data_id,$new_data_id){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; if (isset($new_data_id) && $new_data_id!="") { $sql = "SELECT * FROM tbl_student WHERE std_ID='$new_data_id' "; $sql_class = "SELECT * FROM tbl_std_class_room WHERE std_ID='$new_data_id' AND year='$year_set' "; }else{ $sql = "SELECT * FROM tbl_student WHERE std_ID='$data_id' "; $sql_class = "SELECT * FROM tbl_std_class_room WHERE std_ID='$data_id' AND year='$year_set' "; } $this->sql = $sql; $this->select(); $this->setRows(); $data_response['std_ID']=unchkhtmlspecialchars($this->rows[0]['std_ID']); $data_response['card_ID']=unchkhtmlspecialchars($this->rows[0]['card_ID']); $data_response['name_title']=unchkhtmlspecialchars($this->rows[0]['name_title']); $data_response['fname']=unchkhtmlspecialchars($this->rows[0]['fname']); $data_response['lname']=unchkhtmlspecialchars($this->rows[0]['lname']); $data_response['blood_group']=unchkhtmlspecialchars($this->rows[0]['blood_group']); $data_response['address']=unchkhtmlspecialchars($this->rows[0]['address']); $data_response['parent_name_title']=unchkhtmlspecialchars($this->rows[0]['parent_name_title']); $data_response['parent_fname']=unchkhtmlspecialchars($this->rows[0]['parent_fname']); $data_response['parent_lname']=unchkhtmlspecialchars($this->rows[0]['parent_lname']); $data_response['tell']=unchkhtmlspecialchars($this->rows[0]['tell']); $data_response['parent_address']=unchkhtmlspecialchars($this->rows[0]['parent_address']); $data_response['status']=unchkhtmlspecialchars($this->rows[0]['status']); $this->sql = $sql_class; $this->select(); $this->setRows(); $data_response['class_level']=unchkhtmlspecialchars($this->rows[0]['class_level']); $data_response['room']=unchkhtmlspecialchars($this->rows[0]['room']); $data_response['status_alive']=unchkhtmlspecialchars($this->rows[0]['status']); return json_encode($data_response); } public function get_years(){ $data_response = array(); $years_now=intval(date("Y"));+ $years_now=$years_now+543; for ($i=$years_now; $i >= 2480 ; $i--) { $data_response['set_years'].='<option value="'.$i.'">'.$i.'</option>'; } echo json_encode($data_response); } public function get_day($mouth){ $data_response = array(); for ($i=1; $i <= 29 ; $i++) { $day_make_29.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 30 ; $i++) { $day_make_30.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 31 ; $i++) { $day_make_31.='<option value="'.$i.'">'.$i.'</option>'; } if ($mouth==1 || $mouth==3 || $mouth==5 || $mouth==7 || $mouth==8 || $mouth==10 || $mouth==12) { $data_response['day_set']=$day_make_31; }elseif($mouth==4 || $mouth==6 || $mouth==9 || $mouth==11){ $data_response['day_set']=$day_make_30; }else{ $data_response['day_set']=$day_make_29; } echo json_encode($data_response); } public function get_data_delete($data_val){ $arr_id = explode(",", $data_val); $num=0; for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="DELETE FROM tbl_student WHERE std_ID = '{$arr_id[$i]}'"; $this->query(); $num=$num+$i; } return $num; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function data_year_search_student($arr_search_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; $data_class_search = $arr_search_val['data_class_search']; $data_room_search = $arr_search_val['data_room_search']; $sql = "SELECT tbl_student.std_ID,tbl_student.name_title,tbl_student.fname,tbl_student.lname,tbl_std_class_room.class_level,tbl_std_class_room.room FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_std_class_room.year ='$year_set' AND tbl_std_class_room.status =1 AND tbl_std_class_room.class_level='$data_class_search' AND tbl_std_class_room.room='$data_room_search' ORDER BY tbl_std_class_room.class_level,tbl_std_class_room.room, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN tbl_student.std_ID THEN 4 END "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $std_ID= $value['std_ID']; $name_title_data= $value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname= $value['fname']; $lname= $value['lname']; $class_level_data= $value['class_level']; $class_level=$this->get_class_level($class_level_data); $room= $value['room']; $data_response['table_list'].=' <tr > <td style="text-align: center;">'.$std_ID.'</td> <td style="text-align: left;padding-left:7%;">'.$name_title.$fname.'</td> <td style="text-align: left;padding-left:7%;">'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> <a href="index.php?op=maneger_student-edit&id='.$std_ID.'"> <span class="glyphicon glyphicon-edit edit-icon-table" ari a-hidden="true" ></span> </a> </td> </tr> '; } if($data_response['table_list']==''){ $data_response['table_list']=''; } return json_encode($data_response); } public function get_data($arr_search_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year_set=$this->rows[0]['year']; $data_response = array(); $sql_condition = "tbl_student.std_ID is not null "; $name_id_search = $arr_search_val['name_id_search']; if (isset($name_id_search) && $name_id_search != "") { $sql_condition .= " AND ( tbl_student.std_ID LIKE '%{$name_id_search}%') AND tbl_student.std_ID IN( SELECT std_ID FROM tbl_std_class_room WHERE year='$year_set' AND status=1 ) OR ( tbl_student.fname LIKE '%{$name_id_search}%') AND tbl_student.std_ID IN( SELECT std_ID FROM tbl_std_class_room WHERE year='$year_set' AND status=1 ) OR ( tbl_student.lname LIKE '%{$name_id_search}%') AND tbl_student.std_ID IN( SELECT std_ID FROM tbl_std_class_room WHERE year='$year_set' AND status=1 ) "; }else{ $sql_condition .= " AND tbl_student.std_ID IN( SELECT std_ID FROM tbl_std_class_room WHERE year='$year_set' AND status=1 ) "; } $sql = "SELECT count(*) as num_row_count FROM tbl_student WHERE $sql_condition "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row_count=$this->rows[0]['num_row_count']; $sql = " SELECT tbl_student.std_ID,tbl_student.name_title,tbl_student.fname,tbl_student.lname,tbl_std_class_room.class_level,tbl_std_class_room.room FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND $sql_condition ORDER BY tbl_std_class_room.class_level,tbl_std_class_room.room, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN tbl_student.std_ID THEN 4 END "; $this->sql = $sql; $this->select(); $this->setRows(); if ($num_row_count!=0) { foreach($this->rows as $key => $value) { $std_ID= $value['std_ID']; $name_title_data= $value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname= $value['fname']; $lname= $value['lname']; $class_level_data= $value['class_level']; $class_level=$this->get_class_level($class_level_data); $room= $value['room']; $data_response['table_list'].=' <tr > <td style="text-align: center;">'.$std_ID.'</td> <td style="text-align: left;padding-left:7%;">'.$name_title.$fname.'</td> <td style="text-align: left;padding-left:7%;">'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> <a href="index.php?op=maneger_student-edit&id='.$std_ID.'"> <span class="glyphicon glyphicon glyphicon-edit edit-icon-table" ari a-hidden="true" ></span> </a> </td> </tr> '; } }else{ $data_response['table_list'].=''; } return json_encode($data_response); } }<file_sep>/modules/up_class/class_modules.php <?php class ClassData extends Databases { public function reverse_upclass($data_year_old,$data_year_new,$log_upclass_id){ $this->sql = "DELETE FROM tbl_std_class_room WHERE year='$data_year_new'"; $this->query(); $this->sql = "UPDATE tbl_std_class_room SET status=1 WHERE year='$data_year_old' AND status=0 AND class_level='p1' OR class_level='p2' OR class_level='p3' OR class_level='p4' OR class_level='p5' OR class_level='m1' OR class_level='m2' OR class_level='m4' OR class_level='m5'"; $this->query(); $this->sql = "DELETE FROM tbl_log_upclass WHERE DataID=$log_upclass_id"; $this->query(); return json_encode($log_upclass_id); } public function insert_log_upclass($std_year_new,$std_year_old){ $user_add=$_SESSION['ss_user_id']; $c_date=date("Y-m-d"); $this->sql = "INSERT INTO tbl_log_upclass(user_add,c_date,std_year_old,std_year_new) VALUES($user_add,'$c_date','$std_year_old','$std_year_new')"; $this->query(); } public function chk_before_status($std_ID,$set_class_before){ $data_response = array(); $sql = "SELECT COUNT(*) AS num_row FROM tbl_std_class_room WHERE std_ID=$std_ID AND class_level='$set_class_before' AND status=0 "; $this->sql = $sql; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function up_class_p($i){ $set_class_p_number=$i-1; $set_class_p_number_before=$i-2; $set_class_p_find='p'.$set_class_p_number; $set_class_p_new='p'.$i; $set_class_p_before='p'.$set_class_p_number_before; $this->sql ="SELECT tbl_std_class_room.DataID as std_class_room_id, tbl_student.std_ID,tbl_std_class_room.room,tbl_std_class_room.year FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_std_class_room.status=1 AND tbl_std_class_room.class_level='$set_class_p_find' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $std_class_room_id= $value['std_class_room_id']; $std_ID= $value['std_ID']; $class_level=$set_class_p; $room= $value['room']; $year= $value['year']; $set_year=$year+1; $this->sql = "INSERT INTO tbl_std_class_room(std_ID,class_level,room,year,status) VALUES('$std_ID','$set_class_p_new','$room','$set_year',99)"; $this->query(); $this->sql = "UPDATE tbl_std_class_room SET status=0 WHERE DataID=$std_class_room_id"; $this->query(); } if ($i==1) { $this->sql = "UPDATE tbl_std_class_room SET status=1 WHERE status=99"; $this->query(); $this->insert_log_upclass($set_year,$year); } return json_encode(1); } public function up_class_m($i){ $set_class_m_number=$i-1; $set_class_m_number_before=$i-2; $set_class_m_find='m'.$set_class_m_number; $set_class_m_new='m'.$i; $set_class_m_before='m'.$set_class_m_number_before; $this->sql ="SELECT tbl_std_class_room.DataID as std_class_room_id, tbl_student.std_ID,tbl_std_class_room.room,tbl_std_class_room.year FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_std_class_room.status=1 AND tbl_std_class_room.class_level='$set_class_m_find' "; $this->select(); $this->setRows(); $num_row_set=0; foreach($this->rows as $key => $value) { $std_class_room_id= $value['std_class_room_id']; $std_ID= $value['std_ID']; $class_level=$set_class_m; $room= $value['room']; $year= intval($value['year']); $set_year=$year+1; $this->sql = "INSERT INTO tbl_std_class_room(std_ID,class_level,room,year,status) VALUES('$std_ID','$set_class_m_new','$room','$set_year',99)"; $this->query(); $this->sql = "UPDATE tbl_std_class_room SET status=0 WHERE DataID=$std_class_room_id"; $this->query(); $num_row_set++; } if ($i==6) { $this->sql = "UPDATE tbl_std_class_room SET status=1 WHERE status=99"; $this->query(); } return json_encode(1); } public function data_upclassed(){ $data_response = array(); $sql = "SELECT * FROM tbl_log_upclass ORDER BY std_year_new DESC "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $user_add_set= $value['user_add']; $c_date_set= $value['c_date']; $old_form_date = strtotime($c_date_set); $c_date=date('d/m/Y', $old_form_date); $std_year_old= $value['std_year_old']; $std_year_new= $value['std_year_new']; $user_add=$this->get_user_add($user_add_set); if ($key==0) { $btn_reverse=' <img class="edit-icon-table btn_reverse" data-id="'.$DataID.'" data-text="'.$std_year_new.' เป็น '.$std_year_old.'" data-year-old="'.$std_year_old.'" data-year-new="'.$std_year_new.'" style="width:16px;margin:0 auto;" src="assets/images/glyphicons-366-restart.png" data-toggle="modal" data-target="#modalReverse"> '; }else{ $btn_reverse=''; } $data_response.=' <tr> <td style="text-align: center;"> จาก '.$std_year_old.' เป็น '.$std_year_new.' </td> <td style="text-align: center;">'.$user_add.'</td> <td style="text-align: center;">'.$c_date.'</td> <td style="text-align: center;"> '.$btn_reverse.' </td> </tr> '; } echo json_encode($data_response); } public function get_user_add($user_id){ $data_response = array(); $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID=$user_id "; $this->sql = $sql; $this->select(); $this->setRows(); $fname_th=$this->rows[0]['fname_th']; $lname_th=$this->rows[0]['lname_th']; return $fname_th.' '.$lname_th; } public function get_year(){ $data_response = array(); $sql = " SELECT DISTINCT(year) AS year FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_std_class_room.status=1 AND tbl_std_class_room.class_level='p1' OR tbl_std_class_room.class_level='p2' OR tbl_std_class_room.class_level='p3' OR tbl_std_class_room.class_level='p4' OR tbl_std_class_room.class_level='m1' OR tbl_std_class_room.class_level='m2' OR tbl_std_class_room.class_level='m4' OR tbl_std_class_room.class_level='m5' "; $this->sql = $sql; $this->select(); $this->setRows(); $year=$this->rows[0]['year']; echo json_encode($year); } public function data_year_search_student($data_class_search){ $data_response = array(); $this->sql ="SELECT year FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year=$this->rows[0]['year']; $sql = "SELECT count(*) as num_row_count FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND class_level='$data_class_search' ) "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row_count=$this->rows[0]['num_row_count']; $sql = " SELECT tbl_student.std_ID,tbl_student.name_title,tbl_student.fname,tbl_student.lname,tbl_std_class_room.room FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_std_class_room.status=1 AND tbl_std_class_room.class_level='$data_class_search' ORDER BY tbl_std_class_room.class_level,tbl_std_class_room.room, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN tbl_student.std_ID THEN 4 END "; $this->sql = $sql; $this->select(); $this->setRows(); if ($num_row_count!=0) { foreach($this->rows as $key => $value) { $std_ID= $value['std_ID']; $name_title_data= $value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname= $value['fname']; $lname= $value['lname']; $class_level=$this->get_class_level($data_class_search); $room= $value['room']; $data_response['table_list'].=' <tr > <td style="text-align: center;">'.$std_ID.'</td> <td style="text-align: left;padding-left:7%;">'.$name_title.$fname.'</td> <td style="text-align: left;padding-left:7%;">'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> '.$year.' </td> </tr> '; } }else{ $data_response['table_list'].=''; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/save_score/class_modules.php <?php class ClassData extends Databases { public function get_end_data_find($start_data,$end_data){ $end_data_last=$end_data+1; return $end_data_last-$start_data; } public function set_col_header($length_list_val){ $data_response = array(); list($start_data,$end_data) = split('[-]', $length_list_val); $data_response['end_data_find']=$this->get_end_data_find($start_data,$end_data); return json_encode($data_response); } public function get_score_col_total($std_ID,$registed_courseID,$set_status){ if($set_status=='before'){ $condition='WHERE proportion_status=1'; }elseif($set_status=='after'){ $condition='WHERE proportion_status=2'; } $num_of_i=0; $this->sql ="SELECT count(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1 AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude $condition ) "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND objectiveID IN( SELECT DataID FROM tbl_objective_conclude $condition ) "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($score_total_data==0) { $score_total=0; }else{ $score_total=$score_total_data; } return $score_total+$num_of_i; } public function get_total_proportion($data_id){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$data_id "; $this->select(); $this->setRows(); $data_response['mid_exam'] =$this->rows[0]['mid_exam']; $data_response['final_exam'] =$this->rows[0]['final_exam']; return $data_response; } public function get_total_ob_conclude($data_objective_ob){ $this->sql ="SELECT score FROM tbl_objective_conclude WHERE DataID=$data_objective_ob "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_score_col($std_ID,$data_objective,$registed_courseID,$start_data,$no_std){ $arr_id = explode("-", $data_objective); $no_order_ext=1; for ($i=0; $i < count($arr_id) ; $i++) { if ($arr_id[$i]=='') { $arr_id[$i]=0; }else{ $arr_id[$i]=$arr_id[$i]; } $total_ob_conclude=$this->get_total_ob_conclude($arr_id[$i]); $this->sql ="SELECT no_order FROM tbl_objective_conclude WHERE DataID={$arr_id[$i]} "; $this->select(); $this->setRows(); $no_order=$this->rows[0]['no_order']; $this->sql ="SELECT * FROM tbl_objective_score_std WHERE staID='$std_ID' AND objectiveID={$arr_id[$i]} AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $score=0; }else{ if ($score==-1) { $score='ร'; }else{ $score=$score; } } $data_response.='<td class="relative" ><input style="text-align: center;" onkeyup="chk_score_over(this,this.value)" class_name_change="'.$DataID.'" value_set="'.$score.'" data_main_chk_over="'.$total_ob_conclude.'" name="objective_score_std[]" disabled="disabled" class="select-table-form class_col_set_new class_name_'.$DataID.' class_col_'.$no_order_ext.$no_order.'" type="text" value="'.$score.'"></td>'; $start_data++; $no_order_ext++; } return $data_response; } public function get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$start_data,$room_search,$set_status,$term_set,$year_set){ if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); $score_col=$this->get_score_col($std_ID,$data_objective,$registed_courseID,$start_data,$no_std); $score_col_total=$this->get_score_col_total($std_ID,$registed_courseID,$set_status); $data_response.='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:4%;">'.$name_title.$fname.' '.$lname.'</td> '.$score_col.' <td>'.$score_col_total.'</td> </tr> '; $no_std++; } return $data_response; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data='p'; }else{ $data='m'; } return $data; } public function get_std_id_all($coures_id_list_val,$room_search,$term_set,$year_set){ if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; if ($num_row_std==$no_std) { $std_id_all.=$std_ID; }else{ $std_id_all.=$std_ID.'-'; } $no_std++; } $data_response=$std_id_all; return $data_response; } public function get_proportion_cumulative($coures_id_list_val,$set_status){ switch ($set_status) { case 'before': $sql_con="cumulative_before_mid"; break; case 'after': $sql_con="cumulative_after_mid"; break; default: $sql_co="courseID"; break; } $this->sql ="SELECT $sql_con as cumulative_sum FROM tbl_proportion WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); return $this->rows[0]['cumulative_sum']; } public function get_objective_list_admin($coures_id_list_val,$length_list_val,$room_search,$legth_score,$term_data,$year_data){ $data_response = array(); //$data_response['proportion_cumulative']=$this->get_proportion_cumulative($coures_id_list_val); list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start; if($legth_score=='save-score-pick-before'){ $condition="proportion_status=1"; $set_status='before'; }elseif($legth_score=='save-score-pick-after'){ $condition="proportion_status=2"; $set_status='after'; } $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val AND $condition ORDER BY no_order LIMIT $find_start,$find_end "; $this->select(); $this->setRows(); $chk_loop=1; $no_order_ext=1; foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $no_order=$value['no_order']; $score=$value['score']; $data_response['objective_list'].=' <option value="'.$no_order_ext.$no_order.'">ข้อที่ '.$no_order.'</option>'; $data_response['ob_title_table_col'].='<td>'.$no_order.'</td>'; $data_response['ob_score_max_table_col'].='<td>'.$score.'</td>'; if ($find_end==$chk_loop) { $data_objective.=$DataID; }else{ $data_objective.=$DataID.'-'; } $chk_loop++; $no_order_ext++; } $data_response['ob_score_max_table_col'].='<td style="background-color:#f3e7f9;">'.$this->get_proportion_cumulative($coures_id_list_val,$set_status).'</td>'; $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_data,$year_data); $data_response['registed_courseID']=$registed_courseID; $data_response['detail_std']=$this->get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$start_data,$room_search,$set_status,$term_data,$year_data); $data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search,$term_data,$year_data); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_objective_list($coures_id_list_val,$length_list_val,$room_search,$legth_score){ $data_response = array(); //$data_response['proportion_cumulative']=$this->get_proportion_cumulative($coures_id_list_val); list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start; if($legth_score=='save-score-pick-before'){ $condition="proportion_status=1"; $set_status='before'; }elseif($legth_score=='save-score-pick-after'){ $condition="proportion_status=2"; $set_status='after'; } $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val AND $condition ORDER BY no_order LIMIT $find_start,$find_end "; $this->select(); $this->setRows(); $chk_loop=1; $no_order_ext=1; foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $no_order=$value['no_order']; $score=$value['score']; $data_response['objective_list'].=' <option value="'.$no_order_ext.$no_order.'">ข้อที่ '.$no_order.'</option>'; $data_response['ob_title_table_col'].='<td>'.$no_order.'</td>'; $data_response['ob_score_max_table_col'].='<td>'.$score.'</td>'; if ($find_end==$chk_loop) { $data_objective.=$DataID; }else{ $data_objective.=$DataID.'-'; } $chk_loop++; $no_order_ext++; } $data_response['ob_score_max_table_col'].='<td style="background-color:#f3e7f9;">'.$this->get_proportion_cumulative($coures_id_list_val,$set_status).'</td>'; $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $data_response['registed_courseID']=$registed_courseID; $data_response['detail_std']=$this->get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$start_data,$room_search,$set_status); $data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_registed_courseID($coures_id_list_val,$term_set,$year_set){ if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_config($legth_score,$coures_id_list_val,$room_search,$term_data,$year_data){ $data_response = array(); if ($legth_score=="save-score-pick-before") { $data_response=$this->get_pick($coures_id_list_val,'before'); }elseif($legth_score=="save-score-pick-after"){ $data_response=$this->get_pick($coures_id_list_val,'after'); }elseif($legth_score=="save-score-exam"){ $data_response=$this->get_exam($coures_id_list_val,$room_search,$term_data,$year_data); }elseif($legth_score=="save-score-desirable"){ $data_response=$this->get_desirable($coures_id_list_val,$room_search,$term_data,$year_data); }elseif($legth_score=="save-score-read"){ $data_response=$this->get_read($coures_id_list_val,$room_search,$term_data,$year_data); } return json_encode($data_response); } public function get_selected($num_loop_class){ if (isset($_SESSION['status_active'])) { $active_length=$_SESSION['status_active']; $text='chk_active_'.$num_loop_class; if($active_length==$text){ return "selected"; } } } public function search_course_detail($coures_id_list,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level']=$class_level_data; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($status==1) { $data_response['unit']=$this->rows[0]['unit']; $data_response['class_level_co']=$class_level.'/'.$room_search; }elseif($status==2){ if ($status_form==25 || $status_form==26 || $status_form==27) { $data_response['class_level_co']=$class_level.'/'.$room_search; }else{ $data_response['class_level_co']=$class_level; } $data_response['unit']='-'; } return json_encode($data_response); } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; $data_response['status']=$status; $data_response['status_form']=$status_form; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6') { $term_set='1,2'; } $user_status=$_SESSION['ss_status']; $user_id=$_SESSION['ss_user_id']; if ($user_status==1) { $this->sql ="SELECT room FROM tbl_room_teacher WHERE course_teacherID in( SELECT DataID FROM tbl_course_teacher WHERE teacher_id=$user_id AND regis_course_id in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; }else{ $this->sql =" SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT std_ID FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ) ORDER BY room ASC "; } $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $chk_room_export=$this->get_chk_room_export($room,$term_set,$year_set,$coures_id_list_val); if ($chk_room_export==0) { $data_response['room'].=' <option>'.$room.'</option>'; } } return json_encode($data_response); } public function get_class_level_admin($coures_id_list_val,$term_set,$year_set){ $data_response = array(); $this->sql ="SELECT class_level,status,status_form FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; $data_response['status']=$status; $data_response['status_form']=$this->rows[0]['status_form']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($status==2){ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql="SELECT distinct room FROM tbl_room_export WHERE status=1 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND courseID=$coures_id_list_val ) ORDER BY room ASC "; $this->sql=$sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } }else{ $this->sql ="SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } } }else{ $sql="SELECT distinct room FROM tbl_room_export WHERE status=1 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND courseID=$coures_id_list_val ) ORDER BY room ASC "; $this->sql=$sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } } return json_encode($data_response); } public function get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } /*$this->sql ="SELECT COUNT(*) as num_row FROM tbl_registed_course,tbl_room_export WHERE tbl_registed_course.DataID=tbl_room_export.registed_courseID AND tbl_registed_course.courseID=$DataID AND tbl_registed_course.term='$term_set' AND tbl_registed_course.year='$year_set' AND tbl_room_export.sended_status=99 ";*/ $this->sql ="SELECT COUNT(*) as num_row_not_in FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' AND DataID not in( SELECT registed_courseID FROM tbl_room_export ) "; $this->select(); $this->setRows(); $num_row_not_in=$this->rows[0]['num_row_not_in']; $this->sql ="SELECT COUNT(*) as num_row_in_99 FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export WHERE sended_status=99 ) "; $this->select(); $this->setRows(); $num_row_in_99=$this->rows[0]['num_row_in_99']; if ($num_row_not_in>0 && $num_row_in_99==0) {//no have both in room export $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; }elseif($num_row_not_in==0){//have in room export $this->sql ="SELECT COUNT(*) as num_row_not_99 FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export WHERE sended_status!=99 ) "; $this->select(); $this->setRows(); $num_row_not_99=$this->rows[0]['num_row_not_99']; if ($num_row_in_99>0 && $num_row_not_99==0) {//have only 99 in room export $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; }elseif($num_row_not_99>0){//have only another in room export $this->sql =" SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT std_ID FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); $set_amount=0; $room_amount=0; foreach($this->rows as $key => $value) { $room=$value['room']; $chk_room_export=$this->get_chk_room_export($room,$term_set,$year_set,$DataID); if ($chk_room_export==1) { $set_amount++; } $room_amount++; } if ($set_amount<$room_amount) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; } } } return $data_response; } public function get_chk_room_export($room,$term_set,$year_set,$courseID){ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_room_export WHERE room=$room AND sended_status!=99 AND registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_data_dicision_admin($DataID,$courseID_long,$class_level,$status,$term_set,$year_set){ $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_room_export WHERE status=1 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND courseID=$DataID ) "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; } return $data_response; } public function get_coures_id_list_admin($term_set,$year_set){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; $data_dicision=$this->get_data_dicision_admin($DataID,$courseID_long,$class_level,$status,$term_set,$year_set); $data_response['coures_id_list'].=$data_dicision; } if ($data_response['coures_id_list']=='') { $data_response['coures_id_list']='<option value="">ไม่พบรายวิชา</option>'; } return json_encode($data_response); } public function get_coures_id_list(){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) AND DataID in( SELECT regis_course_id FROM tbl_course_teacher WHERE teacher_id=$user_id ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; $data_dicision=$this->get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set); $data_response['coures_id_list'].=$data_dicision; } echo json_encode($data_response); } public function get_course_teachingID($DataID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_propotion_total($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val"; $this->select(); $this->setRows(); $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; $data_response['total']=$mid_exam+$final_exam; return $data_response; } public function get_std_exam($coures_id_list_val,$course_teachingID,$room_search,$term_set,$year_set){ $total_total_proportion=$this->get_total_proportion($coures_id_list_val); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_mid_exam=$this->get_score_mid_exam($std_ID,$course_teachingID); $score_final_exam=$this->get_score_final_exam($std_ID,$course_teachingID); $score_total=$score_mid_exam['score']+$score_final_exam['score']; $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_exam.=$std_ID; }else{ $std_id_all_exam.=$std_ID.'-'; } $data_response.=' <tr> <td>'.$num_set.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:10%;">'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input onkeyup="chk_score_over(this,this.value)" class_name_change="1'.$score_mid_exam['DataID'].'" data_main_chk_over="'.$total_total_proportion['mid_exam'].'" value_set="'.$score_mid_exam['score'].'" name="score_mid_exam[]" disabled="disabled" class="class_name_1'.$score_mid_exam['DataID'].' select-table-form value_score_mid class_col_set_new_edit class_col_exam_mid text-center" type="text" value="'.$score_mid_exam['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over(this,this.value)" class_name_change="2'.$score_final_exam['DataID'].'" data_main_chk_over="'.$total_total_proportion['final_exam'].'" value_set="'.$score_final_exam['score'].'" name="score_final_exam[]" disabled="disabled" class="class_name_2'.$score_final_exam['DataID'].' select-table-form value_score_final class_col_set_new_edit class_col_exam_final text-center" type="text" value="'.$score_final_exam['score'].'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_exam" type="text" hidden="hidden" value="'.$std_id_all_exam.'" name="">'; return $data_response; } public function get_score_final_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_score_mid_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_score_desirable_1($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_1 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_2($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_2 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_3($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_3 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_4 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_5 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_6($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_6 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_7($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_7 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_8($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_8 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_room_std($std_ID,$year_set){ $data_response = array(); $this->sql ="SELECT room FROM tbl_std_class_room WHERE std_ID='$std_ID' AND year=$year_set "; $this->select(); $this->setRows(); $room=$this->rows[0]['room']; return $room; } public function get_std_desirable($coures_id_list_val,$course_teachingID,$room_search,$status,$status_form,$class_level,$term_set,$year_set){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } if ($status==1) { $sql_condition=" WHERE room='$room_search' AND "; $sql_condition_join=" AND tbl_std_class_room.room='$room_search' AND tbl_std_class_room.status=1 "; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition=" WHERE room='$room_search' AND "; $sql_condition_join=" AND tbl_std_class_room.room='$room_search' AND tbl_std_class_room.status=1 "; }else{ $sql_condition=" WHERE "; $sql_condition_join="AND tbl_std_class_room.status=1 "; } } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room $sql_condition year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student,tbl_course_teaching_std,tbl_std_class_room,tbl_registed_course WHERE tbl_student.std_ID=tbl_course_teaching_std.stdID AND tbl_course_teaching_std.stdID=tbl_std_class_room.std_ID AND tbl_course_teaching_std.registed_courseID=tbl_registed_course.DataID AND tbl_registed_course.courseID=$coures_id_list_val AND tbl_registed_course.term='$term_set' AND tbl_registed_course.year='$year_set' AND tbl_std_class_room.year='$year_set' $sql_condition_join ORDER BY tbl_std_class_room.room, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN tbl_student.std_ID THEN 4 END "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_desirable_1=$this->get_score_desirable_1($std_ID,$course_teachingID); $score_desirable_2=$this->get_score_desirable_2($std_ID,$course_teachingID); $score_desirable_3=$this->get_score_desirable_3($std_ID,$course_teachingID); $score_desirable_4=$this->get_score_desirable_4($std_ID,$course_teachingID); $score_desirable_5=$this->get_score_desirable_5($std_ID,$course_teachingID); $score_desirable_6=$this->get_score_desirable_6($std_ID,$course_teachingID); $score_desirable_7=$this->get_score_desirable_7($std_ID,$course_teachingID); $score_desirable_8=$this->get_score_desirable_8($std_ID,$course_teachingID); $score_total=round(($score_desirable_1['score']+$score_desirable_2['score']+$score_desirable_3['score']+$score_desirable_4['score']+$score_desirable_5['score']+$score_desirable_6['score']+$score_desirable_7['score']+$score_desirable_8['score'])/8,2); $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_desirable.=$std_ID; }else{ $std_id_all_desirable.=$std_ID.'-'; } if ($status_form!=25 && $status_form!=26 && $status_form!=27) { $room_std=$this->get_room_std($std_ID,$year_set); $room_row='<td>'.$room_std.'</td>'; } $data_response.=' <tr> <td>'.$num_set.'</td> <td>'.$std_ID.'</td> '.$room_row.' <td style="text-align:left;padding-left:4%;">'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input name="score_final_desirable_1[]" value_set="'.$score_desirable_1['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="1'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_1'.$score_desirable_1['DataID'].' select-table-form value_score_desirable_1 class_col_set_new_edit class_col_desirable_1 text-center" type="text" value="'.$score_desirable_1['score'].'"></td> <td class="relative"><input name="score_final_desirable_2[]" value_set="'.$score_desirable_2['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="2'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_2'.$score_desirable_2['DataID'].' select-table-form value_score_desirable_2 class_col_set_new_edit class_col_desirable_2 text-center" type="text" value="'.$score_desirable_2['score'].'"></td> <td class="relative"><input name="score_final_desirable_3[]" value_set="'.$score_desirable_3['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="3'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_3'.$score_desirable_3['DataID'].' select-table-form value_score_desirable_3 class_col_set_new_edit class_col_desirable_3 text-center" type="text" value="'.$score_desirable_3['score'].'"></td> <td class="relative"><input name="score_final_desirable_4[]" value_set="'.$score_desirable_4['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="4'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_4'.$score_desirable_4['DataID'].' select-table-form value_score_desirable_4 class_col_set_new_edit class_col_desirable_4 text-center" type="text" value="'.$score_desirable_4['score'].'"></td> <td class="relative"><input name="score_final_desirable_5[]" value_set="'.$score_desirable_5['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="5'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_5'.$score_desirable_1['DataID'].' select-table-form value_score_desirable_5 class_col_set_new_edit class_col_desirable_5 text-center" type="text" value="'.$score_desirable_5['score'].'"></td> <td class="relative"><input name="score_final_desirable_6[]" value_set="'.$score_desirable_6['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="6'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_6'.$score_desirable_6['DataID'].' select-table-form value_score_desirable_6 class_col_set_new_edit class_col_desirable_6 text-center" type="text" value="'.$score_desirable_6['score'].'"></td> <td class="relative"><input name="score_final_desirable_7[]" value_set="'.$score_desirable_7['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="7'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_7'.$score_desirable_7['DataID'].' select-table-form value_score_desirable_7 class_col_set_new_edit class_col_desirable_7 text-center" type="text" value="'.$score_desirable_7['score'].'"></td> <td class="relative"><input name="score_final_desirable_8[]" value_set="'.$score_desirable_8['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="8'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_8'.$score_desirable_8['DataID'].' select-table-form value_score_desirable_8 class_col_set_new_edit class_col_desirable_8 text-center" type="text" value="'.$score_desirable_8['score'].'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_desirable" type="text" hidden="hidden" value="'.$std_id_all_desirable.'" name="">'; return $data_response; } public function get_score_read($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_read_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_write($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_write_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_think($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_think_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_rtw_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_rtw_4_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_rtw_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_rtw_5_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_std_read($coures_id_list_val,$course_teachingID,$room_search,$status,$status_form,$class_level,$term_set,$year_set){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } if ($status==1) { $sql_condition=" WHERE room='$room_search' AND "; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition=" WHERE room='$room_search' AND "; }else{ $sql_condition=" WHERE "; } } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room $sql_condition year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE std_ID in( SELECT std_ID FROM tbl_std_class_room $sql_condition year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $get_score_read=$this->get_score_read($std_ID,$course_teachingID); $get_score_write=$this->get_score_write($std_ID,$course_teachingID); $get_score_think=$this->get_score_think($std_ID,$course_teachingID); $get_score_rtw_4=$this->get_score_rtw_4($std_ID,$course_teachingID); $get_score_rtw_5=$this->get_score_rtw_5($std_ID,$course_teachingID); $score_total=round(($get_score_read['score']+$get_score_write['score']+$get_score_think['score']+$get_score_rtw_4['score']+$get_score_rtw_5['score'])/5,2); $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_read.=$std_ID; }else{ $std_id_all_read.=$std_ID.'-'; } $data_response.=' <tr> <td>'.$num_set.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:10%;">'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_read['score'].'" class_name_change="1'.$get_score_read['DataID'].'" name="score_read[]" disabled="disabled" class="class_name_1'.$get_score_read['DataID'].' select-table-form value_score_read class_col_set_new_edit class_col_read text-center" type="text" value="'.$get_score_read['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_write['score'].'" class_name_change="2'.$get_score_write['DataID'].'" name="score_write[]" disabled="disabled" class="class_name_2'.$get_score_write['DataID'].' select-table-form value_score_write class_col_set_new_edit class_col_write text-center" type="text" value="'.$get_score_write['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_think['score'].'" class_name_change="3'.$get_score_think['DataID'].'" name="score_think[]" disabled="disabled" class="class_name_3'.$get_score_think['DataID'].' select-table-form value_score_think class_col_set_new_edit class_col_think text-center" type="text" value="'.$get_score_think['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_rtw_4['score'].'" class_name_change="4'.$get_score_rtw_4['DataID'].'" name="score_rtw_4[]" disabled="disabled" class="class_name_4'.$get_score_rtw_4['DataID'].' select-table-form value_score_rtw_4 class_col_set_new_edit class_col_rtw_4 text-center" type="text" value="'.$get_score_rtw_4['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_rtw_5['score'].'" class_name_change="5'.$get_score_rtw_5['DataID'].'" name="score_rtw_5[]" disabled="disabled" class="class_name_5'.$get_score_rtw_5['DataID'].' select-table-form value_score_rtw_5 class_col_set_new_edit class_col_rtw_5 text-center" type="text" value="'.$get_score_rtw_5['score'].'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_read" type="text" hidden="hidden" value="'.$std_id_all_read.'" name="">'; return $data_response; } public function get_read($coures_id_list_val,$room_search,$term_set,$year_set){ $data_response = array(); if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 1</td> <td>สามารถอ่านและหาประสบการณ์จากสื่อที่หลากหลาย</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 2</td> <td>สามารถจับประเด็นสำคัญ ข้อเท็จจริง ความคิดเห็นเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 3</td> <td>สามารถเปรียบเทียบแง่มุมต่างๆ เช่น ข้อดี ข้อเสีย ประโยชน์ โทษ ความเหมาะสม ไม่เหมาะสม</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 4</td> <td>สามารถแสดงความคิดเห็นต่อเรื่องที่อ่าน โดยมีเหตุผลประกอบ</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 5</td> <td>สามารถถ่ายทอดความคิดเห็นความรู้สึกจากเรื่องที่อ่านโดยการเขียน</td> </tr> '; }elseif($class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 1</td> <td>สามารถอ่านเพื่อหาข้อมูลสารสนเทศเสริมประสบการณ์จากสื่อประเภทต่างๆ</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 2</td> <td>สามารถจับประเด็นสำคัญ เปรียบเทียบ เชื่อมโยงความเป็นเหตุเป็นผลจากเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 3</td> <td>สามารถเชื่อมโยงความสัมพันธ์ของเรื่องราว เหตุการณ์ของเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 4</td> <td>สามารถแสดงความคิดเห็นต่อเรื่องที่อ่านโดยมีเหตุผลสนับสนุน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 5</td> <td>สามารถถ่ายทอดความเข้าใจ ความคิดเห็น คุณค่าจากเรื่องที่อ่านโดยการเขียน</td> </tr> '; }elseif($class_level=='m1' || $class_level=='m2' || $class_level=='m3') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 1</td> <td >สามารถคัดสรรสื่อที่ต้องการอ่านเพื่อหาข้อมูลสารสนเทศได้ตามวัตถุประสงค์ สามารถสร้างความเข้าใจและประยุกต์ใช้ความรู้จากการอ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 2</td> <td>สามารถจับประเด็นสำคัญและประเด็นสนับสนุน โต้แย้ง</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 3</td> <td>สามารถวิเคราะห์ วิจารณ์ ความสมเหตุสมผล ความน่าเชื่อถือ ลำดับความและความเป็นไปได้ของเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 4</td> <td>สามารถสรุปคุณค่า แนวคิด แง่คิดที่ได้จากการอ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 5</td> <td>สามารถสรุป อภิปราย ขยายความ แสดงความคิดเห็น โต้แย้ง สนับสนุน โน้มน้าว โดยการเขียนสื่อสารในรูปแบบต่าง ๆ เช่น ผังความคิด เป็นต้น</td> </tr> '; }elseif($class_level=='m4' || $class_level=='m5' || $class_level=='m6') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 1</td> <td>สามารถอ่านเพื่อการศึกษาค้นคว้า เพิ่มพูนความรู้ ประสบการณ์ และการประยุกต์ใช้ในชีวิตประจำวัน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 2</td> <td>สามารถจับประเด็นสำคัญลำดับเหตุการณ์จากการอ่านสื่อที่มีความซับซ้อน</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 3</td> <td>สามารถวิเคราะห์สิ่งที่ผู้เขียนต้องการสื่อสารกับผู้อ่าน และสามารถวิพากษ์ ให้ข้อเสนอแนะในแง่มุมต่าง ๆ</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 4</td> <td>สามารถประเมินความน่าเชื่อถือ คุณค่า แนวคิดที่ได้จากสิ่งที่อ่านอย่างหลากหลาย</td> </tr> <tr> <td width="110px" style="vertical-align: top;">ตัวชี้วัดที่ 5</td> <td>สามารถเขียนแสดงความคิดเห็นโต้แย้ง สรุป โดยมีข้อมูลอธิบายสนับสนุนอย่างเพียงพอและสมเหตุสมผล</td> </tr> '; } $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $std_read=$this->get_std_read($coures_id_list_val,$course_teachingID,$room_search,$status,$status_form,$class_level,$term_set,$year_set); $data_response=' <input id="teaching_id_find" type="text" hidden="hidden" name="" value='.$course_teachingID.'> <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div class="row pd-50 stage-set" > <div class="col-sm-12 col-xs-12 mt-nega-20"> <div class="set-line"> <p class="text-bold text-inline">คะแนนอ่าน คิดวิเคราะห์ และเขียน</p> </div> </div> </div> <div class="ml-36 mr-50 mt-nega-50" > <div class="col-sm-12 col-xs-12"> <div class="set-line"> <p class="text-inline">คะแนน</p> <select onchange="open_edit_read()" id="read_select" name="read_select" class="form-control search-drop-sub-id mr-30"> <option value="read">ตัวชี้วัดที่ 1</option> <option value="write">ตัวชี้วัดที่ 2</option> <option value="think">ตัวชี้วัดที่ 3</option> <option value="rtw_4">ตัวชี้วัดที่ 4</option> <option value="rtw_5">ตัวชี้วัดที่ 5</option> </select> <p class=" text-inline" >ระบุคะแนนทั้งหมดเป็น</p> <div class="input-group form-serch-width-small"> <input id="input_set_data_seem_read" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> <div class="btn-search-save-score"> <div id="btn_set_data_seem_read" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </div> </div> </div> <div class=" ml-50 mr-50 mt-30" > <div class="row"> <div class="col-md-12"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "4" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "4" width="8%" style=" vertical-align: middle;">รหัส</td> <td rowspan = "4" width="40%" style=" vertical-align: middle;">ชื่อ-สกุล</td> </tr> <tr> <td colspan="10">คะแนนอ่าน คิดวิเคราะห์ และเขียน</td> </tr> <tr> <td width="120px">ตัวชี้วัดที่ 1</td> <td width="120px">ตัวชี้วัดที่ 2</td> <td width="120px">ตัวชี้วัดที่ 3</td> <td width="120px">ตัวชี้วัดที่ 4</td> <td width="120px">ตัวชี้วัดที่ 5</td> <td width="120px">รวมเฉลี่ย</td> </tr> <tr class="table-bg-white"> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3.00</td> </tr> </thead> <tbody class="body-table"> '.$std_read.' </tbody> </table> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <a href="index.php"> <div class="btn-grey"> ยกเลิก </div> </a> <div data-toggle="modal" data-target="#modalReadScore" class="btn-violet"> บันทึก </div> </div> </div> <div class=" ml-50 mr-50 "> <div class="row"> <div class="col-md-12"> <table> <tbody class="border-none"> '.$text_rtw_desc.' </tbody> </table> </div> </div> </div> '; return $data_response; } public function get_desirable($coures_id_list_val,$room_search,$term_set,$year_set){ $data_response = array(); if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $std_desirable=$this->get_std_desirable($coures_id_list_val,$course_teachingID,$room_search,$status,$status_form,$class_level,$term_set,$year_set); if ($status_form!=25 && $status_form!=26 && $status_form!=27 ) { $text_room_header='<td rowspan = "4" width="8%" style=" vertical-align: middle;">ห้อง</td>'; } $data_response=' <input id="teaching_id_find" type="text" hidden="hidden" name="" value='.$course_teachingID.'> <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div class="row pd-50 stage-set" > <div class="col-sm-12 col-xs-12 mt-nega-20"> <div class="set-line"> <p class="text-bold text-inline">คะแนนคุณลักษณะอันพึงประสงค์</p> </div> </div> </div> <div class="ml-36 mr-50 mt-nega-50" > <div class="col-sm-12 col-xs-12"> <div class="set-line"> <p class="text-inline">คะแนน</p> <select onchange="open_edit_desirable()" id="desirable_select" name="desirable_select" class="form-control search-drop-sub-id mr-30"> <option value="desirable_1">ข้อที่ 1</option> <option value="desirable_2">ข้อที่ 2</option> <option value="desirable_3">ข้อที่ 3</option> <option value="desirable_4">ข้อที่ 4</option> <option value="desirable_5">ข้อที่ 5</option> <option value="desirable_6">ข้อที่ 6</option> <option value="desirable_7">ข้อที่ 7</option> <option value="desirable_8">ข้อที่ 8</option> </select> <p class=" text-inline" >ระบุคะแนนทั้งหมดเป็น</p> <div class="input-group form-serch-width-small"> <input id="input_set_data_seem_desirable" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> <div class="btn-search-save-score"> <div id="btn_set_data_seem_desirable" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </div> </div> </div> <div class=" ml-50 mr-50 mt-30" > <div class="row"> <div class="col-md-12"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "4" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "4" width="8%" style=" vertical-align: middle;">รหัส</td> '.$text_room_header.' <td rowspan = "4" width="35%" style=" vertical-align: middle;">ชื่อ-สกุล</td> </tr> <tr> <td colspan="10">คะแนนคุณลักษณะอันพึงประสงค์</td> </tr> <tr> <td>ข้อที่ 1</td> <td>ข้อที่ 2</td> <td>ข้อที่ 3</td> <td>ข้อที่ 4</td> <td>ข้อที่ 5</td> <td>ข้อที่ 6</td> <td>ข้อที่ 7</td> <td>ข้อที่ 8</td> <td>รวมเฉลี่ย</td> </tr> <tr class="table-bg-white"> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3.00</td> </tr> </thead> <tbody class="body-table"> '.$std_desirable.' </tbody> </table> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <a href="index.php"> <div class="btn-grey"> ยกเลิก </div> </a> <div data-toggle="modal" data-target="#modalDesirableScore" class="btn-violet"> บันทึก </div> </div> </div> '; return $data_response; } public function get_exam($coures_id_list_val,$room_search,$term_set,$year_set){ $data_response = array(); if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $propotion_total=$this->get_propotion_total($coures_id_list_val); $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $std_exam=$this->get_std_exam($coures_id_list_val,$course_teachingID,$room_search,$term_set,$year_set); $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val AND DataID in( SELECT objective_conclude FROM tbl_exam_final_object WHERE courseID=$coures_id_list_val ) ORDER BY no_order ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $no_order=$value['no_order']; $detail=$value['detail']; $objective_final_conclude_desc.=' <tr> <td width="80px">ตัวชี้วัดที่ '.$no_order.'</td> <td >'.$detail.'</td> </tr> '; } $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val AND DataID in( SELECT objective_conclude FROM tbl_exam_mid_object WHERE courseID=$coures_id_list_val ) ORDER BY no_order ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $no_order=$value['no_order']; $detail=$value['detail']; $objective_mid_conclude_desc.=' <tr> <td width="80px">ตัวชี้วัดที่ '.$no_order.'</td> <td >'.$detail.'</td> </tr> '; } $data_response=' <input id="teaching_id_find" type="text" hidden="hidden" name="" value='.$course_teachingID.'> <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div id="course_detal_box" class="ml-50 mr-50 mt-10" > <div class="row"> <div class="box-search-depart"> <table> <tbody style="border: none;"> <tr > <td class="text-before-box3 text-bold" style="float: right;padding-left:45px;"> คะแนน </td> <td width="200px"> <form> <select onchange="open_edit_exam()" id="exam_score_select" name="exam_score_select" class="form-control search-drop-length-ob mt-5"> <option value="mid">กลางภาค</option> <option value="final">ปลายภาค</option> </select> </form> </td> </tr> </tbody> <table> </div> </div> </div> <div class=" ml-50 mr-50 mt-30" > <div class="row"> <div class="col-md-12"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "4" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "4" width="8%" style=" vertical-align: middle;">รหัส</td> <td rowspan = "4" width="60%" style=" vertical-align: middle;">ชื่อ-สกุล</td> </tr> <tr> <td colspan="10">คะแนนสอบ</td> </tr> <tr> <td>กลางภาค</td> <td>ปลายภาค</td> <td>รวม</td> </tr> <tr class="table-bg-white"> <td>'.$propotion_total['mid_exam'].'</td> <td>'.$propotion_total['final_exam'].'</td> <td>'.$propotion_total['total'].'</td> </tr> </thead> <tbody class="body-table"> '.$std_exam.' </tbody> </table> </div> </div> <div class="btn-group-set-add-delete row pd-60 "> <a href="index.php"> <div class="btn-grey"> ยกเลิก </div> </a> <div data-toggle="modal" data-target="#modalExamScore" class="btn-violet"> บันทึก </div> </div> </div> <div class="mr-50 " style="margin-left:80px;"> <p class="text-bold">ตัวชี้วัดกลางถาค</p> </div> <div class="mr-50 mb-30" style="margin-left:100px;"> <div class="row"> <div class="col-md-12"> <table> <tbody class="border-none"> '.$objective_mid_conclude_desc.' </tbody> </table> </div> </div> </div> <div class="mr-50 " style="margin-left:80px;"> <p class="text-bold">ตัวชี้วัดปลายถาค</p> </div> <div class="mr-50 " style="margin-left:100px;"> <div class="row"> <div class="col-md-12"> <table> <tbody class="border-none"> '.$objective_final_conclude_desc.' </tbody> </table> </div> </div> </div> '; return $data_response; } public function get_pick($coures_id_list_val,$active_length){ $data_response = array(); if($active_length=='before'){ $condition="proportion_status=1"; }elseif($active_length=='after'){ $condition="proportion_status=2"; } $this->sql ="SELECT count(*) as num_row FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val AND $condition "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; $num=0; $loop_set=ceil($num_row/10); $scrap=$num_row%10; if ($num_row<=10) { if ($num_row==10) { $length_list="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-10\">ตัวชี้วัดข้อที่ 1-10 </option>" ; }elseif($num_row<10){ if ($num_row==1) { $length_list="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-1\">ตัวชี้วัดข้อที่ 1</option>" ; }else{ $length_list="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-{$num_row}\">ตัวชี้วัดข้อที่ 1-{$num_row} </option>" ; } } }else{ $num_loop_class=1; for ($i=1; $i <=$loop_set ; $i++) { if ($i==1) { $length_list.="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-10\">ตัวชี้วัดข้อที่ 1-10 </option>" ; }else{ if ($loop_set==$i) { if ($scrap==0) { $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$loop_set}0\">ตัวชี้วัดข้อที่ {$num}1-{$loop_set}0 </option>" ; }else{ if ($scrap==1) { $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$num}1\">ตัวชี้วัดข้อที่ {$num}1 </option>" ; }else{ $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$num}{$scrap}\">ตัวชี้วัดข้อที่ {$num}1-{$num}{$scrap} </option>" ; } } }else{ $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$i}0\">ตัวชี้วัดข้อที่ {$num}1-{$i}0 </option>" ; } } $num++; $num_loop_class++; } } $this->sql ="SELECT no_order,detail FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val AND $condition ORDER BY no_order ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $no_order=$value['no_order']; $detail=$value['detail']; $objective_conclude_desc.=' <tr> <td width="80px">ตัวชี้วัดที่ '.$no_order.'</td> <td >'.$detail.'</td> </tr> '; } $data_response=' <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div id="text_header_config" class="row pd-50 stage-set" > <div class="col-sm-12 col-xs-12 mt-nega-20"> <div class="set-line"> <p class="text-bold text-before-box fs-18">คะแนนเก็บ</p> </div> </div> </div> <div id="course_config_box" class="ml-36 mr-50 mt-nega-50" > <div class="col-sm-12 col-xs-12"> <div class="set-line"> <div id="rate_score_box" class="col-sm-12 col-xs-12" style="display: block;"> <div class="row"> <table> <tbody style="border: none;"> <tr > <td class="text-before-box3 text-bold" style="float: right;"> ช่วงคะแนน </td> <td width="250px"> <select onchange="get_objective_list()" id="length_list_val" name="length_list_val" class="form-control search-drop-length-ob mt-5"> '.$length_list.' </select> </td> </tr> <tr > <td class="text-before-box3 text-bold" style="float: right;"> คะแนน </td> <td width="200px"> <select onchange="open_edit_score()" id="objective_list" name="objective_list" class="form-control search-drop-length-ob mt-5"> </select> </td> <td class="text-before-box3 text-bold" style="float: right;"> ระบุคะแนนทั้งหมดเป็น </td> <td> <div class="input-group form-serch-width-small"> <input id="input_set_data_seem" type="text" class="form-control form-set-search" aria-describedby="basic-addon1"> </div> </td> <td> <div class="btn-search-save-score "> <div id="btn_set_data_seem" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <!--table--> <div class=" ml-50 mr-50 mt-80" > <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "5" width="4%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "5" width="4%" style=" vertical-align: middle;">รหัส</td> <td rowspan = "5" width="30%" style=" vertical-align: middle;">ชื่อ-สกุล</td> <td colspan="11">คะแนนเก็บ</td> </tr> <tr> <td id="end_data_find" colspan="10">ตัวชี้วัดทื่/คะแนน</td> <td rowspan = "2">รวม</td> </tr> <tr id="ob_title_table_col"> </tr> <tr id="ob_score_max_table_col" class="table-bg-white"> </tr> </thead> <form id="frm_objective_score_std"> <tbody id="detail_std" class="body-table"> </tbody> </form> </table> </div> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <a href="index.php"> <div class="btn-grey"> ยกเลิก </div> </a> <div data-toggle="modal" data-target="#modalConScore" class="btn-violet"> บันทึก </div> </div> </div> <div class=" ml-50 mr-50 " > <div class="row"> <div class="col-md-12"> <table> <tbody class="border-none"> '.$objective_conclude_desc.' </tbody> </table> </div> </div> </div> '; return $data_response; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_pp6 ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; if($key==0){ $data_response.=' <option selected="selected" value="'.$year.'">'.$year.'</option> '; }else{ $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } } return json_encode($data_response); } } ?><file_sep>/modules/report/level_form.php <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/custom.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); ?> <page orientation="landscape"> <img style="margin :10px 0px 10px 495px;display:block;width: 80px;height: 80px;"src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 22px;margin-top: -5px;"> <p class="text-bold" style="margin-top: -8px;">รายงานการประเมินผลการเรียนตามระดับชั้น</p> <p class="text-bold " style="margin-top: -8px;">โรงเรียนเทศบาลวัดสระทอง</p> <p style="margin-top: -8px;"> <span class="text-bold">ระดับชั้น </span> มัธยมศึกษาปีที่ 1 <span class="text-bold">ห้อง</span> 1 <span class="text-bold">ภาคเรียนที่</span> 1 <span class="text-bold">ปีการศึกษา</span> 2560</p> <p class="text-bold " style="margin-top: 0px;">ครูประจำชั้น ........................................................................</p> </div> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 16px;margin-left:40px;border: 1px solid black;margin-top: 35px;"> <thead > <tr style="background-color: #e0e0e0;"> <td style="width: 4%;height: 65px;">เลขที่</td> <td style="width: 40%;">ชื่อ-สกุล</td> <td style="width: 4%;"><div style="rotate:90;">ท1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ค1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ค1002</div></td> <td style="width: 4%;"><div style="rotate:90;">ส1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ว1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ว1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ว1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ว1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ว1001</div></td> <td style="width: 4%;"><div style="rotate:90;">ว1001</div></td> <td style="width: 4%;"><div style="rotate:90;">คุณลักษณะฯ</div></td> <td style="width: 4%;"><div style="rotate:90;">อ่าน&nbsp;&nbsp;เขียน&nbsp;&nbsp;คิดฯ</div></td> <td style="width: 4%;"><div style="rotate:90;">GPA</div></td> <td style="width: 4%;"><div style="rotate:90;">อันดับที่</div></td> </tr> </thead> <tbody> <tr> <td >1</td> <td >ด.ช. วันสุข สุดสะบาย</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td >1</td> <td >ด.ช. วันสุข สุดสะบาย</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td >1</td> <td >ด.ช. วันสุข สุดสะบาย</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td >1</td> <td >ด.ช. วันสุข สุดสะบาย</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td >1</td> <td >ด.ช. วันสุข สุดสะบาย</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> <tr> <td >1</td> <td >ด.ช. วันสุข สุดสะบาย</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >4</td> <td >1</td> <td >1</td> <td >1</td> <td >1</td> </tr> </tbody> </table> <table style="width: 220px;margin-left: 130px;margin-top: 20px;font-size: 16px;" > <thead> <tr style="width: 220px;"> <td style="width: 35%;text-align: center;border: none;">หมายเหตุ : </td> <td style="width: 65%;border: none;" colspan="3">วิชากิจกรรมพัฒนาผู้เรียน</td> </tr> </thead> <tbody> <tr> <td style="border: none;"></td> <td style="border: none;">ผ</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ผ่าน</td> </tr> <tr> <td style="border: none;"></td> <td style="border: none;">มผ</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ไม่ผ่าน</td> </tr> </tbody> </table> <table style="width: 220px;margin-left: 430px;margin-top: -82.6px;font-size: 16px;" > <thead> <tr> <td colspan="3" style="width: 100%;text-align: center;border: none;">การประเมินผลคุณลักษณะอันพึงประสงค์</td> </tr> </thead> <tbody> <tr> <td style="border: none;">3</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ดีเยี่ยม</td> </tr> <tr> <td style="border: none;">2</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ดี</td> </tr> <tr> <td style="border: none;">1</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ผ่าน</td> </tr> <tr> <td style="border: none;">0</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ไม่ผ่าน</td> </tr> </tbody> </table> <table style="width: 220px;margin-left: 745px;margin-top: -136.5px;font-size: 16px;" > <thead> <tr> <td colspan="3" style="width: 100%;text-align: center;border: none;">การประเมินผลการอ่าน เขียน คิด วิเคราะห์</td> </tr> </thead> <tbody> <tr> <td style="border: none;">3</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ดีเยี่ยม</td> </tr> <tr> <td style="border: none;">2</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ดี</td> </tr> <tr> <td style="border: none;">1</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ผ่าน</td> </tr> <tr> <td style="border: none;">0</td> <td style="border: none;">หมายถึง</td> <td style="border: none;">ไม่ผ่าน</td> </tr> </tbody> </table> </page> <page orientation="landscape"> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 16px;margin-left:40px;border: 1px solid black;margin-top: 35px;"> <thead > <tr style="background-color: #e0e0e0;"> <td colspan="12" style="width: 100%;">สรุปการประเมินผลการเรียน</td> </tr> <tr style="background-color: #e0e0e0;"> <td style="width: 25%;">ผลการเรียน (GPA)</td> <td style="width: 6%;">3.51-4.00</td> <td style="width: 6%;">3.01-3.50</td> <td style="width: 6%;">2.51-3.00</td> <td style="width: 6%;">2.01-2.50</td> <td style="width: 6%;">1.51-2.00</td> <td style="width: 6%;">1.01-1.50</td> <td style="width: 6%;">0.00-1.00</td> <td style="width: 6%;">รวม</td> <td style="width: 6%;">ผ</td> <td style="width: 6%;">มผ</td> <td style="width: 6%;">รวม</td> </tr> </thead> <tbody> <tr> <td >จำนวน</td> <td >10</td> <td >10</td> <td >-</td> <td >-</td> <td >-</td> <td >-</td> <td >-</td> <td >20</td> <td >20</td> <td >-</td> <td >20</td> </tr> <tr> <td >ร้อยละ</td> <td >50.00</td> <td >50.00</td> <td >-</td> <td >-</td> <td >-</td> <td >-</td> <td >-</td> <td >100.00</td> <td >100.00</td> <td >-</td> <td >100</td> </tr> </tbody> </table> <table cellspacing="0" style="width: 94%; text-align: center; font-size: 16px;margin-left:40px;border: 1px solid black;"> <thead > <tr style="background-color: #e0e0e0;"> <td style="width: 27.44%;border-top: none;"></td> <td colspan="5" style="width: 33%;border-top: none;">คุณลักษณะอันพึงประสงค์</td> <td colspan="5" style="width: 39.6%;border-top: none;">อ่าน เขียน คิดวิเคราะห์</td> </tr> <tr style="background-color: #e0e0e0;"> <td >ผลการประเมิน</td> <td style="width: 5%">3</td> <td style="width: 5%">2</td> <td style="width: 5%">1</td> <td style="width: 5%">0</td> <td style="width: 5%">รวม</td> <td style="width: 5%">3</td> <td style="width: 5%">2</td> <td style="width: 5%">1</td> <td style="width: 5%">0</td> <td style="width: 5%">รวม</td> </tr> </thead> <tbody> <tr> <td >จำนวน</td> <td >20</td> <td >-</td> <td >-</td> <td >-</td> <td >20</td> <td >20</td> <td >-</td> <td >-</td> <td >-</td> <td >20</td> </tr> <tr> <td >ร้อยละ</td> <td >100.00</td> <td >-</td> <td >-</td> <td >-</td> <td >100.00</td> <td >100.00</td> <td >-</td> <td >-</td> <td >-</td> <td >100.00</td> </tr> </tbody> </table> <div style="margin-left: 140px;margin-top: 60px;font-size: 16px"> <p>.................................................................รองผู้อำนวยการฝ่ายวิชาการ </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> <div style="margin-left: 690px;margin-top: -77px;font-size: 16px"> <p>.................................................................ผู้อำนวยการ </p> <p style="margin-left: 2px;">(</p> <p style="margin-top: -24px;margin-left:140px;"> )</p> <p style="margin-left: 12px;">................/................/...................</p> </div> </page><file_sep>/src/api.payment.php <?php class ApiPayment { public function __construct() { //$this->APP_URL = BASE_URL.'payment/action.php'; } public function test($value='') { $input = self::demo(); $data = self::set_request($input); return self::order_payment($data); } public function send_order_payment($input=null) { $url = $input['action_url']; $data = self::set_request($input); return apicaller($url,$data); //return json_encode($data);// apicaller($url,$data); } public function set_request($input=null) { /* ['acc_action'] = ''; // new_payment_online ['service_type_name'] = ''; // BookingRoom ['acc_path_rep'] = ''; ['respurl'] = ''; ['member_id'] = ''; ['contact'] = array([i]) ['items'] = array([j]) ['payment'] = array([k]) */ if(!$input){ return false; } $i=0; $contact = $input['contact_info']; $items = $input['items_info']; $payments = $input['payments_info']; // 1 ------------------------------------- $send_data = array(); $send_data['acc_action'] = $input['acc_action']; $send_data['acc_path_rep'] = $input['acc_path_rep']; // success.php // URL forwaording // --------------------------------- $send_data['service_type_name'] = $input['service_type_name']; // BookingRoom $send_data['service_ref_id'] = $input['service_ref_id']; // item ID $send_data['seveice_ref_key_1'] = $input['seveice_ref_key_1']; // (optional) $send_data['seveice_ref_key_2'] = $input['seveice_ref_key_2']; $send_data['seveice_ref_key_3'] = $input['seveice_ref_key_3']; $send_data['server_title'] = $input['server_title']; // BookingRoom : EventID 002 $send_data['respurl'] = $input['respurl']; // URL callback to from server $send_data['member_id'] = $input['member_id']; // member ID // Contact Info // ----- //$send_data['customer_id'] = ''; $send_data['customer_code'] = $input['customer_code']; $send_data['customer_name'] = $input['customer_name']; // ref contact person name OR company name $send_data['io_no'] = $input['io_no']; $send_data['business_place'] = $contact[$i++]; // 0 $send_data['tax_id'] = $contact[$i++]; $send_data['contact_email'] = $contact[$i++]; $send_data['contact_tel_no'] = $contact[$i++]; $send_data['add_building'] = $contact[$i++]; $send_data['add_house_no'] = $contact[$i++]; $send_data['add_street'] = $contact[$i++]; $send_data['add_country'] = $contact[$i++]; $send_data['add_city'] = $contact[$i++]; $send_data['add_district'] = $contact[$i++]; $send_data['add_subdistrict'] = $contact[$i++]; $send_data['add_postal_code'] = $contact[$i++]; // 11 // Contactn Address (optional) $send_data['add_home_building'] = ''; $send_data['add_home_house_no'] = ''; $send_data['add_home_street'] = ''; $send_data['add_home_subdistrict'] = ''; $send_data['add_home_district'] = ''; $send_data['add_home_city'] = ''; $send_data['add_home_country'] = ''; $send_data['add_home_postal_code'] = ''; // Items List $item_count = sizeof($items); $send_data['item_count'] = $item_count; // item count [number] for ($i=0; $i < $item_count; $i++) { $c=0; $send_data['material_on'][] = $items[$i][$c++]; // 0 :รหัสสินค้า : '-' $send_data['service_type'][] = $items[$i][$c++]; // BookingRoom : $service_type_name $send_data['payment_detail'][] = $items[$i][$c++]; // 11A (Meeting Room) A1101 | Date 12/01/2014 10:00 - 16:00 $send_data['quantity'][] = $items[$i][$c++]; // จำนวน : 20 $send_data['unit'][] = $items[$i][$c++]; // หน่วย $send_data['unit_price'][] = $items[$i][$c++]; // ราคาต่อหน่วย : 1000 $send_data['discount'][] = $items[$i][$c++]; // ราคาต่อหน่วย : 500 $send_data['amount'][] = $items[$i][$c++]; // 7: ราคารวม //: (1000x20)-500 = 19500 } // Payment $item_count = sizeof($payments); $deposit = ($item_count > 1)? 'y':'n'; $send_data['deposit_status'] = $deposit; //n/y for ($i=0; $i < $item_count; $i++) { $c=0; $send_data['payment_type'][] = $payments[$i][$c++]; // 0 : creditcard / paypal / billpayment / pos $send_data['invoice_date'][] = $payments[$i][$c++]; //days : 0 $send_data['payment_date'][] = $payments[$i][$c++]; //days : 30 $send_data['net_price'][] = $payments[$i][$c++]; //THB : 39500 $send_data['paid'][] = $payments[$i][$c++]; //THB : 27650 $send_data['whtax'][] = $payments[$i][$c++]; //n/y : n $send_data['whtype'][] = $payments[$i][$c++]; //03 (บุคคลธรรมดา) / 53 (นิติบุคคล) $send_data['percentwh'][] = $payments[$i][$c++]; // 7 : % Withholding tax : 0 } return $send_data; //return apicaller($this->APP_URL,$request_data); } // :: NOT USED :: --------------------------------------------------------------------------------- public function demo() { $data = array(); $data['action_url'] = 'payment/action.php'; $data['action_name'] = 'new_payment_online'; $data['service_name'] = 'BookingRoom'; $data['forword_url'] = 'payment/test_resp.php'; $data['callback_url'] = ''; $data['member_id'] = '1'; $data['sap_id'] = ''; // customer_code // backoffice admin id $data['io_no'] = ''; $data['ref_id'] = '140342104'; // item ID $data['ref_id_1'] = ''; // (optional) $data['ref_id_2'] = ''; $data['ref_id_3'] = ''; $data['title_name'] = 'BookingRoom : EventID 001'; $data['customer_name'] = 'บริษัท ไทยเบฟเวอเรจ จำกัด (มหาชน)';// ref contact person name OR company name $contact = range(1,12); $items = array( range(1,8), range(9,16) ); $payments = array( range(1,8), range(9,16) ); /***************************** @Contact Info:: business_place // 0 tax_id contact_email contact_tel_no add_building add_house_no add_street add_subdistrict add_district add_city add_country add_postal_code // 11 */ $data['contact_info'] = $contact; /***************************** @Items Info:: material_on // รหัสสินค้า : '-' service_type // BookingRoom : $service_type_name payment_detail // 11A (Meeting Room) A1101 | Date 12/01/2014 10:00 - 16:00 quantity // จำนวน 20 unit // หน่วย unit_price // ราคาต่อหน่วย : 1000 discount // ราคาต่อหน่วย : 500 amount // 7 : ราคารวม //: (1000x20)-500 = 19500 */ $data['items_info'] = $items; /***************************** @Payment Info:: payment_type // creditcard / paypal / billpayment / pos invoice_date // days payment_date // days net_price // THB paid // THB whtax // n, y whtype //03 (บุคคลธรรมดา) / 53 (นิติบุคคล) percentwh // 7 : % Withholding tax : 0 */ $data['payments_info'] = $payments; return $data; } public function test_set_request($input=null) { if(!$input){ return false; } $data = array(); $data['acc_action'] = $input['action_name']; $data['service_type_name'] = $input['service_name']; $data['acc_path_rep'] = $input['forword_url']; $data['respurl'] = $input['callback_url']; $data['member_id'] = $input['member_id']; $data['customer_code'] = $input['sap_id']; $data['io_no'] = $input['io_no']; $data['service_ref_id'] = $input['ref_id']; // item ID $data['seveice_ref_key_1'] = $input['ref_id_1']; // (optional) $data['seveice_ref_key_2'] = $input['ref_id_2']; $data['seveice_ref_key_3'] = $input['ref_id_3']; $data['server_title'] = $input['title_name']; $data['customer_name'] = $input['customer_name']; // ref contact person name OR company name // @array and value key[i] $data['contact_info'] = $input['contact_info']; $data['items_info'] = $input['items_info']; $data['payments_info'] = $input['payments_info']; return $data; } } <file_sep>/modules/authen_user/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); /////// CLASS ROLE MANAGEMENT ///// require_once('../../src/class_role.php'); $role = new ClassRole(); $user_role_id = (int)$_SESSION['ss_user_id']; ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $targetfile = '../../../file_managers/userprofile/'; if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list"){ $sort_column = $_GET['sort_column']; $sort_by = $_GET['sort_by']; $pages_current = $_GET['pages_current']; $arr_search_val = array(); $arr_search_val['data_name'] = $_GET['data_name']; $arr_search_val['data_status'] = $_GET['data_status']; echo $class_data->get_data_list($arr_search_val,$pages_current,$sort_column,$sort_by); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_from"){ $data_id = $_GET['data_id']; echo $class_data->get_data_from($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $data_id = (int)$_POST['data_id']; $ath_tasks = $_POST['ath_tasks']; if ($data_id > 0) { $arr_sql = array(); $password = trim($_POST['<PASSWORD>']); $arr_sql[]="role_id='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['role_id'])))."'"; $arr_sql[]="username='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['username'])))."'"; if ($password != "") { $arr_sql[]="password='".MD5($password)."'"; } $arr_sql[]="first_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['first_name'])))."'"; $arr_sql[]="last_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['last_name'])))."'"; $arr_sql[]="status='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['data_status'])))."'"; $arr_sql[]="mdate=now()"; if ($class_data->update_data($arr_sql,$data_id) == "") { if ($ath_tasks != "") { $class_data->update_ath_tasks($ath_tasks,$data_id); } echo "Y"; }else{ echo "N"; } }else{ $arr_sql = array(); $password = trim($_POST['password']); $arr_sql["role_id"]= "'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['role_id'])))."'"; $arr_sql["username"]= "'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['username'])))."'"; if ($password != "") { $arr_sql["password"]= "'".MD5($password)."'"; } $arr_sql["first_name"]= "'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['first_name'])))."'"; $arr_sql["last_name"]= "'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['last_name'])))."'"; $arr_sql["status"]= "'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['data_status'])))."'"; $arr_sql["cdate"]= "now()"; $arr_sql["mdate"]= "now()"; $data_id = $class_data->insert_data($arr_sql,'0'); if ($data_id > 0) { if ($ath_tasks != "") { $class_data->update_ath_tasks($ath_tasks,$data_id); } echo "Y"; }else{ echo "N"; } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "get_role_list"){ $RoleList = $class_data->fetchRole(); echo $RoleList; } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "get_tasks_list"){ $data_val = $_POST['data_val']; $data_id = (int)$_POST['data_id']; echo $class_data->get_tasks_list($data_val,$data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "get_role_reletion_tasks"){ $role_id = $_POST['role_id']; echo $class_data->get_role_reletion_tasks($role_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "upload_thumb"){ // $targetfile = $targetfile."news/"; if (!empty($_FILES)) { $size = getimagesize($_FILES['file']['tmp_name']); // $chk_height = $size[1]; // if($chk_height<271){ // echo $chk_height; // }else{ $new_file_name = date('Ymdhis'); ini_set ( "memory_limit", "80M"); $StatusSave = 0;//[0]=Problems [1]=Successfully $file_name = ""; // File name in Database # Check Type Files $typeaccept = array(".jpg",".gif",".jpeg",".png"); // $typeaccept_doc = array(".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"); $fileExt = "." . strtolower(end(explode('.', $_FILES['file']['name']))); $file_ok = (in_array($fileExt, $typeaccept)) ? true : false; // $document_ok = (in_array($fileExt, $typeaccept_doc)) ? true : false; list($width_n, $height_n, $type_n, $w_n) = getimagesize($_FILES['file']['tmp_name']); if($file_ok==true || $document_ok==true) { include ('../../src/class.upload.php'); // $thumbnail = new Upload($_FILES['file']); // if ($thumbnail->uploaded) { // $thumbnail->image_convert = 'jpg'; // $thumbnail->jpeg_quality = 100; // $thumbnail->image_resize = true; // $thumbnail->image_ratio_crop = true; // $thumbnail->image_x = 100; //4:3 Aspect Ratio // $thumbnail->image_y = 100; //4:3 Aspect Ratio // $thumbnail->file_new_name_body = $new_file_name; // $thumbnail->process($targetfile.'thumbnail/'); // if ($thumbnail->processed) { // UPLOAD THUMBNAIL PROCESS END // //$thumbnail->clean(); // $statussave = 1; // } // } $main_photo = new Upload($_FILES['file']); if ($main_photo->uploaded) { $main_photo->image_convert = 'jpg'; $main_photo->jpeg_quality = 100; $main_photo->image_resize = true; $main_photo->image_ratio_crop = true; $main_photo->image_x = 400; //4:3 Aspect Ratio $main_photo->image_y = 400; //4:3 Aspect Ratio $main_photo->file_new_name_body = $new_file_name; $main_photo->process($targetfile.'thumbnails/'); if ($main_photo->processed) { // UPLOAD MAIN PHOTO PROCESS END //$main_photo->clean(); $statussave = 1; } } $file_name = $new_file_name.".jpg";//.$fileExt; $filetype = $fileExt; } # Check Upload Processed Successfully if($statussave==1){ $usersID = ((int)$_POST['data_id'] == 0) ? 0 : (int)$_POST['data_id']; $arr_sql["usersID"]= "'{$usersID}'"; $arr_sql["FileName"]= "'{$file_name}'"; $arr_sql["Type"]= "'0'"; $arr_sql["sequence"]= "'0'"; $arr_sql["status"]= "'{$usersID}'"; $arr_sql["create_time"]= "now()"; $arr_sql["create_ip"]= "'".$ip."'"; $arr_sql["update_time"]= "now()"; $arr_sql["update_ip"]= "'".$ip."'"; $new_par_id = $class_data->ex_add_thumb($arr_sql); // echo $usersID; echo "successfully"; }else{ echo "Problems"; } // } } } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "get_thumb"){ $data_id = $_POST['data_id']; echo $class_data->get_thumb($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "remove_thumb"){ $data_id = $_POST['data_id']; echo $class_data->remove_thumb($data_id); } ?><file_sep>/modules/profile/class_modules.php <?php class ClassData extends Databases { public function get_img($status_get){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql = "SELECT * FROM tbl_regis_teacher_gallery WHERE regis_teacher_id=$user_id" ; $this->select(); $this->setRows(); $FileName= $this->rows[0]['FileName']; if ($status_get=="index") { if ($FileName!="") { $data_response['get_profile_img'] ='<img class="circle-profile-index" src="file_managers/profile/'.$FileName.'"> '; }else{ $data_response['get_profile_img'] ='<div class="circle-profile-index" style="text-align:center;"> <span class="glyphicon glyphicon-picture span-profile mt-40" aria-hidden="true"></span></div>'; } }else{ if ($FileName!="") { $data_response['get_profile_img'] ='<img class="circle-profile" src="file_managers/profile/'.$FileName.'"> '; }else{ $data_response['get_profile_img'] =''; } } $data_response['file_name']='file_managers/profile/'.$FileName; return json_encode($data_response); } public function update_data($update){ $user_id=$_SESSION['ss_user_id']; $this->sql = "UPDATE tbl_regis_teacher SET ".implode(",",$update)." WHERE DataID='".$user_id."'"; $this->query(); } public function get_department($department_data){ if ($department_data=="1") { $department="ภาษาไทย "; }elseif($department_data=="2"){ $department="คณิตศาสตร์"; }elseif($department_data=="3"){ $department="วิทยาศาสตร์"; }elseif($department_data=="4"){ $department="สังคมศึกษา ศาสนาและวัฒนธรรม"; }elseif($department_data=="41"){ $department="สังคมศึกษา"; }elseif($department_data=="42"){ $department="ภูมิศาสตร์"; }elseif($department_data=="43"){ $department="ประวัติศาสตร์"; }elseif($department_data=="5"){ $department="สุขศึกษาและพลศึกษา"; }elseif($department_data=="6"){ $department="ศิลปะ"; }elseif($department_data=="7"){ $department="การงานอาชีพและเทคโนโลยี"; }elseif($department_data=="8"){ $department="ภาษาต่างประเทศ"; }elseif($department_data=="9"){ $department="หน้าที่พลเมือง"; }elseif($department_data=="10"){ $department="ศิลปะพื้นบ้าน"; }elseif($department_data=="11"){ $department="ศักยภาพ"; }elseif($department_data=="12"){ $department="ภาษาจีน"; }else{ $department="-"; } return $department; } public function get_gender($birthday_data){ if ($birthday_data=="male") { $gender="ชาย"; }else{ $gender="หญิง"; } return $gender; } public function get_birthday($birthday){ $time = strtotime($birthday); $day = date('d',$time); $month = date('m',$time); $year = date('Y',$time)+543; if ($month==1) { $month_data="กรกฎาคม"; }elseif($month==2){ $month_data="กุมภาพนธ์"; }elseif($month==3){ $month_data="มีนาคม"; }elseif($month==4){ $month_data="เมษายน"; }elseif($month==5){ $month_data="พฤษภาคม"; }elseif($month==6){ $month_data="มิถุนายน"; }elseif($month==7){ $month_data="กรกฎาคม"; }elseif($month==8){ $month_data="สิงหาคม"; }elseif($month==9){ $month_data="กัยายน"; }elseif($month==10){ $month_data="ตุลาคม"; }elseif($month==11){ $month_data="พฤษจิกายน"; }elseif($month==12){ $month_data="ธันวาคม"; } $birthday_result=$day.' '.$month_data.' '.$year; return $birthday_result; } public function get_extra_data(){ $data_response = array(); $user_id=$_SESSION['ss_user_id']; $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID= '$user_id' "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['blood_group']=unchkhtmlspecialchars($this->rows[0]['blood_group']); $data_response['gender']=unchkhtmlspecialchars($this->rows[0]['gender']); $data_response['department']=unchkhtmlspecialchars($this->rows[0]['department']); $birthday=unchkhtmlspecialchars($this->rows[0]['birthday']); $time = strtotime($birthday); $day = date('d',$time); $month = date('m',$time); $year = date('Y',$time)+543; if ($month==1 || $month==3 || $month==5 || $month==7 || $month==8 || $month==10 || $month==12) { for ($i=1; $i <=31 ; $i++) { if ($day==$i) { $day_data.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $day_data.='<option value="'.$i.'">'.$i.'</option> '; } } }elseif($month==4 || $month==6 || $month==9 || $month==11){ for ($i=1; $i <=30 ; $i++) { if ($day==$i) { $day_data.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $day_data.='<option value="'.$i.'">'.$i.'</option> '; } } }else{ for ($i=1; $i <=29 ; $i++) { if ($day==$i) { $day_data.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $day_data.='<option value="'.$i.'">'.$i.'</option> '; } } } $data_response['day']=$day_data; $data_response['month']=$month; $data_response['year']=$year; return $data_response; } public function get_data(){ $data_response = array(); $user_id=$_SESSION['ss_user_id']; $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID= '$user_id' "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['positionID'] = unchkhtmlspecialchars($this->rows[0]['positionID']); $fname_th = unchkhtmlspecialchars($this->rows[0]['fname_th']); $lname_th = unchkhtmlspecialchars($this->rows[0]['lname_th']); $data_response['fname_th'] = unchkhtmlspecialchars($this->rows[0]['fname_th']); $data_response['lname_th'] = unchkhtmlspecialchars($this->rows[0]['lname_th']); $data_response['full_name_th'] = $fname_th.' '.$lname_th; $fname_en = unchkhtmlspecialchars($this->rows[0]['fname_en']); $lname_en = unchkhtmlspecialchars($this->rows[0]['lname_en']); $data_response['fname_en'] = unchkhtmlspecialchars($this->rows[0]['fname_en']); $data_response['lname_en'] = unchkhtmlspecialchars($this->rows[0]['lname_en']); $data_response['full_name_en'] = $fname_en.' '.$lname_en; $data_response['study_history'] = unchkhtmlspecialchars($this->rows[0]['study_history']); $birthday_data= unchkhtmlspecialchars($this->rows[0]['birthday']); $birthday=$this->get_birthday($birthday_data); $data_response['birthday']=$birthday; $gender_data= unchkhtmlspecialchars($this->rows[0]['gender']); $gender=$this->get_gender($gender_data); $data_response['gender']=$gender; $data_response['blood_group'] = unchkhtmlspecialchars($this->rows[0]['blood_group']); $data_response['address'] = unchkhtmlspecialchars($this->rows[0]['address']); $data_response['position_name'] = unchkhtmlspecialchars($this->rows[0]['position_name']); $department_data = unchkhtmlspecialchars($this->rows[0]['department']); $department=$this->get_department($department_data); $data_response['department']=$department; $data_response['work'] = unchkhtmlspecialchars($this->rows[0]['work']); $data_response['more_detail'] = unchkhtmlspecialchars($this->rows[0]['more_detail']); $data_response['tell'] = unchkhtmlspecialchars($this->rows[0]['tell']); $data_response['email'] = unchkhtmlspecialchars($this->rows[0]['email']); echo json_encode($data_response); } public function get_day($mouth){ $data_response = array(); for ($i=1; $i <= 29 ; $i++) { $day_make_29.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 30 ; $i++) { $day_make_30.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 31 ; $i++) { $day_make_31.='<option value="'.$i.'">'.$i.'</option>'; } if ($mouth==1 || $mouth==3 || $mouth==5 || $mouth==7 || $mouth==8 || $mouth==10 || $mouth==12) { $data_response['day_set']=$day_make_31; }elseif($mouth==4 || $mouth==6 || $mouth==9 || $mouth==11){ $data_response['day_set']=$day_make_30; }else{ $data_response['day_set']=$day_make_29; } echo json_encode($data_response); } }<file_sep>/src/class.packagewifi.php <?php // API authen class Packagewifi { public function __construct() { } public function get_package() { return self::set_package(); } public function get_package_data() { $package_wifi = array(); $result = self::set_package(); foreach($result['Packages'] as $package){ $package_wifi[$package['ID']] = $package; } return $package_wifi; } public function get_package_name() { $package_wifi = array(); $result = self::set_package(); foreach($result['Packages'] as $package){ $package_wifi[$package['ID']] = $package['Name']; } return $package_wifi; } public function create_wifi_account($package_id,$input) { $data = array( 'Interface' => 'CloudPOS',// 'Command' => '9100',// 'Channel' => 'POS',// 'Version' => '1.0',// 'IP' => '192.168.1.1',// 'PosUsername' => '<EMAIL>', 'PosPassword' => '<PASSWORD>', 'PackageID' => $package_id, 'NoAcc' => 1,// 'Prefix' => $input[$i++], 'Postfix' => $input[$i++], 'MobileNo' => $input[$i++], 'Email' => $input[$i++], 'FName' => $input[$i++], 'Lname' => $input[$i++], 'IDCard' => $input[$i++], // th only 'Passport' => $input[$i++], // other only ); return self::output($data); } public function insert_wifi_account($account_id,$package_id,$input) { $data=array( '', //'Prefix' => '',//'Postfix' => $input['tel'],//'MobileNo' => $input['email'],//'Email' => $input['first_name'],//'FName' => $input['last_name'],//'Lname' => '', // th only//'IDCard' => '', // other only//'Passport' => ); $result = self::create_wifi_account($package_id,$data); $account = $result['Accounts'][0]; $insert = array( 'account_id' => $account_id, 'package_id' => $package_id, 'username' => $account['Username'], 'password' => $account['<PASSWORD>'], 'expire_date' => $account['ExpireDate'], 'cdate' => DATETIME, 'mdate' => DATETIME ); return $insert; } /* Protected */ protected function set_package() { $data = array( 'Interface' => 'CloudPOS', 'Command' => '4400', 'Channel' => 'POS', 'Version' => '1.0', 'IP' => '192.168.1.1', 'PosUsername' => '<EMAIL>', 'PosPassword' => '<PASSWORD>', ); return self::output($data); } protected function output($data) { $data_string = json_encode($data); //$ch = curl_init('http://11.11.11.18/mediator/'); $ch = curl_init('http://172.16.17.32:81/mediator/'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //curl_setopt($ch, CURLOPT_PORT, 81); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string) )); $result = curl_exec($ch); if (curl_errno($ch)) { die(curl_errno($ch)); } return json_decode($result, TRUE); } } <file_sep>/modules/send_midterm/index.php <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="circle-bg-violet"> <img class="head-img-circle" src="assets/images/03.png"> </div> <div class="text-head-title"> <p>ส่งผลการเรียนกลางปี</p> </div> <div class="text-head-desc"> <p>สรุปการประเมินผลการเรียน การประเมินคุณลักษณะอันพึงประสงค์ และการประเมินการอ่าน คิดวิเคราะห์ และเขียน</p> </div> <div class="row pd-50 pt-60 stage-set" > </div> <div class=" ml-50 mr-50" > <div class="row"> <ul class="nav nav-tabs" role="tablist"> <?php if ($_SESSION['ss_status']==1){ ?> <li role="presentation" class="active"><a class="text-black" href="#all_sub_tab" aria-controls="all_sub_tab" role="tab" data-toggle="tab">ส่งผลการเรียน</a></li> <li role="presentation"><a class="text-black" href="#registed_tab" aria-controls="registed_tab" role="tab" data-toggle="tab">รายวิชาที่ส่งผลการเรียนแล้ว</a></li> <?php }else{ ?> <li role="presentation" class="active"><a class="text-black" href="#all_sub_tab" aria-controls="all_sub_tab" role="tab" data-toggle="tab">ส่งผลการเรียน</a></li> <li role="presentation"><a class="text-black" href="#registed_tab" aria-controls="registed_tab" role="tab" data-toggle="tab">รายวิชาที่ส่งผลการเรียนแล้ว</a></li> <li role="presentation" ><a class="text-black" href="#teacher_tab" aria-controls="teacher_tab" role="tab" data-toggle="tab">ยกเลิกการส่งผลการเรียน</a></li> <?php } ?> </ul> </div> <div class="tab-content"> <?php if ($_SESSION['ss_status']==1){ ?> <div role="tabpanel" class="tab-pane fade <?php if ($_SESSION['ss_status']==1){ echo "in active";} ?>" id="all_sub_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">ส่งผลการเรียน</h4> </div> </div> <div class="row"> <div class="col-sm-6"> <p class="text-search" style="font-weight: bold;">ปีการศึกษา</p> <p class="text-search" style="margin-left: 5px;font-weight: bold;">2560</p> <!-- <div style="padding: 5px;height: 25px;background-color: #ac68cc;float: left;margin-top: -2px "> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> </div>--> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th><input id="checkbox_all" type="checkbox"></th> <th style="text-align: left;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th>ระดับชั้น</th> <th>ห้อง</th> </tr> </thead> <tbody id="table_list" class="body-table"> </tbody> </table> </div> </div> </div> <div id="btn_cancel_checked" class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalAddPp6" class="btn-violet"> ยืนยัน </div> </div> <div role="tabpanel" class="tab-pane fade " id="registed_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">รายวิชาที่ส่งผลการเรียนแล้ว</h4> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th></th> <th style="text-align: left;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th>ระดับชั้น</th> <th>ห้อง</th> </tr> </thead> <tbody id="table_list_added" class="body-table"> </tbody> </table> </div> </div> </div> </div> <?php }else if($_SESSION['ss_status']==2){ ?> <div role="tabpanel" class="tab-pane fade in active" id="all_sub_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">ส่งผลการเรียน</h4> </div> </div> <div class="row"> <div class="col-sm-6"> <form id="frm_data_search_reiged_send"> <p class="text-search" >ภาคเรียนที่</p> <select name="data_term_search" id="data_term_search_send" class="form-control search-years-registed"> <option value="1">1</option> <option value="2">2</option> <option value="1,2">1,2</option> </select> <p class="text-search ml-10" >ปีการศึกษา</p> <select name="data_year_search" id="year_data_sum_send" class="form-control search-years-registed data_year_search"> </select> <div class="btn-years-registed" > <div id="get_coures_id_list_send" class="btn-search "><span class="glyphicon glyphicon-search" aria-hidden="true"></span></div> </div> </form> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th><input id="checkbox_all" type="checkbox"></th> <th style="text-align: left;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th>ระดับชั้น</th> <th>ห้อง</th> </tr> </thead> <tbody id="table_list_send" class="body-table"> </tbody> </table> </div> </div> </div> <div id="btn_cancel_checked" class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalAddPp6" class="btn-violet"> ยืนยัน </div> </div> <div role="tabpanel" class="tab-pane fade " id="registed_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">รายวิชาที่ส่งผลการเรียนแล้ว</h4> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table id="table_added" class="table table-striped-violet" > <thead class="header-table"> <tr> <th></th> <th style="text-align: left;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th>ระดับชั้น</th> <th>ห้อง</th> <th>วันที่</th> </tr> </thead> <tbody id="table_list_added" class="body-table"> </tbody> </table> </div> </div> </div> </div> <div role="tabpanel" class="tab-pane fade " id="teacher_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">ยกเลิกการส่งผลการเรียน</h4> </div> </div> <div class="row"> <div class="col-sm-6"> <form id="frm_data_search_reiged_edit"> <p class="text-search" >ภาคเรียนที่</p> <select name="data_term_search" id="data_term_search" class="form-control search-years-registed"> <option value="1">1</option> <option value="2">2</option> <option value="1,2">1,2</option> </select> <p class="text-search ml-10" >ปีการศึกษา</p> <select name="data_year_search" id="year_data_sum" class="form-control search-years-registed data_year_search"> </select> <div class="btn-years-registed" > <div id="btn_data_year_search_edit" class="btn-search "><span class="glyphicon glyphicon-search" aria-hidden="true"></span></div> </div> </form> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th></th> <th style="text-align: left;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th>ระดับชั้น</th> <th>ห้อง</th> <th>ยกเลิก</th> </tr> </thead> <tbody id="table_list_edit" class="body-table"> </tbody> </table> </div> </div> </div> </div> <?php } ?> </div> </div> </div><file_sep>/modules/authen_user/from.js document.writeln('<script type="text/javascript" src="assets/js/texteditor/texteditor.js"></script>'); document.writeln("<link href='assets/plugins/bootstrap3-wysihtml5/bootstrap3-wysihtml5.min.css' rel='stylesheet' type='text/css' />"); // document.writeln("<script type='text/javascript' src='http://bp.yahooapis.com/2.4.21/browserplus-min.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.gears.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.silverlight.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.flash.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.browserplus.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.html4.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.html5.js'></script>"); document.writeln("<script type='text/javascript' src='modules/authen_user/upload_boxIV.js'></script>"); document.writeln("<script type='text/javascript' src='modules/authen_user/upload_award.js'></script>"); var opPage = 'authen_user'; var url_process = 'modules/' + opPage + '/process.php' var data_id = (typeof _get.id === 'undefined') ? 0 : _get.id; $(document).ready(function() { get_role_list(); get_data(); tasks_list(); get_thumb(); }); function get_data(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_data_from" }); formData.push({ "name": "data_id", "value": data_id}); $.getJSON(url_process, formData, function(data, textStatus) { // alert(data.role_id); $('#username').val(data.username); $('#first_name').val(data.first_name); $('#last_name').val(data.last_name); $('#role_id').select2("val",data.role_id); $('#data_status').select2("val",data.status); }); } function get_role_list(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_role_list" }); $.post(url_process, formData, function(data, textStatus, xhr) { $('#role_id').html(data); }); } $(document).delegate('#btn__save', 'click', function(event) { var ath_tasks=$("input[name='checkbox_ath_tasks[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "save_data" }); formData.push({ "name": "data_id", "value": data_id}); formData.push({ "name": "ath_tasks", "value": ath_tasks}); $.post(url_process, formData, function(data, textStatus, xhr) { window.location = 'index.php?op=authen_user-index&data=success'; }); }); function tasks_list(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_tasks_list" }); formData.push({ "name": "data_id", "value": _get.id}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('.tasks_list').html(data.tasks_list); },'JSON'); } $(document).delegate('#role_id', 'change', function(event) { get_role_reletion_tasks($(this).val()); }); function get_role_reletion_tasks(role_id){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_role_reletion_tasks" }); formData.push({ "name": "role_id", "value": role_id}); $.post(url_process, formData, function(data, textStatus, xhr) { $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); $.each(data.task_id, function(k, v) { $('#ath_tasks_'+v).attr('checked', true); }); },'json'); } <file_sep>/src/#1class.userauthen.php <?php // API authen class UserAuthen { var $DB; var $BY; var $ss_user_menu; var $ss_user_task; public function __construct() { $this->DB = new Databases(); $this->BY = ($_SESSION['ssADMIN_ID'])? $_SESSION['ssADMIN_ID']: null; $this->ss_user_menu = ($_SESSION['ssADMIN']['MENU'])? $_SESSION['ssADMIN']['MENU']: null; $this->ss_user_task = ($_SESSION['ssADMIN']['TASK'])? $_SESSION['ssADMIN']['TASK']: null; if($this->BY){ self::result_authentication(); } } public function __escape($inputVar) { return mysql_real_escape_string(addslashes(htmlentities($inputVar, ENT_QUOTES))); } public function login( $user=null, $pass=null ) { $where = ' where '; $where .= ' a.username = "'.self::__escape($user).'" and a.password = "'.self::__escape($pass).'"'; $this->DB->sql = 'select a.*,a.status as status1,b.role_name,b.status as status2 from ath_users as a left join ath_roles as b on (a.role_id=b.role_id) '. $where .' limit 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ if( $result[0][status1] != 1 ){ return 1; } if( $result[0][status2] != 1 ){ return 2; } return $result[0]; } return 0; } public function reLogin( $id ) { $where = ' where '; $where .= ' a.user_id = '.self::__escape($id).' and a.status=1 and b.status=1 '; $this->DB->sql = 'select a.*,b.role_name from ath_users as a left join ath_roles as b on (a.role_id=b.role_id) '. $where .' limit 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ return $result[0]; } return null; } public function task( $task_key=null ) { $data = array(); if($_SESSION['ssADMIN']['TASK']){ $data = $_SESSION['ssADMIN']['TASK']; } else{ $result = self::result_authentication(); $data = $result['task']; } if($data[$task_key]){ return true; } else{ return false; } } public function menu_authen() { $data = array(); if($_SESSION['ssADMIN']['MENU']){ $data = $_SESSION['ssADMIN']['MENU']; } else{ $result = self::result_authentication(); $data = $result['menu']; } return $data; } protected function result_authentication() { if( $_SESSION['ssADMIN']['MENU'] && $_SESSION['ssADMIN']['TASK'] ){ return true; } $this->DB->sql = 'SELECT a.fun_id,a.task_id,a.task_key FROM ath_tasks as a LEFT JOIN ath_user_reletion_tasks as b on(a.task_id=b.task_id) WHERE b.user_id='.$this->BY; $this->DB->select(); $result = $this->DB->getRows(); $fun_data = array(); $task_data = array(); $data = array(); if($result){ foreach( $result as $rs ){ $fun_id = $rs['fun_id']; $task_key = $rs['task_key']; $fun_data[$fun_id] = $fun_id; $task_data[$task_key] = $rs['task_id']; } $data['menu'] = $fun_data; $data['task'] = $task_data; } $_SESSION['ssADMIN']['MENU'] = $fun_data; $_SESSION['ssADMIN']['TASK'] = $task_data; return $data; } public function view_tasks() { $result = self::ath_tasks(); if(!$result){ return false; } // Result foreach( $result as $rs ){ $data[$rs['task_key']] = $rs['task_description']; } return $data; } /* public function logout( $url=null ) { // unset unset($_SESSION); // location if($url){ header('location:'.$url); } return true; } */ public function update_last_login($id) { if($id){ /* $update = array(); $update['mdate'] = DATETIME; $where = array(); $where['user_id'] = $id; */ $this->DB->sql = 'UPDATE ath_users set mdate="'.DATETIME.'" where user_id='.$id; $this->DB->update(); //$this->DB->update( 'ath_users', $update, $where); } } // ================================================================================== /* protected */ protected function ath_main_function() { $this->DB->sql = 'select * from ath_main_function where status=1 '; $this->DB->select(); $result = $this->DB->getRows(); return $result; } protected function ath_tasks($key=null) { $where = null; if($key){ $where = ' where '; $where .= ' task_key = "'.self::__escape($key).'" '; } $this->DB->sql = 'select * from ath_tasks '. $where; $this->DB->select(); $result = $this->DB->getRows(); if($key){ return $result[0]; } else{ return $result; } } } <file_sep>/modules/graduate/index.js var opPage = 'graduate'; $(document).ready(function() { get_year(); }); function get_std_list() { var formData = $( "#frm_data_search" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_std_list" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_std_list").html(data.std_list); }) } function get_year() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_year" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#year_search").html(data.year); get_std_list(); }) } $(document).delegate('#btn_search_std_list', 'click', function(event) { get_std_list(); }); $(document).delegate('#checkbox_all', 'click', function(event) { if(this.checked) { // check select status $('.checkbox_data').each(function() { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); }else{ $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } }); $(document).delegate('#btn__conf_add', 'click', function(event) { var tempValue=$("input[name='checkbox_add[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var formData = new Array(); formData.push({ "name": "acc_action", "value": "data_add" }); formData.push({ "name": "data_val", "value": tempValue}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { tempValue=''; get_std_list(); $('.modal').modal('hide'); }) }); $(document).delegate('#btn_edit_status', 'click', function(event) { var class_room_modal_id = $('#status_modal_id').val(); var status_val = $('#status_modal').val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "edit_status" }); formData.push({ "name": "class_room_modal_id", "value": class_room_modal_id }); formData.push({ "name": "status_val", "value": status_val }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_std_list(); $('.modal').modal('hide'); status_val=''; class_room_modal_id=''; }); }); $(document).delegate('.btn_getdata_edit', 'click', function(event) { var data_id = $(this).attr('data-id'); var formData = new Array(); formData.push({ "name": "acc_action", "value": "getdata_edit" }); formData.push({ "name": "data_id", "value": data_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#status_modal').val(data.status); $('#status_modal_id').val(data_id); data_id=''; }); });<file_sep>/includes/class_modules.php <?php class ClassData extends Databases { public function get_img_tab(){ $data_response = array(); $user_id=$_SESSION['ss_user_id']; $sql = "SELECT * FROM tbl_regis_teacher_gallery WHERE regis_teacher_id= '$user_id' "; $this->sql = $sql; $this->select(); $this->setRows(); $FileName= unchkhtmlspecialchars($this->rows[0]['FileName']); if (isset($_SESSION['ss_status_std']) && $_SESSION['ss_status_std']==1) { $data_response['get_img_tab'] = '<img class="user-profile" src="assets/images/per.png" >'; }else{ if ($FileName=='') { $data_response['get_img_tab'] = '<img class="user-profile" src="assets/images/per.png" >'; }else{ $data_response['get_img_tab'] = '<img class="user-profile" src="file_managers/profile/'.$FileName.'" >'; } } return json_encode($data_response); } public function get_name_tab(){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); if (isset($_SESSION['ss_status_std']) && $_SESSION['ss_status_std']==1) { $sql = "SELECT * FROM tbl_student WHERE std_ID= '$user_id' "; $this->sql = $sql; $this->select(); $this->setRows(); $fname_th= unchkhtmlspecialchars($this->rows[0]['fname']); $lname_th= unchkhtmlspecialchars($this->rows[0]['lname']); }else{ $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID= '$user_id' "; $this->sql = $sql; $this->select(); $this->setRows(); $fname_th= unchkhtmlspecialchars($this->rows[0]['fname_th']); $lname_th= unchkhtmlspecialchars($this->rows[0]['lname_th']); } $data_response['full_name_th'] = $fname_th.' '.$lname_th; return json_encode($data_response); } } ?><file_sep>/modules/conclusion/process.php <?php @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list_learning"){ $class_level=$_GET['class_level']; $room_data=$_GET['room_data']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_data_list_learning($class_level,$room_data,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list_department"){ $class_level=$_GET['class_level']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; $department_search=$_GET['department_search']; echo $class_data->get_data_list_department($class_level,$term_data,$year_data,$department_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list_level"){ $class_level=$_GET['class_level']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_data_list_level($class_level,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list_desirable"){ $class_level=$_GET['class_level']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_data_list_desirable($class_level,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_list_rtw"){ $class_level=$_GET['class_level']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_data_list_rtw($class_level,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); }<file_sep>/modules/news/upload.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $arr_sql["title"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['title'])))."'"; $arr_sql["detail"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['detail'])))."'"; $arr_sql["author"]="'".$_SESSION['ss_user_id']."'"; $arr_sql["date"]="'".date("Y-m-d")."'"; $news_id= $class_data->insert_news($arr_sql); for ($i=1; $i <= 5 ; $i++) { if ($i==1) { if(is_uploaded_file($_FILES["img$i"]['tmp_name'])) { $ext=pathinfo(basename($_FILES["img$i"]['name']),PATHINFO_EXTENSION); $new_file='file_'.uniqid().".".$ext; $oldFileName=$_FILES["img$i"]['name']; $sourcePath = $_FILES["img$i"]['tmp_name']; $targetPath = "../../file_managers/news/".$new_file; $upload=move_uploaded_file($sourcePath,$targetPath); if ($upload==false) { echo "no"; exit(); } $class_data->sql="INSERT INTO tbl_news_gallery(newsID,file_name) VALUES($news_id,'$new_file')"; $class_data->query(); $new_id= $class_data->insertID(); } }else{ if(is_uploaded_file($_FILES["img$i"]['tmp_name'])) { $ext=pathinfo(basename($_FILES["img$i"]['name']),PATHINFO_EXTENSION); $new_file='file_'.uniqid().".".$ext; $oldFileName=$_FILES["img$i"]['name']; $sourcePath = $_FILES["img$i"]['tmp_name']; $targetPath = "../../file_managers/news_sub/".$new_file; $upload=move_uploaded_file($sourcePath,$targetPath); if ($upload==false) { echo "no"; exit(); } $class_data->sql="INSERT INTO tbl_news_gallery_sub(newsID,file_name) VALUES($news_id,'$new_file')"; $class_data->query(); $new_id= $class_data->insertID(); } } } header("location:../../index.php?op=news-index"); <file_sep>/modules/mobile_api/newsheighlight.php <?php @session_start(); require_once('config.php'); require_once('src/database.php'); include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $condition = false; $num= $class_data->rows[0]['num']; $json = json_decode(file_get_contents('php://input'), true); $newsheighlight=$json['newsheighlight']; $token=$json['token']; $token_set='4939d40bd21d4b987edc18a1911a6b94'; if (MD5($token)==$token_set) { if (!empty($newsheighlight) ) { //$sql = "SELECT DataID,title,detail,date FROM tbl_news WHERE DataID in(SELECT MAX(DataID) FROM tbl_news)"; $sql = "SELECT DataID,title,detail,date FROM tbl_news ORDER BY date DESC"; $class_data->sql = $sql; $class_data->select(); $class_data->setRows(); $DataID=$class_data->rows[0]['DataID']; $data_res['DataID']=$DataID; $data_res['title']=strip_tags(htmlspecialchars_decode($class_data->rows[0]['title'])); $data_res['detail']=strip_tags(htmlspecialchars_decode($class_data->rows[0]['detail'])); $date_set=$class_data->rows[0]['date']; $old_form_date = strtotime($date_set); $data_res['date']=date('d-m-Y', $old_form_date); $data_res['status']=1; $sql = " SELECT file_name FROM tbl_news_gallery WHERE newsID=$DataID"; $class_data->sql =$sql; $class_data->select(); $class_data->setRows(); $data_res['img_url']='/file_managers/news/'.$class_data->rows[0]['file_name']; }else{ $data_res['status']=0; } } echo json_encode($data_res); ?> <file_sep>/src/config.php <?php @header( 'Pragma: no-cache' ); @header( 'Content-Type:text/html;arset=utf-8'); date_default_timezone_set('Asia/Bangkok'); $config['page_title'] = "iwind.co.th"; $config['web_name'] = "iwind.co.th"; $config['ip_address'] = ipCheck(); $config['date_now'] = date('Y-m-d H:i:s'); $config['referrer_page'] = (@eregi($_SERVER["HTTP_HOST"], str_replace("www.", "", strtolower($_SERVER["HTTP_REFERER"])))) ? 1 : 0; //[1]=yes / [0]=no /*Database Connect *************************************************************/ define("HostName","localhost"); define("DBName","tapma_db"); define("DBUsername","tapma_admin"); define("DBPassword","<PASSWORD>"); //offline //define("HostName","localhost"); //define("DBName","japan_db"); //define("DBUsername","root"); //define("DBPassword","<PASSWORD>"); // Open the base (construct the object): $db = new DB(DBName, HostName, DBUsername, DBPassword); // Admin Config $ADMIN_ID = $_SESSION['ssADMIN_ID']; $result = $db->query("SELECT * FROM tbl_admin WHERE admin_id='{$ADMIN_ID}'"); $line = $db->fetchNextObject($result); $PM_LEVEL = $line->LEVEL; $ARR_PM_BANNER = explode(",", "1,1,1");//explode(",", $line->PM_BANNER); // [insert],[edit],[remove],[review],[show index],[sequence] $ARR_PM_NEWS_ACTIVITY = explode(",", "1,1,1");//explode(",", $line->PM_NEWS_ACTIVITY); // [insert],[edit],[remove],[review],[show index],[sequence] ?><file_sep>/src/class.userauthen.php <?php // API authen class UserAuthen { var $DB; var $BY; var $ss_user_menu; var $ss_user_task; public function __construct() { $this->DB = new Databases(); $this->BY = ($_SESSION['ssADMIN_ID'])? $_SESSION['ssADMIN_ID']: null; $this->ss_user_menu = ($_SESSION['ssADMIN']['MENU'])? $_SESSION['ssADMIN']['MENU']: null; $this->ss_user_task = ($_SESSION['ssADMIN']['TASK'])? $_SESSION['ssADMIN']['TASK']: null; if($this->BY){ self::result_authentication(); } } public function __escape($inputVar) { return mysql_real_escape_string(addslashes(htmlentities($inputVar, ENT_QUOTES))); } public function ldap_connection($ldaprdn,$ldappass) { $ldaphost = 'LDAP://scbwadc01.thaibev.com'; //$ldaprdn = 'i1026573'; //$ldappass = '<PASSWORD>'; // 'P@ssw0rd'; // ' $domain='thaibev'; $port=389; $ldapconn = ldap_connect($ldaphost, $port) or die("Could not conenct to {$host}"); if ($ldapconn) { //echo "$ldapconn, $ldaprdn@$domain, $ldappass <p>" ; $bind=@ldap_bind($ldapconn, $ldaprdn .'@' .$domain, $ldappass); if ($bind) { return 1; //echo("Login correct"); } else { return 4; //echo("Login incorrect"); } } return 3; } public function login( $user=null, $pass=null ) { $where = ' where '; $where .= ' a.username = "'.self::__escape($user).'" and a.status=1 and b.status=1 '; //$where .= ' a.username = "'.self::__escape($user).'" and a.password = "'.self::__escape($pass).'"'; $this->DB->sql = 'select a.*,a.status as status1,b.role_name,b.status as status2 from ath_users as a left join ath_roles as b on (a.role_id=b.role_id) '. $where .' limit 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ if( $result[0]['status1'] != 1 ){ return 1; } if( $result[0]['status2'] != 1 ){ return 2; } if($user!='c1000475'){ // LDAP Connection $check_ldap = self::ldap_connection($user,$pass); if( $check_ldap != 1 ){ return $check_ldap; // connection or user , pass fail } }else{ return $result[0]; } return $result[0]; } return 0; } public function reLogin( $id ) { $where = ' where '; $where .= ' a.user_id = '.self::__escape($id).' and a.status=1 and b.status=1 '; $this->DB->sql = 'select a.*,b.role_name from ath_users as a left join ath_roles as b on (a.role_id=b.role_id) '. $where .' limit 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ return $result[0]; } return null; } public function task( $task_key=null ) { $data = array(); if($_SESSION['ssADMIN']['TASK']){ $data = $_SESSION['ssADMIN']['TASK']; } else{ $result = self::result_authentication(); $data = $result['task']; } if($data[$task_key]){ return true; } else{ return false; } } public function menu_authen() { $data = array(); if($_SESSION['ssADMIN']['MENU']){ $data = $_SESSION['ssADMIN']['MENU']; } else{ $result = self::result_authentication(); $data = $result['menu']; } return $data; } protected function result_authentication() { if( $_SESSION['ssADMIN']['MENU'] && $_SESSION['ssADMIN']['TASK'] ){ return true; } $this->DB->sql = 'SELECT a.fun_id,a.task_id,a.task_key FROM ath_tasks as a LEFT JOIN ath_user_reletion_tasks as b on(a.task_id=b.task_id) WHERE b.user_id='.$this->BY; $this->DB->select(); $result = $this->DB->getRows(); $fun_data = array(); $task_data = array(); $data = array(); if($result){ foreach( $result as $rs ){ $fun_id = $rs['fun_id']; $task_key = $rs['task_key']; $fun_data[$fun_id] = $fun_id; $task_data[$task_key] = $rs['task_id']; } $data['menu'] = $fun_data; $data['task'] = $task_data; } $_SESSION['ssADMIN']['MENU'] = $fun_data; $_SESSION['ssADMIN']['TASK'] = $task_data; return $data; } public function view_tasks() { $result = self::ath_tasks(); if(!$result){ return false; } // Result foreach( $result as $rs ){ $data[$rs['task_key']] = $rs['task_description']; } return $data; } /* public function logout( $url=null ) { // unset unset($_SESSION); // location if($url){ header('location:'.$url); } return true; } */ public function update_last_login($id) { if($id){ /* $update = array(); $update['mdate'] = DATETIME; $where = array(); $where['user_id'] = $id; */ $this->DB->sql = 'UPDATE ath_users set mdate="'.DATETIME.'" where user_id='.$id; $this->DB->update(); //$this->DB->update( 'ath_users', $update, $where); } } public function insert_log($username,$message,$status=0) { $insert = array(); $insert['username'] = $username; $insert['ip'] = $_SERVER['REMOTE_ADDR']; $insert['status'] = $status; $insert['message'] = $message; $insert['cdate'] = date('Y-m-d H:i:s'); self::this_insert('ath_log_login',$insert); } // Timestamp Or Session public function checkedTimestamp() { $where = 'session_id="'.session_id().'"'; $this->DB->sql = 'select * from ath_log_timestamp where '.$where.' LIMIT 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ return 1; } else{ return 0; } } public function createTimestamp($user_id) { $where = 'user_id="'.$user_id.'"'; $this->DB->sql = 'select * from ath_log_timestamp where '.$where.' LIMIT 0,1 '; $this->DB->select(); $result = $this->DB->getRows(); if($result){ // update self::updateTimestamp($user_id); } else{ // insert self::insertTimestamp($user_id); } } public function insertTimestamp($user_id) { $insert = array(); $insert['user_id'] = $user_id; $insert['session_id'] = session_id(); $insert['cdate'] = DATETIME;//date('Y-m-d H:i:s',strtotime(DATETIME.'+30 minute'));; self::this_insert('ath_log_timestamp',$insert); //$this->DB->_insert('ath_log_timestamp',$insert); } public function updateTimestamp($user_id) { $where = 'user_id="'.$user_id.'"'; $update = array(); $update['session_id'] = session_id(); $update['cdate'] = DATETIME;//date('Y-m-d H:i:s',strtotime(DATETIME.'+30 minute'));; self::this_update('ath_log_timestamp',$update,$where); //$this->DB->_update('ath_log_timestamp',$update,$where); } // ================================================================================== /* protected */ protected function ath_main_function() { $this->DB->sql = 'select * from ath_main_function where status=1 '; $this->DB->select(); $result = $this->DB->getRows(); return $result; } protected function ath_tasks($key=null) { $where = null; if($key){ $where = ' where '; $where .= ' task_key = "'.self::__escape($key).'" '; } $this->DB->sql = 'select * from ath_tasks '. $where; $this->DB->select(); $result = $this->DB->getRows(); if($key){ return $result[0]; } else{ return $result; } } protected function this_insert($table,$insert) { $keys = array_keys($insert); $values = array_values($insert); $field = @implode(",",$keys); $value_data = @implode("','",$values); $this->DB->sql = "INSERT INTO {$table}({$field}) VALUES('{$value_data}')"; $this->DB->insert(); } protected function this_update( $table=null, $data, $where=null) { $update = ''; if( $data ){ foreach($data as $k => $v){ $update .= $k.'="'.$v.'",'; } $update = substr($update, 0, -1); } if( $where ) $where = " WHERE ". $where; $this->DB->sql = "UPDATE {$table} SET {$update} {$where}"; $this->DB->update(); } } <file_sep>/modules/regis_student/class_modules.php <?php class ClassData extends Databases { public function get_term_year_now(){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $data_response['year']=$this->rows[0]['year']; $data_response['year_now']=date("Y")+543; $data_response['status_rang']=$_SESSION['ss_status_rang']; echo json_encode($data_response); } public function chk_id($std_ID,$card_ID){ $data_response = array(); $sql = "SELECT count(*) as num_std_ID FROM tbl_student WHERE std_ID='$std_ID' "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['num_std_ID']=unchkhtmlspecialchars($this->rows[0]['num_std_ID']); $sql = "SELECT count(*) as num_card_ID FROM tbl_student WHERE card_ID='$card_ID' "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['num_card_ID']=unchkhtmlspecialchars($this->rows[0]['num_card_ID']); return json_encode($data_response); } public function insert_data($insert,$arr_sql_class_room){ $this->sql = "INSERT INTO tbl_student(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $new_id = $this->insertID(); $this->sql = "INSERT INTO tbl_std_class_room(".implode(",",array_keys($arr_sql_class_room)).") VALUES (".implode(",",array_values($arr_sql_class_room)).")"; $this->query(); } public function get_years(){ $data_response = array(); $years_now=intval(date("Y"));+ $years_now=$years_now+543; for ($i=$years_now; $i >= 2480 ; $i--) { $data_response['set_years'].='<option value="'.$i.'">'.$i.'</option>'; } echo json_encode($data_response); } public function get_day($mouth){ $data_response = array(); for ($i=1; $i <= 29 ; $i++) { $day_make_29.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 30 ; $i++) { $day_make_30.='<option value="'.$i.'">'.$i.'</option>'; } for ($i=1; $i <= 31 ; $i++) { $day_make_31.='<option value="'.$i.'">'.$i.'</option>'; } if ($mouth==1 || $mouth==3 || $mouth==5 || $mouth==7 || $mouth==8 || $mouth==10 || $mouth==12) { $data_response['day_set']=$day_make_31; }elseif($mouth==4 || $mouth==6 || $mouth==9 || $mouth==11){ $data_response['day_set']=$day_make_30; }else{ $data_response['day_set']=$day_make_29; } echo json_encode($data_response); } }<file_sep>/modules/up_class/index.js var opPage = 'up_class'; $(document).ready(function() { get_year(); get_data_upclassed(); }); function up_class_p2() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_p" }); formData.push({ "name": "value_set", "value": 2 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_p2').css('display','block');up_class_p3(); }); } function up_class_p3() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_p" }); formData.push({ "name": "value_set", "value": 3 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_p3').css('display','block');up_class_p4(); }); } function up_class_p4() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_p" }); formData.push({ "name": "value_set", "value": 4 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_p4').css('display','block');up_class_p5(); }); } function up_class_p5() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_p" }); formData.push({ "name": "value_set", "value": 5 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_p5').css('display','block');up_class_p6(); }); } function up_class_p6() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_p" }); formData.push({ "name": "value_set", "value": 6 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_p6').css('display','block');up_class_m2(); }); } function up_class_m2() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_m" }); formData.push({ "name": "value_set", "value": 2 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_m2').css('display','block');up_class_m3(); }); } function up_class_m3() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_m" }); formData.push({ "name": "value_set", "value": 3 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_m3').css('display','block');up_class_m5(); }); } function up_class_m5() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_m" }); formData.push({ "name": "value_set", "value": 5 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_m5').css('display','block');up_class_m6(); }); } function up_class_m6() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "up_class_m" }); formData.push({ "name": "value_set", "value": 6 }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#text_status_m6').css('display','block'); $('#footer_btn').css('display','block'); $('#text_status_header').html('เลื่อนระดับชั้นของนักเรียนทั้งหมดสำเร็จ'); get_data_upclassed(); }); } $(document).delegate('.btn_reverse', 'click', function(event) { var log_upclass_id = $(this).attr('data-id'); var data_text = $(this).attr('data-text'); var data_year_old = $(this).attr('data-year-old'); var data_year_new = $(this).attr('data-year-new'); $('#log_upclass_id').val(log_upclass_id); $('#data_text').html(data_text); $('#data_year_old').val(data_year_old); $('#data_year_new').val(data_year_new); log_upclass_id=''; data_text=''; data_year_old=''; data_year_new=''; }); $(document).delegate('#btn_reverse_upclass', 'click', function(event) { var log_upclass_id = $('#log_upclass_id').val(); var data_year_old = $('#data_year_old').val(); var data_year_new = $('#data_year_new').val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "reverse_upclass" }); formData.push({ "name": "log_upclass_id", "value": log_upclass_id }); formData.push({ "name": "data_year_old", "value": data_year_old }); formData.push({ "name": "data_year_new", "value": data_year_new }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal('hide'); $("#modalReversed").modal('show'); get_data_upclassed(); }); }); $(document).delegate('#btn_upclass', 'click', function(event) { $(".modal").modal('hide'); $("#modalWaitUp").modal('show'); up_class_p2(); }) function get_year() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_year" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#year_set").html(data); get_std_list(); }) } function get_data_upclassed() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "data_upclassed" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list_upclassed").html(data); }) }<file_sep>/modules/report/index.js var opPage = 'report'; $(document).ready(function() { }); function get_pdf_sara(){ $( "#form_pdf_sara" ).submit(); } function get_pdf_desirable(){ $( "#form_pdf_desirable" ).submit(); } function get_pdf_major(){ $( "#form_pdf_major" ).submit(); } function get_pdf_level(){ $( "#form_pdf_level" ).submit(); } function get_pdf_person_p(){ $( "#form_pdf_person_p" ).submit(); } function get_pdf_person_m(){ $( "#form_pdf_person_m" ).submit(); } <file_sep>/modules/menu/from.js document.writeln('<script type="text/javascript" src="assets/js/texteditor/texteditor.js"></script>'); document.writeln("<link href='assets/plugins/bootstrap3-wysihtml5/bootstrap3-wysihtml5.min.css' rel='stylesheet' type='text/css' />"); // document.writeln("<script type='text/javascript' src='http://bp.yahooapis.com/2.4.21/browserplus-min.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.gears.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.silverlight.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.flash.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.browserplus.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.html4.js'></script>"); document.writeln("<script type='text/javascript' src='assets/js/plupload/js/plupload.html5.js'></script>"); document.writeln("<script type='text/javascript' src='modules/menu/upload_boxIV.js'></script>"); document.writeln("<script type='text/javascript' src='modules/menu/upload_award.js'></script>"); // document.writeln("<script type='text/javascript' src='modules/menu/upload_photo.js'></script>"); // document.writeln("<script type='text/javascript' src='modules/menu/upload_keyword.js'></script>"); var opPage = 'menu'; $(document).ready(function() { get_data(); get_thumb(); get_award(); // initMap(); // get_photo(); // get_keyword(); }); function get_data(){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_data_from" }); formData.push({ "name": "data_id", "value": _get.id}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus) { // console.log(data); $('#DataID').val(_get.id); $('#boxI_name').val(data.boxI_name); $('#boxI_nameEn').val(data.boxI_nameEn); $('#boxII_name').val(data.boxII_name); $('#boxII_nameEn').val(data.boxII_nameEn); $('#boxIII_name').val(data.boxIII_name); $('#boxIII_nameEn').val(data.boxIII_nameEn); $('#boxIV_name').val(data.boxIV_name); $('#boxIV_nameEn').val(data.boxIV_nameEn); $('#boxI_desc').val(data.boxI_desc); $('#boxI_descEn').val(data.boxI_descEn); $('#boxII_desc').val(data.boxII_desc); $('#boxII_descEn').val(data.boxII_descEn); $('#boxIII_desc').val(data.boxIII_desc); $('#boxIII_descEn').val(data.boxIII_descEn); $('#boxIV_desc').val(data.boxIV_desc); $('#boxIV_descEn').val(data.boxIV_descEn); $('#tag_title').val(data.tag_title); $('#tag_keyword').val(data.tag_keyword); $('#tag_description').val(data.tag_description); $('#date_start_value').val(data.date_start_value); $('#date_end_value').val(data.date_end_value); $('#status').select2("val",data.status); }); } $(document).delegate('#btn__save', 'click', function(event) { var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "save_data" }); formData.push({ "name": "data_id", "value": _get.id}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { // console.log(data); // return false; window.location = 'index.php?op='+opPage+'-index&data=success'; }); }); $(document).delegate('#btn__preview', 'click', function(event) { $( "#frm_data" ).submit(); }); <file_sep>/modules/profile/backup/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_img"){ $status_get=$_GET['status_get']; echo $class_data->get_img($status_get); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data"){ echo $class_data->get_data(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day"){ $mouth=$_GET['mouth']; echo $class_data->get_day($mouth); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $day=$_POST['day']; $month=$_POST['month']; $years=$_POST['years']-543; $birthday=$years.'-'.$month.'-'.$day; $arr_sql[]="positionID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['positionID'])))."'"; $arr_sql[]="fname_th='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname_th'])))."'"; $arr_sql[]="lname_th='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname_th'])))."'"; $arr_sql[]="fname_en='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname_en'])))."'"; $arr_sql[]="lname_en='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname_en'])))."'"; $arr_sql[]="birthday='".chkhtmlspecialchars($InputFilter->clean_script(trim($birthday)))."'"; $arr_sql[]="study_history='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['study_history'])))."'"; $arr_sql[]="gender='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['gender'])))."'"; $arr_sql[]="blood_group='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['blood_group'])))."'"; $arr_sql[]="address='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['address'])))."'"; $arr_sql[]="position_name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['position_name'])))."'"; $arr_sql[]="department='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['department'])))."'"; $arr_sql[]="work='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['work'])))."'"; $arr_sql[]="more_detail='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['more_detail'])))."'"; $arr_sql[]="tell='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tell'])))."'"; $arr_sql[]="email='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['email'])))."'"; $class_data->update_data($arr_sql); }<file_sep>/modules/news/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "delete_news"){ $data_id=$_GET['data_id']; echo $class_data->delete_news($data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "delete_img_file"){ $data_id=$_GET['data_id']; echo $class_data->delete_img_file($data_id,$_GET['set_type']); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_news_detail"){ $news_id=$_GET['news_id']; echo $class_data->get_news_detail($news_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_news_list"){ echo $class_data->get_news_list(); } <file_sep>/modules/mobile_api/class_modules.php <?php class ClassData extends Databases { public function get_header_box($user_id){ $products_arr=array(); $products_arr["records"]=array(); $this->sql ="SELECT DISTINCT year FROM tbl_pp6 WHERE std_ID='$user_id' ORDER BY year "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year=$value['year']; $product_item=array( "key" => $key, "year" => $year, ); array_push($products_arr["records"], $product_item); } echo json_encode($products_arr); } public function get_table_box($user_id,$year){ $products_arr=array(); $products_arr["records"]=array(); $this->sql ="SELECT DISTINCT(term) as term,year,class_level,room FROM tbl_pp6 WHERE std_ID='$user_id' AND year='$year' ORDER BY term "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $term=$value['term']; $room=$value['room']; $class_level=$value['class_level']; $ClasslevelText=$this->getClasslevelText($class_level); if($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6'){ $class_level_status=1; $resaultGpa=$this->get_resaultGpaP($user_id,$term,$year); }else{ $class_level_status=2; $resaultGpa=$this->get_resaultGpaM($user_id,$term,$year); $resaultGpax=$this->get_resaultGpax($user_id,$term,$year); } $resaultSum=$this->get_resaultSum($user_id,$term,$year); $find_position=$this->find_position($year,$class_level,$room); arsort($find_position); $arrayValuePosition=$this->arrayValuePositionNew($find_position,$user_id); $product_item=array( "key" => $key, "term" => $term, "class_level" => $ClasslevelText, "room" => $room, "year" => $year, "resaultSum" => $resaultSum, "resaultGpa" => $resaultGpa, "resaultGpax" => $resaultGpax, "class_level_status" => $class_level_status, "std_position" => $arrayValuePosition, ); array_push($products_arr["records"], $product_item); } echo json_encode($products_arr); } public function arrayValuePositionNew($find_position,$std_ID){ $result = array(); $pos = $real_pos = 0; $prev_score = -1; foreach ($find_position as $exam_n => $score) { $real_pos += 1;// Natural position. $pos = ($prev_score != $score) ? $real_pos : $pos;// If I have same score, I have same position in ranking, otherwise, natural position. $result[$exam_n] = array( "score" => $score, "position" => $pos, "exam_no" => $exam_n ); $prev_score = $score;// update last score. } return $result[$std_ID]["position"]; } public function find_position($year_data,$class_level_data,$room){ $data_response = array(); $this->sql ="SELECT distinct(tbl_pp6.std_ID) as std_pp6_id,tbl_pp6.DataID as pp6_id FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_pp6.year='$year_data' AND tbl_pp6.room='$room' AND tbl_pp6.class_level='$class_level_data' AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $find_gpa_sum=0; $score_final_count=0; foreach($this->rows as $key => $value) { $std_pp6_id=$value['std_pp6_id']; $pp6_id=$value['pp6_id']; if($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6'){ $data_big_std= $this->get_data_big_std_p($std_pp6_id,$pp6_id); }else{ $data_big_std= $this->get_data_big_std_m($std_pp6_id,$pp6_id); } $test[$std_pp6_id] = $data_big_std; /* $pick_poi= $this->get_pick_poi($registed_courseID,$stdID,$term_data,$year); $grade_text=$this->get_grade_text($score_exam,$pick_poi); $unit=$this->get_unit($registed_courseID); $find_gpa=$grade_text*$unit; $find_gpa_sum=$find_gpa_sum+$find_gpa;*/ //$tt.=$stdID.'='.$insert.','; } //$total= $final_poi+$mid_poi; return $test; } public function get_data_big_std_p($std_pp6_id,$pp6_id){ $this->sql ="SELECT sum(score_total) as sumed FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); return $this->rows[0]['sumed']; } public function get_data_big_std_m($std_pp6_id,$pp6_id){ $this->sql ="SELECT unit,score_total FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND score_total!=-1 "; $this->select(); $this->setRows(); $find_row_sum=0; foreach($this->rows as $key => $value) { $unit=$value['unit']; $score_total=$value['score_total']; $grade= $this->get_grade($score_total); $find_row_sum=$find_row_sum+($unit*$grade); } $this->sql ="SELECT SUM(unit) as unit_sum FROM tbl_pp6,tbl_sub_pp6 WHERE tbl_pp6.DataID=tbl_sub_pp6.pp6_ID AND tbl_sub_pp6.pp6_ID=$pp6_id AND tbl_sub_pp6.status=1 "; $this->select(); $this->setRows(); $unit_sum=$this->rows[0]['unit_sum']; return $find_row_sum/$unit_sum; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_resaultGpax($user_id,$term,$year){ $this->sql ="SELECT score_total,unit FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year<=$year AND term<=$term ) "; $this->select(); $this->setRows(); $score_row_sum=0; $unit_count=0; foreach($this->rows as $key => $value) { $score_total=$value['score_total']; $unit=$value['unit']; if($score_total!=-1){ $grade=$this->get_grade_text($score_total); $score_row=$grade*$unit; $score_row_sum=$score_row_sum+$score_row; } $unit_count=$unit_count+$unit; } return number_format($score_row_sum/$unit_count,2); } public function get_resaultGpaM($user_id,$term,$year){ $this->sql ="SELECT score_total,unit FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $score_row_sum=0; $unit_count=0; foreach($this->rows as $key => $value) { $score_total=$value['score_total']; $unit=$value['unit']; if($score_total!=-1){ $grade=$this->get_grade_text($score_total); $score_row=$grade*$unit; } $score_row_sum=$score_row_sum+$score_row; $unit_count=$unit_count+$unit; } return number_format($score_row_sum/$unit_count,2); } public function get_resaultGpaP($user_id,$term,$year){ $this->sql ="SELECT SUM(score_total) as score_total FROM tbl_sub_pp6 WHERE score_total!=-1 AND status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $score_total=$this->rows[0]['score_total']; $this->sql ="SELECT COUNT(*) as num_row FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; $resaultGpaFind=$score_total/$num_row; return $resaultGpaFind; } public function get_resaultSum($user_id,$term,$year){ $this->sql ="SELECT SUM(score_total) as score_total FROM tbl_sub_pp6 WHERE score_total!=-1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) "; $this->select(); $this->setRows(); $score_total=$this->rows[0]['score_total']; if($score_total=='' || $score_total==NULL){ $score_total=0; } return $score_total; } public function get_grade_text($score_exam,$score_pick){ $total=$score_exam+$score_pick; if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } public function get_subject_list($user_id,$term,$year){ $products_arr=array(); $products_arr["records"]=array(); $this->sql =" SELECT class_level FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE std_ID=$user_id AND year='$year' AND term='$term' ) ORDER BY status ASC "; $this->select(); $this->setRows(); $sum_course_score=0; $sum_cproportion_score=0; $find_gpa_sum=0; $find_unit_sum=0; $grade_sum=0; $count_loop=0; foreach($this->rows as $key => $value) { $courseID=$value['courseID']; $name=$value['name']; $status=$value['status']; if($status==1){ if($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6'){ $name=$this-> get_department($value['department']); }else{ $name=$courseID; } $unit=$value['unit']; $score_total=$value['score_total']; if($score_total==-1){ $score_total=$value['score_mid']+$value['score_final']; $grade='ร'; }else{ $grade=$this->get_grade_text($score_total); } }else{ $score_total='-'; $unit='-'; $score_attend=$value['score_attend']; if($score_attend==-1){ $grade='ไม่ผ่าน'; }else{ $grade='ผ่าน'; } } $product_item=array( "key" => $key, "name" => $name, "score_total" => $score_total, "unit" => $unit, "grade" => $grade, ); array_push($products_arr["records"], $product_item); } echo json_encode($products_arr); } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพและเทคโนโลยี'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; default: $department=''; } return $department; } public function getClasslevelText($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/add_delete_course/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "getdata_edit"){ $data_id = $_GET['data_id']; echo $class_data->getdata_edit($data_id); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "data_remove"){ $data_val = $_POST['data_val']; echo $class_data->get_data_delete($data_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data"){ $arr_search_val['courseID_search'] = $_GET['courseID_search']; $arr_search_val['department_search'] = $_GET['department_search']; $arr_search_val['class_level_search'] = $_GET['class_level_search']; $arr_search_val['status'] = $_GET['status']; echo $class_data->get_data($arr_search_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data_edit"){ $user_add=$_SESSION['ss_user_id']; $data_id_course=$_POST['data_id_course']; $arr_sql[]="courseID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['courseID_edit'])))."'"; $arr_sql[]="user_add='".chkhtmlspecialchars($InputFilter->clean_script(trim($user_add)))."'"; $arr_sql[]="name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['name'])))."'"; $arr_sql[]="class_level='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['class_level'])))."'"; $arr_sql[]="unit='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['unit'])))."'"; $arr_sql[]="department='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['department'])))."'"; $arr_sql[]="hr_learn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['hr_learn'])))."'"; $arr_sql[]="status='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['course_status'])))."'"; $status_form=$_POST['course_status']; if ($status_form==11 || $status_form==12) { $arr_sql[]="status=1"; $arr_sql[]="status_form='".$status_form."'"; }else{ $arr_sql[]="status='2'"; $arr_sql[]="status_form='".$_POST['dev_mode_value_add_edit']."'"; } echo $class_data->update_data($arr_sql,$data_id_course); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $user_add=$_SESSION['ss_user_id']; $arr_sql["courseID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['courseID'])))."'"; $arr_sql["name"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['name'])))."'"; $arr_sql["class_level"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['class_level'])))."'"; $arr_sql["unit"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['unit'])))."'"; $arr_sql["department"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['department'])))."'"; $arr_sql["hr_learn"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['hr_learn'])))."'"; $arr_sql["user_add"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($user_add)))."'"; $status_form=$_POST['course_status']; if ($status_form==11 || $status_form==12) { $arr_sql["status"]=1; $arr_sql["status_form"]=$status_form; }else{ $arr_sql["status"]=2; $arr_sql["status_form"]=$_POST['dev_mode_value_add']; } $arr_sql["cdate"]="now()"; echo $class_data->insert_data($arr_sql); }<file_sep>/modules/conclusion/form/learning_result_final_m.php <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="../../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <link href="../../../assets/css/print_conclusion.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" rel="stylesheet" type="text/css"> <script type="text/javascript" src="../../../assets/js/jquery.js"></script> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 2px; } --> </style> <?php @session_start(); include ('../logo.php'); include ('learning_result_footer.php'); require_once('../../../init.php'); include('../class_modules/learing_resualt_final_m.php'); $class_data = new ClassData(); $class_level=$_GET['class_level']; $room=$_GET['room']; $year=$_GET['year']; $term=$_GET['term']; $final_data_m=$class_data->get_final_data_m($class_level,$room,$year,$term,$image_logo,$footer_text_detail,$footer_text_cen); ?> <div style="background-color: rgb(82, 86, 89);min-height: 100%"> <div style="font-size:16px;background-color: white;min-height: 100%;padding-right: 30px; padding-left: 30px;margin-right: auto;margin-left: auto;width: 100%"> <?php echo $final_data_m['std_list']; ?> </div> </div> <script> $(document).ready(function() { get_print(); setTimeout(window.close, 0); }); function get_print() { window.print(); } </script><file_sep>/modules/regis_course_teaching/back/New folder/class_modules.php <?php class ClassData extends Databases { public function get_term_year_now(){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $data_response['term']=$this->rows[0]['term']; $data_response['year']=$this->rows[0]['year']; echo json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_teaching_std_id($std_ID,$data_id){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$data_id AND stdID='$std_ID' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_teaching_student_only($data_id,$data_room){ $data_response = array(); $this->sql ="SELECT count(*) as count_loop_std FROM tbl_student WHERE room='$data_room' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID = $data_id ) "; $this->select(); $this->setRows(); $count_loop_std=$this->rows[0]['count_loop_std']; if ($count_loop_std!=0) { $this->sql ="SELECT * FROM tbl_student WHERE room='$data_room' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID = $data_id ) ORDER BY CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $teaching_std_id=$this->get_teaching_std_id($std_ID,$data_id); $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $fname=$value['fname']; $lname=$value['lname']; $class_level_data=$value['class_level']; $class_level=$this->get_class_level($class_level_data); $room =$value['room']; $data_response['std_list_only'].=' <tr> <td style="text-align:center;">'.$std_ID.'</td> <td style="text-align:left;padding-left:16%;">'.$name_title.$fname.' '.$lname.'</td> <td style="text-align:center;">'. $class_level.'</td> <td style="text-align:center;">'.$room.'</td> <td style="text-align:center;"> <div data-id="'.$teaching_std_id.'" class="bt_delete" aria-hidden="true" data-toggle="modal" data-target="#modalConfirmReStd"> <span class="glyphicon glyphicon-trash edit-icon-table" ></span> </div> </td> </tr> '; } }else{ $data_response['std_list_only']=''; } return json_encode($data_response); } public function get_course_teaching_student($data_id){ $data_response = array(); $sql="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE DataID=$data_id ) "; $this->sql =$sql; $this->select(); $this->setRows(); $data_response['course_data_ID']=$this->rows[0]['DataID']; $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; return json_encode($data_response); } public function get_score_before_after($course_id,$cumulative_before_mid,$cumulative_after_mid){ $data_response = array(); $this->sql ="SELECT COUNT(*) as num_of_course FROM tbl_objective_conclude WHERE courseID=$course_id "; $this->select(); $this->setRows(); $num_of_course=$this->rows[0]['num_of_course']; if($num_of_course!="" || $num_of_course==0){ $this->sql ="SELECT COUNT(DataID) as score_count_before FROM tbl_objective_conclude WHERE courseID=$course_id AND proportion_status=1 "; $this->select(); $this->setRows(); $score_count_before=$this->rows[0]['score_count_before']; $data_response['score_count_before']=$this->rows[0]['score_count_before']; if ($score_count_before!=0) { $this->sql ="SELECT SUM(score) as score_sum_before FROM tbl_objective_conclude WHERE courseID=$course_id AND proportion_status=1 "; $this->select(); $this->setRows(); $data_response['score_sum_before']=$cumulative_before_mid-$this->rows[0]['score_sum_before']; }else{ $data_response['score_sum_before']="0"; } $this->sql ="SELECT COUNT(DataID) as score_count_after FROM tbl_objective_conclude WHERE courseID=$course_id AND proportion_status=2 "; $this->select(); $this->setRows(); $score_count_after=$this->rows[0]['score_count_after']; $data_response['score_count_after']=$this->rows[0]['score_count_after']; if ($score_count_after!=0) { $this->sql ="SELECT SUM(score) as score_sum_after FROM tbl_objective_conclude WHERE courseID=$course_id AND proportion_status=2 "; $this->select(); $this->setRows(); $data_response['score_sum_after']=$cumulative_after_mid-$this->rows[0]['score_sum_after']; }else{ $data_response['score_sum_after']="0"; } }else{ $data_response['score_sum_before']=0; $data_response['score_sum_after']=0; } return $data_response; } public function update_exam_mid_object($data_id_first,$objective_conclude_id){ $this->sql ="SELECT count(*) as num_row FROM tbl_exam_mid_object WHERE courseID=$data_id_first AND objective_conclude=$objective_conclude_id "; $this->select(); $this->setRows(); $num_row= $this->rows[0]['num_row']; if($num_row==0){ $this->sql ="INSERT INTO tbl_exam_mid_object(courseID,objective_conclude) VALUES($data_id_first,$objective_conclude_id); "; $this->query(); }else{ $this->sql ="DELETE FROM tbl_exam_mid_object WHERE courseID=$data_id_first AND objective_conclude=$objective_conclude_id "; $this->query(); } } public function update_exam_final_object($data_id_first,$objective_conclude_id){ $this->sql ="SELECT count(*) as num_row FROM tbl_exam_final_object WHERE courseID=$data_id_first AND objective_conclude=$objective_conclude_id "; $this->select(); $this->setRows(); $num_row= $this->rows[0]['num_row']; if($num_row==0){ $this->sql ="INSERT INTO tbl_exam_final_object(courseID,objective_conclude) VALUES($data_id_first,$objective_conclude_id); "; $this->query(); }else{ $this->sql ="DELETE FROM tbl_exam_final_object WHERE courseID=$data_id_first AND objective_conclude=$objective_conclude_id "; $this->query(); } } public function get_exam_mid_object($data_id_first,$objective_conclude_id){ $this->sql ="SELECT count(*) as num_exam_mid_object FROM tbl_exam_mid_object WHERE courseID=$data_id_first AND objective_conclude=$objective_conclude_id "; $this->select(); $this->setRows(); return $this->rows[0]['num_exam_mid_object']; } public function get_exam_final_object($data_id_first,$objective_conclude_id){ $this->sql ="SELECT count(*) as num_exam_final_object FROM tbl_exam_final_object WHERE courseID=$data_id_first AND objective_conclude=$objective_conclude_id "; $this->select(); $this->setRows(); return $this->rows[0]['num_exam_final_object']; } public function get_exam_object($data_id_first){ $this->sql ="SELECT status FROM tbl_add_delete_course WHERE DataID=$data_id_first "; $this->select(); $this->setRows(); $data_response['status']=$this->rows[0]['status']; $this->sql ="SELECT DataID,no_order FROM tbl_objective_conclude WHERE courseID=$data_id_first ORDER BY no_order ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $no_order= $value['no_order']; $objective_conclude_id= $value['DataID']; $exam_mid_object=$this->get_exam_mid_object($data_id_first,$objective_conclude_id); if($exam_mid_object==1){ $status_mid="checked"; }else{ $status_mid=""; } $data_response['object_list_mid'].=' <div class="col-sm-3"> <div class="checkbox"> <label><input type="checkbox" onclick="update_exam_mid_object('.$data_id_first.','.$objective_conclude_id.')" '.$status_mid.'>ตัวชี้วัดที่ '.$no_order.'</label> </div> </div> '; $exam_final_object=$this->get_exam_final_object($data_id_first,$objective_conclude_id); if($exam_final_object==1){ $status_final="checked"; }else{ $status_final=""; } $data_response['object_list_final'].=' <div class="col-sm-3"> <div class="checkbox"> <label><input type="checkbox" onclick="update_exam_final_object('.$data_id_first.','.$objective_conclude_id.')" '.$status_final.'>ตัวชี้วัดที่ '.$no_order.'</label> </div> </div> '; } echo json_encode($data_response); } public function get_propotion_objective($data_id_first){ $data_response = array(); $this->sql ="SELECT class_level FROM tbl_add_delete_course WHERE DataID=$data_id_first "; $this->select(); $this->setRows(); $class_level_course=$this->rows[0]['class_level']; if ($class_level_course=='p1' || $class_level_course=='p2' || $class_level_course=='p3' || $class_level_course=='p4' || $class_level_course=='p5' || $class_level_course=='p6') { $text_desc_1='ก่อนวัดผลกลางปี'; $text_desc_2='หลังวัดผลกลางปี'; }else{ $text_desc_1='ก่อนกลางภาค'; $text_desc_2='หลังกลางภาค'; } $data_response = array(); $this->sql ="SELECT count(*) as num_row_propotion FROM tbl_proportion WHERE courseID=$data_id_first "; $this->select(); $this->setRows(); $num_row_propotion=$this->rows[0]['num_row_propotion']; if ($num_row_propotion!=0) { $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$data_id_first "; $this->select(); $this->setRows(); $cumulative_before_mid=$this->rows[0]['cumulative_before_mid']; $cumulative_after_mid=$this->rows[0]['cumulative_after_mid']; $data_response['cumulative_before_mid']=$cumulative_before_mid; $data_response['cumulative_after_mid']=$cumulative_after_mid; $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; }else{ $data_response['cumulative_before_mid']=""; $data_response['cumulative_after_mid']=""; $data_response['mid_exam']=""; $data_response['final_exam']=""; } $this->sql ="SELECT count(*) as num_row_ob FROM tbl_objective_conclude WHERE courseID=$data_id_first "; $this->select(); $this->setRows(); $num_row_ob=$this->rows[0]['num_row_ob']; if ($num_row_ob!=0) { $score_before_after=$this->get_score_before_after($data_id_first,$cumulative_before_mid,$cumulative_after_mid); $data_response['score_sum_before']=$score_before_after['score_sum_before']; $data_response['score_sum_after']=$score_before_after['score_sum_after']; $this->sql ="SELECT count(*) num_loop FROM tbl_objective_conclude WHERE courseID=$data_id_first "; $this->select(); $this->setRows(); $num_loop=$this->rows[0]['num_loop']; $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$data_id_first ORDER BY no_order "; $this->select(); $this->setRows(); $set_loop_id=1; foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $no_order= $value['no_order']; $detail= $value['detail']; $score= $value['score']; $proportion_status= $value['proportion_status']; if ($proportion_status==1) { $object_list=' <option selected value="1">'.$text_desc_1.'</option> <option value="2">'.$text_desc_2.'</option> '; }elseif($proportion_status==2){ $object_list=' <option value="1">'.$text_desc_1.'</option> <option selected value="2">'.$text_desc_2.'</option> '; } $data_response['objective_list'].=' <tr> <td width="4%">ข้อที่</td> <td width="7%"> <div class="input-group"> <input name="no_order[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value="'.$no_order.'"> </div> </td> <td width="12%" style="padding-left: 30px;">ตัวชี้วัด</td> <td width="40%"> <div class="input-group" style="width: 100%;margin-left: -20px;"> <input name="detail[]" type="text" class="form-control form-set-search exam_chk_dis" aria-describedby="basic-addon1" value="'.$detail.'"> </div> </td> <td width="25%"> <select name="object_list_data[]" class="form-control search-course-depart object_list_data" style="width: 100%;"> '.$object_list.' </select> </td> <td width="5%" style="padding-left: 30px;">คะแนน</td> <td width="15%" style="padding-left: 5px;"> <div class="input-group"> <input name="score_data[]" type="text" class="form-control form-set-search score_data" aria-describedby="basic-addon1" value="'.$score.'" > </div> </td> <td style="padding-left: 15px;"> <div data-toggle="modal" data-target="#modalConRemoveobjective" data-id="'.$DataID.'" class="btn-search btn_delete_objective_first" style="margin-top: -6px;"> <span class="text-icon" style="margin-left: 3px;">-</span> </div> </td> </tr> '; if ($num_loop==$set_loop_id) { $data_response['objective_data_all_id'].=$DataID; }else{ $data_response['objective_data_all_id'].=$DataID.'-'; } $set_loop_id++; } }else{ $data_response['objective_list']=''; } return json_encode($data_response); } public function insert_data_teaching($insert,$term_search,$year_search){ $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$insert AND year='$year_search' AND term='$term_search' "; $this->select(); $this->setRows(); $long_course=$this->rows[0]['DataID']; $cdate=date("Y-m-d"); $this->sql ="SELECT count(*) as row_data_1 FROM tbl_registed_course_teaching WHERE registed_courseID=$long_course "; $this->select(); $this->setRows(); $row_data_1=$this->rows[0]['row_data_1']; if ($row_data_1==0) { $this->sql = "INSERT INTO tbl_registed_course_teaching(registed_courseID,cdate) VALUES($long_course,'$cdate')"; $this->query(); $new_id = $this->insertID(); } } public function insert_data_proportion($insert,$course_id){ $this->sql ="SELECT count(*) as row_data_2 FROM tbl_proportion WHERE courseID=$course_id "; $this->select(); $this->setRows(); $row_data_2=$this->rows[0]['row_data_2']; if ($row_data_2!=0) { $this->sql ="DELETE FROM tbl_proportion WHERE courseID = $course_id"; $this->query(); } $this->sql = "INSERT INTO tbl_proportion(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $new_id = $this->insertID(); } public function data_remove_std($data_val){ $data_response = array(); $arr_id = explode(",", $data_val); $num=0; for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="DELETE FROM tbl_course_teaching_std WHERE DataID = '$arr_id[$i]'"; $this->query(); $num=$num+$i; } return $num; } public function data_remove_objective($data_val){ $this->sql ="DELETE FROM tbl_objective_conclude WHERE DataID=$data_val" ; $this->query(); return $num; } public function get_data_delete($data_val){ list($data_id,$room) = split('[-]', $data_val); /* $this->sql ="DELETE FROM tbl_registed_course_teaching WHERE registed_courseID=$data_id" ; $this->query();*/ if ($room=='') { $this->sql ="DELETE FROM tbl_registed_course_teaching WHERE registed_courseID=$data_id" ; $this->query(); }else{ $this->sql ="DELETE FROM tbl_course_teaching_std WHERE registed_courseID=$data_id AND stdID IN( SELECT std_ID FROM tbl_student WHERE room='$room' ) " ; $this->query(); } /* $this->sql ="DELETE FROM tbl_course_teaching_std WHERE stdID in( SELECT std_ID FROM tbl_student WHERE room='$room' ) AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE DataID=$data_id ) "; $this->query();*/ return $room; } function get_unit_data($unit_data){ if ($unit_data==0.0 | $unit_data==9.9) { $unit="-"; }else{ $unit=$unit_data; } return $unit; } public function get_term($unit_data,$status_data,$term){ if ($unit_data==0) { if ($status_data==1) { $term="1,2"; }else{ $term=$term; } }else{ $term=$term; } return $term; } public function get_year_data($registed_courseID){ $this->sql ="SELECT * FROM tbl_registed_course WHERE DataID=$registed_courseID "; $this->select(); $this->setRows(); return $this->rows[0]['year']; } public function get_term_data($registed_courseID){ $this->sql ="SELECT * FROM tbl_registed_course WHERE DataID=$registed_courseID "; $this->select(); $this->setRows(); return $this->rows[0]['term']; } public function chk_find_std($registed_courseID,$term){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE DataID=$registed_courseID ) "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $long_course=$this->rows[0]['courseID']; $name_course=$this->rows[0]['name']; $unit_course=$this->rows[0]['unit']; $hr_learn_course=$this->rows[0]['hr_learn']; $class_level_course=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status=$this->rows[0]['status']; $class_level=$this->get_class_level($class_level_course); $unit_data=$this->get_unit_data($unit_course); $status_data=$this->rows[0]['status']; $term=$this->get_term_data($registed_courseID); $year_data=$this->get_year_data($registed_courseID); $term_new=$this->get_term($unit_course,$status_data,$term); if ($class_level_course=='p1' || $class_level_course=='p2' || $class_level_course=='p3' || $class_level_course=='p4' || $class_level_course=='p5' || $class_level_course=='p6') { $class_level_status='p'; }else{ $class_level_status='m'; } $this->sql ="SELECT COUNT(distinct room) as num_room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $num_room=$this->rows[0]['num_room']; if ($num_room!=0) { $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data.=' <tr style="text-align:center;"> <td style="text-align:left;padding-left:3%;">'.$long_course.'</td> <td style="text-align:left;padding-left:8%;"><a href="index.php?op=regis_course_teaching-edit_student&id='.$registed_courseID.'&room='.$room.'&courseID='.$DataID.'&term='.$term_new.'&year='.$year_data.'&status='.$status.'&class_level_status='.$class_level_status.'">'.$name_course.'</a></td> <td>'.$unit_data.'</td> <td>'.$hr_learn_course.'</td> <td>'.$class_level .'</td> <td>'.$room.'</td> <td>'.$term_new.'</td> <td>'.$year_data.'</td> <td> <div class="bt_delete" data-id="'.$registed_courseID.'-'.$room.'" aria-hidden="true" data-toggle="modal" data-target="#modalConfirm"> <span class="glyphicon glyphicon-trash edit-icon-table"></span> </div> </td> </tr> '; } }else{ $data.=' <tr style="text-align:center;"> <td style="text-align:left;padding-left:3%;">'.$long_course.'</td> <td style="text-align:left;padding-left:8%;"><a href="index.php?op=regis_course_teaching-edit_student&id='.$registed_courseID.'&room=0&courseID='.$DataID.'&term='.$term_new.'&year='.$year_data.'">'.$name_course.'</a></td> <td>'.$unit_data.'</td> <td>'.$hr_learn_course.'</td> <td>'.$class_level .'</td> <td>ยังไม่เลือกนักเรียน</td> <td>'.$term_new.'</td> <td>'.$year_data.'</td> <td> <div class="bt_delete" data-id="'.$registed_courseID.'" aria-hidden="true" data-toggle="modal" data-target="#modalConfirm"> <span class="glyphicon glyphicon-trash edit-icon-table" style="top:-1px;"></span> </div> </td> </tr> '; } return $data; } public function get_registed_course_teaching(){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $year=$this->rows[0]['year']; $term=$this->rows[0]['term']; $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year' AND DataID in( SELECT regis_course_id FROM tbl_course_teacher WHERE teacher_id=$user_id ) ) "; $this->select(); $this->setRows(); $num=1; foreach($this->rows as $key => $value) { $registed_courseID=$value['registed_courseID']; $chk_find.=$this->chk_find_std($registed_courseID,$term); $data.='number '.$registed_courseID.'is ' .$chk_find; $num++; } return json_encode($chk_find); } public function data_add_std($data_val,$course_id,$term_search,$year_search){ $sql="SELECT * FROM tbl_registed_course WHERE courseID=$course_id AND year='$year_search' AND term='$term_search' "; $this->sql =$sql; $this->select(); $this->setRows(); $courseID=$this->rows[0]['DataID']; /*$sql="SELECT * FROM tbl_add_delete_course WHERE DataID=$course_id "; $this->sql =$sql; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; */ $cdate=date("Y-m-d"); $arr_id = explode(",", $data_val); $num=0; for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="INSERT INTO tbl_course_teaching_std(registed_courseID,stdID,cdate) VALUES($courseID,'{$arr_id[$i]}','$cdate')"; $this->query(); $new_id = $this->insertID(); /* if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { for ($j=1; $j <=40 ; $j++) { $this->sql ="INSERT INTO tbl_attend_class(course_teaching_stdID,week,score_status) VALUES($new_id,$j,0)"; $this->query(); } }else{ for ($j=1; $j <=20 ; $j++) { $this->sql ="INSERT INTO tbl_attend_class(course_teaching_stdID,week,score_status) VALUES($new_id,$j,0)"; $this->query(); } }*/ $num=$num+$i; } return $num; } public function get_std_list($id_std_search,$search_class_modal,$search_room_modal,$course_id,$term_search,$year_search){ $sql="SELECT * FROM tbl_add_delete_course WHERE DataID=$course_id "; $this->sql =$sql; $this->select(); $this->setRows(); $status_form=$this->rows[0]['status_form']; $sql="SELECT * FROM tbl_registed_course WHERE courseID=$course_id AND term='$term_search' AND year='$year_search' "; $this->sql =$sql; $this->select(); $this->setRows(); $registed_courseID=$this->rows[0]['DataID']; $data_response = array(); $condition_sql.="std_ID is not null "; if ($id_std_search=="" && $search_class_modal=="" && $search_room_modal=="") { $condition_sql.=" AND class_level='p1' AND room='1' "; } if (isset($id_std_search) && $id_std_search != "") { $condition_sql .= " AND ( std_ID LIKE '%{$id_std_search}%') "; } if (isset($search_class_modal) && $search_class_modal != "") { $condition_sql .= " AND ( class_level = '$search_class_modal') "; } if (isset($search_room_modal) && $search_room_modal != "") { $condition_sql .= " AND ( room = '$search_room_modal') "; } $this->sql ="SELECT count(*) num_row FROM tbl_student WHERE $condition_sql "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row!=0) { $sql="SELECT * FROM tbl_student WHERE $condition_sql ORDER BY class_level ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN std_ID THEN 4 END "; $this->sql =$sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; //$data_response['asd']=$std_ID; $name_title=$value['name_title']; $std_ID_status=$this->chk_std_id($std_ID,$registed_courseID,$status_form,$term_search,$year_search,$name_title); $name_title_con=$this->get_name_title($name_title); $fname=$value['fname']; $lname=$value['lname']; $class_level_data=$value['class_level']; $class_level=$this->get_class_level($class_level_data); $room=$value['room']; if ($std_ID_status==0) { $data_response['std_list'].=' <tr> <td style="text-align: center;"> <input class="checkbox_data" type="checkbox" value="'.$std_ID.'" name="checkbox_delete[]" id="checkbox'.$std_ID.'"> </td> <td style="text-align: center;">'.$std_ID.'</td> <td style="text-align:left;pl-20">'.$name_title_con.'</td> <td style="text-align:left;pl-20">'.$fname.'</td> <td style="text-align:left;pl-20">'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> </tr> '; }else{ $data_response['std_list'].=''; } } }else{ $data_response['std_list'].=''; } $data_response['std_ID_status']=$registed_courseID; return json_encode($data_response); } public function chk_std_id($std_ID_status,$registed_courseID,$status_form,$term_search,$year_search,$name_title){ if ($status_form==21) { $sql="SELECT * FROM tbl_registed_course WHERE term ='$term_search' AND year='$year_search' AND courseID in( SELECT DataID FROM tbl_add_delete_course WHERE status_form=21 ) "; $this->sql =$sql; $this->select(); $this->setRows(); $count_data_set=0; foreach($this->rows as $key => $value) { $count_std_choomnoom=$this->get_count_std_choomnoom($value['DataID'],$std_ID_status); $count_data_set=$count_data_set+$count_std_choomnoom; } $data=$count_data_set; }else if($status_form==22){ if ($name_title=='dekying') { $data=1; }else{ $data=0; } }else if($status_form==23){ if ($name_title=='dekying') { $data=0; }else{ $data=1; } }else{ $sql="SELECT count(*) as num_row_status FROM tbl_course_teaching_std WHERE stdID='$std_ID_status' AND registed_courseID=$registed_courseID "; $this->sql =$sql; $this->select(); $this->setRows(); $data= $this->rows[0]['num_row_status']; } return $data; } public function get_count_std_choomnoom($regis_id,$std_ID_status){ $sql="SELECT count(*) as num_row FROM tbl_course_teaching_std WHERE stdID='$std_ID_status' AND registed_courseID=$regis_id "; $this->sql =$sql; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_name_to_add_std($data_id_first,$registed_course_id,$term_search,$year_search){ $data_response = array(); $sql="SELECT * FROM tbl_add_delete_course WHERE DataID=$data_id_first "; $this->sql =$sql; $this->select(); $this->setRows(); $data_response['name']=$this->rows[0]['name']; $data_response['status']=$this->rows[0]['status']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data_response['class_level_status']='p'; }else{ $data_response['class_level_status']='m'; } if ($registed_course_id=="") { $registed_course_id=$this->get_registed_course_id($data_id_first,$term_search,$year_search); } $this->sql ="SELECT count(*) as num_row FROM tbl_registed_course_teaching WHERE registed_courseID=$registed_course_id "; $this->select(); $this->setRows(); $data_response['num_row']=$this->rows[0]['num_row']; return json_encode($data_response); } public function search_course_class($department_search,$class_level_search,$term_search,$year_search){ $data_response = array(); $condition_sql="DataID > 0"; $condition_sql_date="DataID > 0"; if (isset($department_search) && $department_search != "") { if ($department_search=="dev_mode") { $condition_sql .= " AND ( status=2 ) "; }else{ $condition_sql .= " AND ( department = '$department_search') "; } } if (isset($class_level_search) && $class_level_search != "") { $condition_sql .= " AND ( class_level = '$class_level_search') "; } if (isset($term_search) && $term_search != "") { $condition_sql_date .= " AND ( term = '$term_search') "; } if (isset($year_search) && $year_search != "") { $condition_sql_date .= " AND ( year = '$year_search') "; } /*$year_now=date("Y"); $year_now_set=$year_now+543;*/ $this->sql ="SELECT count(*) as num_row_data FROM tbl_add_delete_course WHERE $condition_sql AND DataID in( SELECT courseID FROM tbl_registed_course WHERE $condition_sql_date ) "; $this->select(); $this->setRows(); $num_row_data=$this->rows[0]['num_row_data']; if ($num_row_data!=0) { $sql="SELECT * FROM tbl_add_delete_course WHERE $condition_sql AND DataID in( SELECT courseID FROM tbl_registed_course WHERE $condition_sql_date ) ORDER BY courseID ASC "; $this->sql =$sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID=$value['courseID']; if ($key==0) { $data_response['data_id_first']=$DataID; $data_response['registed_course_id']=$this->get_registed_course_id($DataID,$term_search,$year_search); } $data_response['dropdown_list'].=' <option value="'.$DataID.'">'.$courseID.'</option> '; } }else{ $data_response['dropdown_list']='<option>ไม่พบรหัสวิชา</option>'; $data_response['course_name']='ไม่พบรายวิชา'; $data_response['data_id_first']=""; } echo json_encode($data_response); } public function hide_class_std($data_id_first){ $data_response = array(); $sql="SELECT * FROM tbl_add_delete_course WHERE DataID=$data_id_first "; $this->sql =$sql; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=="p1") { $data_response='<option value="p1"> ป.1</option>'; }elseif($class_level=="p2"){ $data_response='<option value="p2"> ป.2</option>'; }elseif($class_level=="p3"){ $data_response='<option value="p3"> ป.3</option>'; }elseif($class_level=="p4"){ $data_response='<option value="p4"> ป.4</option>'; }elseif($class_level=="p5"){ $data_response='<option value="p5"> ป.5</option>'; }elseif($class_level=="p6"){ $data_response='<option value="p6"> ป.6</option>'; }elseif($class_level=="m1"){ $data_response='<option value="m1"> ม.1</option>'; }elseif($class_level=="m2"){ $data_response='<option value="m2"> ม.2</option>'; }elseif($class_level=="m3"){ $data_response='<option value="m3"> ม.3</option>'; }elseif($class_level=="m4"){ $data_response='<option value="m4"> ม.4</option>'; }elseif($class_level=="m5"){ $data_response='<option value="m5"> ม.5</option>'; }elseif($class_level=="m6"){ $data_response='<option value="m6"> ม.6</option>'; } return json_encode($data_response); } public function get_registed_course_id($courseID,$term_search,$year_now_set){ $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$courseID AND year='$year_now_set' AND term='$term_search' "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; return $DataID; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } } ?><file_sep>/modules/attend_class/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "add_attend"){ $value_loop=$_GET['value_loop']; $set_attend_day_id=$_GET['set_attend_day_id']; $course_teaching_stdID=$_GET['course_teaching_stdID']; $length_list_val=$_GET['length_list_val']; if ($value_loop==3) { $attend_value_1=$_GET['attend_value_1']; $attend_value_2=$_GET['attend_value_2']; $attend_value_3=$_GET['attend_value_3']; echo $class_data->add_attend($value_loop,$course_teaching_stdID,$set_attend_day_id,$length_list_val,$attend_value_1,$attend_value_2,$attend_value_3); }elseif($value_loop==2){ $attend_value_1=$_GET['attend_value_1']; $attend_value_2=$_GET['attend_value_2']; echo $class_data->add_attend($value_loop,$course_teaching_stdID,$set_attend_day_id,$length_list_val,$attend_value_1,$attend_value_2); }elseif($value_loop==1){ $attend_value_1=$_GET['attend_value_1']; echo $class_data->add_attend($value_loop,$course_teaching_stdID,$set_attend_day_id,$length_list_val,$attend_value_1); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "insert_value_in_attend"){ $value=$_GET['value']; $week=$_GET['week']; $set_attend_day_id=$_GET['set_attend_day_id']; $course_teaching_stdID=$_GET['course_teaching_stdID']; $registed_course_id=$_GET['registed_course_id']; $attend_class_week_listID=$_GET['attend_class_week_listID']; echo $class_data->insert_value_in_attend($registed_course_id,$value,$week,$set_attend_day_id,$course_teaching_stdID,$attend_class_week_listID); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "set_hr"){ $registed_course_id=$_GET['registed_course_id']; $value_day=$_GET['value_day']; $hr_set=$_GET['hr_set']; echo $class_data->set_hr($registed_course_id,$value_day,$hr_set); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "set_day"){ $registed_course_id=$_GET['registed_course_id']; $value_day=$_GET['value_day']; $hr_set=$_GET['hr_set']; $room_search=$_GET['room_search']; $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->set_day($registed_course_id,$value_day,$hr_set,$room_search,$coures_id_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day_set"){ $registed_course_id=$_GET['registed_course_id']; $room_search=$_GET['room_search']; echo $class_data->get_day_set($registed_course_id,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_week_between"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_week_between($coures_id_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_count_adttend_class_val"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_count_adttend_class_val($coures_id_list_val); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_attend_score_std"){ $std_id_all=$_POST['std_id_all']; $value_attend_week=$_POST['value_attend_week']; $all_attendID=$_POST['all_attendID']; $coures_id_list_val=$_POST['coures_id_list_val']; //$set_count_adttend_class_val=$_POST['set_count_adttend_class_val']; $arr_std_id_all = explode("-", $std_id_all); $arr_value_attend_week = explode(",", $value_attend_week); $arr_all_attendID = explode("-", $all_attendID); $num_1=0; for ($i=0; $i <count($arr_std_id_all) ; $i++) { for ($k=0; $k < 10; $k++) { $class_data->sql =" UPDATE tbl_attend_class SET score_status='$arr_value_attend_week[$num_1]' WHERE DataID=$arr_all_attendID[$num_1] "; echo $class_data->query(); $num_1++; } } //echo $class_data->set_count_adttend_class_val($coures_id_list_val,$set_count_adttend_class_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "save_attend"){ $status=$_GET['status']; $attend_id=$_GET['attend_id']; $course_teaching_stdID=$_GET['course_teaching_stdID']; $set_attend_day_id=$_GET['set_attend_day_id']; $week=$_GET['week']; $class_data->sql ="SELECT COUNT(*) as attend_count FROM tbl_attend_class_std WHERE DataID=$attend_id "; $class_data->select(); $class_data->setRows(); $attend_count=$class_data->rows[0]['attend_count']; if ($attend_id==0) { $class_data->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$week,'$status') "; $class_data->query(); }else{ if ($status=='1') { $class_data->sql ="DELETE FROM tbl_attend_class_std WHERE DataID=$attend_id" ; $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_attend_class_std SET status='$status' WHERE DataID=$attend_id"; $class_data->query(); } } /*if ($attend_count>0) { if ($status=='1') { $class_data->sql ="DELETE FROM tbl_attend_class_std WHERE DataID=$attend_id" ; $class_data->query(); }else{ $class_data->sql ="UPDATE tbl_attend_class_std SET status='$status' WHERE DataID=$attend_id"; $class_data->query(); } }else{ $class_data->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$week,'$status') "; $class_data->query(); }*/ echo json_encode(1); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_week_list_data"){ $room_search=$_GET['room_search']; $coures_id_list_val=$_GET['coures_id_list_val']; $length_list_val=$_GET['length_list_val']; $registed_course_teaching_id=$_GET['registed_course_teaching_id']; $user_status=$_SESSION['ss_status']; if ($user_status==1) { echo $class_data->get_week_list_data($coures_id_list_val,$length_list_val,$room_search,$registed_course_teaching_id); }elseif($user_status==2){ $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_week_list_data_admin($coures_id_list_val,$length_list_val,$room_search,$registed_course_teaching_id,$term_data,$year_data); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day_list"){ $length_list_val=$_GET['length_list_val']; $registed_course_id=$_GET['registed_course_id']; $room_search=$_GET['room_search']; echo $class_data->get_day_list($length_list_val,$registed_course_id,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_detail"){ $coures_id_list=$_GET['coures_id_list']; $room_search=$_GET['room_search']; $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->search_course_detail($coures_id_list,$room_search,$term_data,$year_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_class_level"){ $coures_id_list_val=$_GET['coures_id_list_val']; $user_status=$_SESSION['ss_status']; if ($user_status==1) { echo $class_data->get_class_level($coures_id_list_val); }elseif($user_status==2){ $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_class_level_admin($coures_id_list_val,$term_data,$year_data); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list"){ $user_status=$_SESSION['ss_status']; if ($user_status==1) { echo $class_data->get_coures_id_list(); }elseif($user_status==2){ $term_data=$_GET['term_data']; $year_data=$_GET['year_data']; echo $class_data->get_coures_id_list_admin($term_data,$year_data); } } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); }<file_sep>/config.php <?php @header( 'Pragma: no-cache' ); @header( 'Content-Type:text/html; charset=utf-8'); date_default_timezone_set('Asia/Bangkok'); error_reporting(0); /*Database Connect *************************************************************/ //ONLINE // define("DB_SERVER","localhost"); // define("DB_USER","hishield_db"); // define("DB_PASS","<PASSWORD>"); // define("DB_DATABASE","hishield_db"); // OFFLINE : LOCALHOST define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS",""); define("DB_DATABASE","sratongact_eva"); ?> <file_sep>/modules/print/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "search_course_detail"){ $coures_id_list=$_GET['coures_id_list']; $room_search=$_GET['room_search']; echo $class_data->search_course_detail($coures_id_list,$room_search); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_class_level"){ $coures_id_list_val=$_GET['coures_id_list_val']; echo $class_data->get_class_level($coures_id_list_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_coures_id_list"){ echo $class_data->get_coures_id_list(); }<file_sep>/src/class_db_test.php <?php /*************************************** PROCESS DB ****************************************/ // -- SELECT * FROM pro_category WHERE lft <= 1 AND rgt >= 1 AND level > 0 // -- SELECT * FROM pro_category WHERE lft <= 23 AND rgt >= 23 AND level = 1 // -- SELECT * FROM pro_category WHERE lft >= 22 AND rgt <= 33 // -- SELECT * FROM pro_category WHERE lft > 2 AND rgt < 15 and level=2 // -- SELECT * FROM pro_category WHERE lft <= 2 AND rgt >= 2 AND level > 0 // -- SELECT count(cat_id) as data_id_total FROM pro_category WHERE parent_id = 0 ORDER BY sequence DESC class Members extends Databases { public function __construct($params=NULL){ $this->module = $params['module'] ; parent::__construct((empty($params['table']))?$module:$params['table'] ); } public function ex_setrows_tb(){ $this->sql = "select * from $this->table " ; $this->select(); //update(); delete(); $this->setRows(); echo '<pre>'; print_r($this->rows); echo '</pre>'; } public function ex_getrows_tb(){ $this->sql = "select * from our_people_photos " ; $this->select(); return $this->getRows(); } public function ex_getone_tb(){ $this->sql = "select opp_id from our_people_photos where our_id='2' limit 0,1 " ; $this->select(); $this->setRows(); return $this->rows[0]['opp_id']; } // public function ex_getrows_tb(){ // $this->sql = "inset into our_people_photos ('.......') " ; // $this->insert(); // return $this->insertID(); // } } ?><file_sep>/modules/regis_student/index.js var opPage = 'regis_student'; $(document).ready(function() { years_set(); get_day(1); get_term_year_now(); }); $(function () { $('[data-toggle="tooltip"]').tooltip() }) $(document).delegate('#exit_std', 'click', function(event) { window.location.reload(); }); $(document).delegate('#uploadBtn_select', 'click', function(event) { $('#uploadBtn').trigger('click'); }); $( "#uploadBtn" ).change(function() { $("#modalWaitUp").modal("show"); var year_main =$("#year_main").val(); var file_data = $('#uploadBtn').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); form_data.append('year_main', year_main); //alert(form_data); $.ajax({ url: 'modules/regis_student/upload_one.php', // point to server-side PHP script dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(data){ $(".modal").modal("hide"); $("#table_list").html(data); $("#modalstdshow").modal("show"); //alert (php_script_response); // display response from the PHP script, if any } }); }); function form_reset(form_se) { $("#"+form_se)[0].reset(); } function send_data() { var formData = $( "#frm_data" ).serializeArray(); var year_main =$("#year_main").val(); formData.push({ "name": "acc_action", "value": "save_data" }); formData.push({ "name": "year_main", "value": year_main }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { // console.log(data); // return false; $(".modal").modal("hide"); $("#modalRegistered").modal("show"); $("#std_ID").attr( "placeholder", "" ); $("#card_ID").attr( "placeholder", "" ); form_reset("frm_data"); }); } function isNumber(data){ data = data +"e1"; // Disallow eng. notation "10e2"+"e1" is NaN var clean = parseFloat(data,10) / data ; // 1 if parsed cleanly return (clean && (data/data) === 1.0); // Checks for NaN } $(document).delegate('#btn__save', 'click', function(event) { $("#std_ID").addClass("form-set"); $("#card_ID").addClass("form-set"); var std_ID =$("#std_ID").val(); var card_ID =$("#card_ID").val(); if(std_ID!='' && card_ID!='') { var formData = new Array(); formData.push({ "name": "acc_action", "value": "chk_id" }); formData.push({ "name": "std_ID", "value": std_ID }); formData.push({ "name": "card_ID", "value": card_ID }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { if (data.num_std_ID=="1") { $(".modal").modal("hide"); $("#std_ID").removeClass("form-set"); $("#std_ID").addClass("form-set-null-data"); $("#std_ID").attr( "placeholder", "รหัส "+std_ID+" มีอยู่ในระบบแล้ว" ); $("#std_ID").val(""); } if(data.num_card_ID=="1"){ $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "รหัส "+card_ID+" มีอยู่ในระบบแล้ว" ); $("#card_ID").val(""); } if (data.num_std_ID=="0" && data.num_card_ID=="0") { var num_card_ID=card_ID.length; if (num_card_ID>13) { $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "รหัสบัตรประชาชนเกิน 13 หลัก" ); $("#card_ID").val(""); }else if(num_card_ID<13){ $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "รหัสบัตรประชาชนไม่ถึง 13 หลัก" ); $("#card_ID").val(""); }else{ var card_id_sck=isNumber(card_ID); if (card_id_sck==true) { send_data(); }else{ $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "ใส่ข้อมูลเป็นตัวเลขเท่านั้น" ); $("#card_ID").val(""); } } } }); }else{ $(".modal").modal("hide"); if(std_ID==""){ $("#std_ID").removeClass("form-set"); $("#std_ID").addClass("form-set-null-data"); $("#std_ID").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } if(card_ID==""){ $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } } }); function get_term_year_now() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_term_year_now" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { var year=data.year; var year_now=data.year_now; var year_last=year_now-5;; var year_set=document.getElementById("year_main"); var year_now_max=year_now+1; year_set.innerHTML += '<option selected="selected" value="'+year_now_max+'"> ปีการศึกษา'+year_now_max+'</option>'; for (var i = year_now; i >= year_last; i--) { if (i==year) { year_set.innerHTML += '<option selected="selected" value="'+i+'"> ปีการศึกษา'+i+'</option>'; }else{ year_set.innerHTML += '<option value="'+i+'">ปีการศึกษา '+i+'</option>'; } } }); } function years_set() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_years" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#years_set").html(data.set_years); }); } function get_day(mouth) { //var formData = $( "#frm_data" ).serializeArray(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_day" }); formData.push({ "name": "mouth", "value": mouth }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { console.log(data.day_set) $("#day_set").html(data.day_set); }); }<file_sep>/modules/regis_student/class_room.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); $class_data->sql ="SELECT * FROM tbl_student "; $class_data->select(); $class_data->setRows(); foreach($class_data->rows as $key => $value) { $std_ID=$value['std_ID']; $class_level=$value['class_level']; $room=$value['room']; $data_response.=" insert into tbl_std_class_room(std_ID,class_level,room,year) values('$std_ID','$class_level','$room','2558');<br> "; } echo $data_response;<file_sep>/modules/print/pdf_form.php <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/print.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" rel="stylesheet" type="text/css"> <script type="text/javascript" src="../../assets/js/jquery.js"></script> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 5px; } --> </style> <?php @session_start(); include('logo.php'); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); $data_id=$_POST['data_id']; $room_search=$_POST['room_search']; $status=$_POST['status']; $status_form=$_POST['status_form']; $page=$_POST['page']; $class_data->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$data_id "; $class_data->select(); $class_data->setRows(); $courseID=$class_data->rows[0]['courseID']; $name=$class_data->rows[0]['name']; $class_level=$class_data->rows[0]['class_level']; $class_data->sql ="SELECT * FROM tbl_set_term_year "; $class_data->select(); $class_data->setRows(); $term=$class_data->rows[0]['term']; $year=$class_data->rows[0]['year']; //$class_level_new=$class_data->get_class_level_new($class_level); if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_level_remove=str_replace('p','',$class_level); }else{ $class_level_remove=str_replace('m','',$class_level); } $get_grade_summary=$class_data->get_grade_summary($data_id,$room_search,$status); if($status==1/* || $page=='all_page'*/){ $attend=$class_data->get_attend($data_id,$status,$room_search); $objective_list=$class_data->get_objective_list($data_id,$room_search); $std_desirable=$class_data->get_std_desirable($data_id,$room_search); } if ($status==2) { $attend=$class_data->get_attend($data_id,$status,$room_search); $std_desirable=$class_data->get_std_desirable($data_id,$room_search); $dev_summary=$class_data->get_dev_summary($data_id,$room_search); $num_all_std_dev=$dev_summary['num_all_std']; $data_atte_pass=$dev_summary['data_atte_pass']; $data_atte_nopass=$dev_summary['data_atte_nopass']; $summary_atte_pass_per=round(($data_atte_pass*100)/$num_all_std_dev,2); $summary_atte_nopass_per=round(($data_atte_nopass*100)/$num_all_std_dev,2); } $num_all_std=$get_grade_summary['num_all_std']; $data_i=$get_grade_summary['data_i']; $data_atte=$get_grade_summary['data_atte']; $data_00=$get_grade_summary['data_00']; $data_10=$get_grade_summary['data_10']; $data_15=$get_grade_summary['data_15']; $data_20=$get_grade_summary['data_20']; $data_25=$get_grade_summary['data_25']; $data_30=$get_grade_summary['data_30']; $data_35=$get_grade_summary['data_35']; $data_40=$get_grade_summary['data_40']; $data_i=$get_grade_summary['data_i']; $data_atte=$get_grade_summary['data_atte']; $get_per_00=round(($data_00*100)/$num_all_std,2); $get_per_10=round(($data_10*100)/$num_all_std,2); $get_per_15=round(($data_15*100)/$num_all_std,2); $get_per_20=round(($data_20*100)/$num_all_std,2); $get_per_25=round(($data_25*100)/$num_all_std,2); $get_per_30=round(($data_30*100)/$num_all_std,2); $get_per_35=round(($data_35*100)/$num_all_std,2); $get_per_40=round(($data_40*100)/$num_all_std,2); $get_per_i=round(($data_i*100)/$num_all_std,2); $get_per_atte=round(($data_atte*100)/$num_all_std,2); $data_desirable_nopass=$get_grade_summary['data_desirable_nopass']; $data_desirable_pass=$get_grade_summary['data_desirable_pass']; $data_desirable_good=$get_grade_summary['data_desirable_good']; $data_desirable_verygood=$get_grade_summary['data_desirable_verygood']; $get_per_desirable_nopass=round(($data_desirable_nopass*100)/$num_all_std,2); $get_per_desirable_pass=round(($data_desirable_pass*100)/$num_all_std,2); $get_per_desirable_good=round(($data_desirable_good*100)/$num_all_std,2); $get_per_desirable_verygood=round(($data_desirable_verygood*100)/$num_all_std,2); $data_read_think_write_nopass=$get_grade_summary['data_read_think_write_nopass']; $data_read_think_write_pass=$get_grade_summary['data_read_think_write_pass']; $data_read_think_write_good=$get_grade_summary['data_read_think_write_good']; $data_read_think_write_verygood=$get_grade_summary['data_read_think_write_verygood']; $get_per_read_think_write_nopass=round(($data_read_think_write_nopass*100)/$num_all_std,2); $get_per_read_think_write_pass=round(($data_read_think_write_pass*100)/$num_all_std,2); $get_per_read_think_write_good=round(($data_read_think_write_good*100)/$num_all_std,2); $get_per_read_think_write_verygood=round(($data_read_think_write_verygood*100)/$num_all_std,2); if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 1</td> <td style="border: none;">สามารถอ่านและหาประสบการณ์จากสื่อที่หลากหลาย</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 2</td> <td style="border: none;">สามารถจับประเด็นสำคัญ ข้อเท็จจริง ความคิดเห็นเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 3</td> <td style="border: none;">สามารถเปรียบเทียบแง่มุมต่างๆ เช่น ข้อดี ข้อเสีย ประโยชน์ <br>โทษ ความเหมาะสม ไม่เหมาะสม</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 4</td> <td style="border: none;">สามารถแสดงความคิดเห็นต่อเรื่องที่อ่าน โดยมีเหตุผลประกอบ</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 5</td> <td style="border: none;">สามารถถ่ายทอดความคิดเห็นความรู้สึกจากเรื่องที่อ่านโดยการเขียน</td> </tr> '; }elseif($class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 1</td> <td style="border: none;">สามารถอ่านเพื่อหาข้อมูลสารสนเทศเสริมประสบการณ์จากสื่อประเภท<br>ต่างๆ</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 2</td> <td style="border: none;">สามารถจับประเด็นสำคัญ เปรียบเทียบ เชื่อมโยงความเป็นเหตุเป็น<br>ผลจากเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 3</td> <td style="border: none;">สามารถเชื่อมโยงความสัมพันธ์ของเรื่องราว เหตุการณ์ของเรื่อง<br>ที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 4</td> <td style="border: none;">สามารถแสดงความคิดเห็นต่อเรื่องที่อ่านโดยมีเหตุผลสนับสนุน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 5</td> <td style="border: none;">สามารถถ่ายทอดความเข้าใจ ความคิดเห็น คุณค่าจากเรื่องที่อ่าน<br>โดยการเขียน</td> </tr> '; }elseif($class_level=='m1' || $class_level=='m2' || $class_level=='m3') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 1</td> <td style="border: none;">สามารถคัดสรรสื่อที่ต้องการอ่านเพื่อหาข้อมูลสารสนเทศได้ตาม<br>วัตถุประสงค์ สามารถสร้างความเข้าใจและประยุกต์ใช้ความรู้จากการอ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 2</td> <td style="border: none;">สามารถจับประเด็นสำคัญและประเด็นสนับสนุน โต้แย้ง</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 3</td> <td style="border: none;">สามารถวิเคราะห์ วิจารณ์ ความสมเหตุสมผล ความน่าเชื่อถือ ลำดับความ<br>และความเป็นไปได้ของเรื่องที่อ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 4</td> <td style="border: none;">สามารถสรุปคุณค่า แนวคิด แง่คิดที่ได้จากการอ่าน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 5</td> <td style="border: none;">สามารถสรุป อภิปราย ขยายความ แสดงความคิดเห็น โต้แย้ง สนับสนุน<br> โน้มน้าว โดยการเขียนสื่อสารในรูปแบบต่าง ๆ เช่น ผังความคิด เป็นต้น</td> </tr> '; }elseif($class_level=='m4' || $class_level=='m5' || $class_level=='m6') { $text_rtw_desc=' <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 1</td> <td style="border: none;">สามารถอ่านเพื่อการศึกษาค้นคว้า เพิ่มพูนความรู้ประสบการณ์และ<br>การประยุกต์ใช้ในชีวิตประจำวัน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 2</td> <td style="border: none;">สามารถจับประเด็นสำคัญลำดับเหตุการณ์จากการอ่านสื่อที่มีความ<br>ซับซ้อน</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 3</td> <td style="border: none;">สามารถวิเคราะห์สิ่งที่ผู้เขียนต้องการสื่อสารกับผู้อ่านและสามารถ<br>วิพากษ์ ให้ข้อเสนอแนะในแง่มุมต่าง ๆ</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 4</td> <td style="border: none;">สามารถประเมินความน่าเชื่อถือ คุณค่า แนวคิดที่ได้จากสิ่งที่อ่าน<br>อย่างหลากหลาย</td> </tr> <tr> <td width="110px" style="vertical-align: top;border: none;padding-left:20px;">ตัวชี้วัดที่ 5</td> <td style="border: none;">สามารถเขียนแสดงความคิดเห็นโต้แย้ง สรุป โดยมีข้อมูลอธิบาย<br>สนับสนุนอย่างเพียงพอและสมเหตุสมผล</td> </tr> '; } ?> <div class="container"> <center> <button id="printPageButton" onClick="window.print();">พิมพ์</button> </center> <div style="page-break-after:always;width: 297mm"> <page > <img class="logo-print-size" src="<?php echo $image_logo ?>"> <br> <div class="col-sm-12 text-center " style="font-size: 36px;margin-top: 8px;"> <p class="text-bold " style="margin-top: -8px;">แบบบันทึกผลการพัฒนาคุณภาพผู้เรียน (ปพ.5)</p> <p class="text-bold " style="line-height: 0.3">โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อำเภอเมือง จังหวัดร้อยเอ็ด</p> <p >รหัสวิชา <span class="text-bold"><?php echo $courseID; ?></span> รายวิชา <span class="text-bold"><?php echo $name; ?></span></p> <?php if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { ?> <?php if ($status==2) { ?> <?php if ($status_form==25 || $status_form==26 || $status_form==27) { ?> <p style="line-height: 0.5">ระดับชั้นประถมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove.'/'.$room_search; ?></span> ปีการศึกษา <span class="text-bold"><?php echo $year; ?></span> </p> <?php }else{ ?> <p style="line-height: 0.5">ระดับชั้นประถมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove; ?></span> ปีการศึกษา <span class="text-bold"><?php echo $year; ?></span> </p> <?php } ?> <?php }else{ ?> <p style="line-height: 0.5">ระดับชั้นประถมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove.'/'.$room_search; ?></span> ปีการศึกษา <span class="text-bold"><?php echo $year; ?></span> </p> <?php } ?> <?php }else{ ?> <?php if ($status==2) { ?> <?php if ($status_form==25 || $status_form==26 || $status_form==27) { ?> <p style="line-height: 0.4">ระดับชั้นมัธยมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove.'/'.$room_search; ?></span> ภาคเรียนที่ <span class="text-bold"><?php echo $term; ?></span> ปีการศึกษา <span class="text-bold"><?php echo $year; ?></span> </p> <?php }else{ ?> <p style="line-height: 0.4">ระดับชั้นมัธยมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove; ?></span> ภาคเรียนที่ <span class="text-bold"><?php echo $term; ?></span> ปีการศึกษา <span class="text-bold"><?php echo $year; ?></span> </p> <?php } ?> <?php }else{ ?> <p style="line-height: 0.4">ระดับชั้นมัธยมศึกษาปีที่ <span class="text-bold"><?php echo $class_level_remove.'/'.$room_search; ?></span> ภาคเรียนที่ <span class="text-bold"><?php echo $term; ?></span> ปีการศึกษา <span class="text-bold"><?php echo $year; ?></span> </p> <?php } ?> <?php } ?> <?php if ($status==1) { ?> <p style="line-height: 1.4;font-size: 28px;margin-top: 30px;"> <span>ครูประจำชั้น ........................................................................</span> <span style="margin-left: 20px;">ครูประจำชั้น ........................................................................</span> </p> <?php } ?> </div> <br> <?php if($status==1){ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 26px;margin-left: 30px;border: 1px solid black;margin-top:-10px;"> <thead style="border: none;"> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="10" style="width: 60%;padding: 5px;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style=" vertical-align: middle;width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="10" style="padding: 5px;border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td style="width: 7%;"><?php echo $num_all_std.'&nbsp;&nbsp; คน'; ?></td> <td style="width: 7%;">4.0</td> <td style="width: 7%;">3.5</td> <td style="width: 7%;">3.0</td> <td style="width: 7%;">2.5</td> <td style="width: 7%;">2.0</td> <td style="width: 7%;">1.5</td> <td style="width: 7%;">1.0</td> <td style="width: 7%;">0</td> <td style="width: 7%;">ร</td> <td style="width: 7%;">มส</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_40; ?></td> <td><?php echo $data_35; ?></td> <td><?php echo $data_30; ?></td> <td><?php echo $data_25; ?></td> <td><?php echo $data_20; ?></td> <td><?php echo $data_15; ?></td> <td><?php echo $data_10; ?></td> <td><?php echo $data_00; ?></td> <td><?php echo $data_i; ?></td> <td><?php echo $data_atte; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_40; ?></td> <td><?php echo $get_per_35; ?></td> <td><?php echo $get_per_30; ?></td> <td><?php echo $get_per_25; ?></td> <td><?php echo $get_per_20; ?></td> <td><?php echo $get_per_15; ?></td> <td><?php echo $get_per_10; ?></td> <td><?php echo $get_per_00; ?></td> <td><?php echo $get_per_i; ?></td> <td><?php echo $get_per_atte; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 26px;margin-left: 30px;"> <thead style="border-top: none;"> <tr class="text-middle"> <td rowspan="2" style="vertical-align: middle;width: 12.74%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ และเขียน</td> <td style=" vertical-align: middle;width: 11.08%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <?php }else{ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 26px;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead style="border: none;"> <tr> <td rowspan="2" style="width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="2" style="width: 70%;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style="width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="2" style="border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td><?php echo $num_all_std_dev.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 13.8px;">ผ่าน</td> <td>ไม่ผ่าน</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_atte_pass; ?></td> <td><?php echo $data_atte_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $summary_atte_pass_per; ?></td> <td><?php echo $summary_atte_nopass_per; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 26px;margin-left: 30px;"> <thead style="border-top: none;"> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 12.74%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ และเขียน</td> <td style=" vertical-align: middle;width: 11.08%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <?php } ?> <div style="position: relative;margin-top: 40px;font-size: 24px;"> <div style="position: absolute;left: 130px;top: 40px;"> <p >................................................................. ครูผู้สอน </p> <div style="position: relative;"> <p style="position: absolute;left: 0;">(</p> <p style="position: absolute;right: 50px;"> )</p> </div><br> <p style="margin-left: 15px;">................/................/...................</p> </div> <div style="position: absolute;right: 140px;top: 40px;"> <p>................................................................. หัวหน้างานวัดผล </p> <div style="position: relative;"> <p style="position: absolute;left: 0;">(</p> <p style="position: absolute;right: 102px;"> )</p> </div><br> <p style="margin-left: 15px;">................/................/...................</p> </div> </div> <div style="position: relative;margin-top: 200px;font-size: 24px;"> <div style="position: absolute;top: 40px;left: 130px;"> <p>................................................................. หัวหน้ากลุ่มสาระการเรียนรู้</p> <div style="position: relative;"> <p style="position: absolute;left: 0;">(</p> <p style="position: absolute;right: 170px;"> )</p> </div><br> <p style="margin-left: 15px;">................/................/...................</p> </div> </div> <div style="position: relative;margin-top: 330px;font-size: 24px;"> <div style="position: absolute;top: 40px;right: 280px;"> <p >(</span> <span style="margin-left:10px ">)</span> อนุมัติ</p> <p style="margin-top: -44px;margin-left: 95px;"><span>(</span> <span style="margin-left:10px ">)</span> ไม่อนุมัติ</p> </div> </div> <div style="position: relative;margin-top: 400px;margin-bottom: 700px;font-size: 24px;"> <div style="position: absolute;left: 130px;top: 40px;"> <p>................................................................. รองผู้อำนวยการฝ่ายวิชาการ </p> <div style="position: relative;"> <p style="position: absolute;left: 0;">(</p> <p style="position: absolute;right: 175px;"> )</p> </div><br> <p style="margin-left: 15px;">................/................/...................</p> </div> <div style="position: absolute;right: 90px;top: 40px;"> <p>................................................................. ผู้อำนวยการสถานศึกษา </p> <div style="position: relative;"> <p style="position: absolute;left: 0;">(</p> <p style="position: absolute;right: 145px;"> )</p> </div><br> <p style="margin-left: 15px;">................/................/...................</p> </div> </div> </page> </div> <?php if($page=='all_page'){ if($attend['set_page']=='port'){ echo $attend['data_html']; }else{ echo $attend['data_html']; } } ?> <!--<?php if($page=='all_page'){ ?> <?php if($attend['set_page']=='port'){ echo $attend['data_html']; ?> <?php }else{ echo $attend['data_html']; ?> -orientation="<?php if($attend['set_page']=='land'){echo "landscape";}else{echo "portrait";}?>" <?php } ?> --> <page orientation="portrait"> <?php if($status==1){ echo $objective_list['data_html']; } ?> </page> <?php if ($status==2) { ?> <?php echo $dev_summary['data_html_dev']; ?> <?php } ?> <?php echo $std_desirable; ?> <div style="page-break-after:always;position: relative;top: 100px; "> <page orientation="portrait"> <?php if($status==1){ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead style="border: none;"> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="10" style="width: 60%;padding: 5px;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style=" vertical-align: middle;width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="10" style="padding: 5px;border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td style="width: 7%;"><?php echo $num_all_std.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 7%;">4.0</td> <td style="width: 7%;">3.5</td> <td style="width: 7%;">3.0</td> <td style="width: 7%;">2.5</td> <td style="width: 7%;">2.0</td> <td style="width: 7%;">1.5</td> <td style="width: 7%;">1.0</td> <td style="width: 7%;">0</td> <td style="width: 7%;">ร</td> <td style="width: 7%;">มส</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_40; ?></td> <td><?php echo $data_35; ?></td> <td><?php echo $data_30; ?></td> <td><?php echo $data_25; ?></td> <td><?php echo $data_20; ?></td> <td><?php echo $data_15; ?></td> <td><?php echo $data_10; ?></td> <td><?php echo $data_00; ?></td> <td><?php echo $data_i; ?></td> <td><?php echo $data_atte; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_40; ?></td> <td><?php echo $get_per_35; ?></td> <td><?php echo $get_per_30; ?></td> <td><?php echo $get_per_25; ?></td> <td><?php echo $get_per_20; ?></td> <td><?php echo $get_per_15; ?></td> <td><?php echo $get_per_10; ?></td> <td><?php echo $get_per_00; ?></td> <td><?php echo $get_per_i; ?></td> <td><?php echo $get_per_atte; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;"> <thead style="border-top: none;"> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 12.74%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ และเขียน</td> <td style=" vertical-align: middle;width: 11.08%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <div style="margin-left: 30px;margin-top: 30px;line-height: 0.9;"> <p style="font-size: 24px;">เกณฑ์ระดับคุณภาพ</p> <p style="margin-left: 12px;margin-top: 10px;font-size: 22px;">ระดับผลการเรียน</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 4</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 3.5</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 3</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 2.5</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 2</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 1.5</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 1</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ระดับ 0</p> </div> <div style="margin-left: 160px;margin-top: -221px;line-height: 0.9;"> <p style="margin-left: 12px;margin-top: 10px;font-size: 22px;">ความหมาย</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ดีเยี่ยม</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ดีมาก</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ดี</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ค่อนข้างดี</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ปานกลาง</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">พอใช้</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ผ่านเกณฑ์ขั้นต่ำ</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">ต่ำกว่าเกณฑ์</p> </div> <div style="margin-left:290px;margin-top: -221px;line-height: 0.9;"> <p style="margin-left: 12px;margin-top: 10px;font-size: 22px;">ช่วงคะแนน</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">80-100</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">75-79</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">70-74</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">65-69</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">60-64</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">55-59</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">50-54</p> <p style="margin-left: 12px;margin-top: -5px;font-size: 22px;">0-49</p> </div> <div> <table style="width: 80%;margin-left: 50px;margin-top: 40px;font-size: 14px;" > <tbody style="border:none;"> <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;font-size: 24px;">ตัวชี้วัดคุณลักษณะอันพึงประสงค์</p> <p style="line-height: 0.9;font-size: 22px;">1.รักชาติ ศาสน์ กษัตริย์</p> <p style="line-height: 0.9;font-size: 22px;">2.ซื่อสัตย์สุจริต</p> <p style="line-height: 0.9;font-size: 22px;">3.มีวินัย</p> <p style="line-height: 0.9;font-size: 22px;">4.ใฝ่เรียนรู้</p> <p style="line-height: 0.9;font-size: 22px;">5.อยู่อย่างพอเพียง</p> <p style="line-height: 0.9;font-size: 22px;">6.มุ่งมั่นในการทำงาน</p> <p style="line-height: 0.9;font-size: 22px;">7.รักความเป็นไทย</p> <p style="line-height: 0.9;font-size: 22px;">8.มีจิตสาธารณะ</p> </td> </tr> </tbody> </table> <table style="width: 80%;margin-left:700px;margin-top: -193px;font-size: 14px;"> <tbody style="border:none;"> <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;margin-top: -92px;font-size: 24px;">เกณฑ์ระดับคุณภาพคุณลักษณะอันพึงประสงค์</p> <p style="line-height: 0.9;font-size: 22px;">3 ดีเยี่ยม คะแนน 2.5-3.0</p> <p style="line-height: 0.9;font-size: 22px;">2 ดี คะแนน 1.5-2.4</p> <p style="line-height: 0.9;font-size: 22px;">1 ผ่าน คะแนน 0.5-1.4</p> <p style="line-height: 0.9;font-size: 22px;">0 ไม่ผ่าน คะแนน 0-0.4</p> </td> </tr> </tbody> </table> <table style="width: 80%;margin-left:700px;margin-top: 240px;font-size: 14px;"> <tbody style="border:none;"> <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;margin-top: -91px;font-size: 24px;">เกณฑ์ระดับคุณภาพการอ่าน คิดวิเคราะห์และเขียน</p> <p style="line-height: 0.9;font-size: 22px;">3 ดีเยี่ยม คะแนน 2.5-3.0</p> <p style="line-height: 0.9;font-size: 22px;">2 ดี คะแนน 1.5-2.4</p> <p style="line-height: 0.9;font-size: 22px;">1 ผ่าน คะแนน 0.5-1.4</p> <p style="line-height: 0.9;font-size: 22px;">0 ไม่ผ่าน คะแนน 0-0.4</p> </td> </tr> </tbody> </table> <p style="margin-top: -163px;margin-left: 40px;font-size: 24px;margin-bottom: -12px;">ตัวชี้วัดการอ่าน คิดวิเคราะห์และเขียน </p> <table style="margin-left: 35px;margin-top: 15px;font-size: 14px;"> <tbody style="border:none;font-size: 22px;"> <?php echo $text_rtw_desc; ?> </tbody> </table> </div> <?php }else{ ?> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;border: 1px solid black;margin-top: 10px;"> <thead style="border: none;"> <tr> <td rowspan="2" style="width: 16%;">จำนวนนักเรียนทั้งหมด</td> <td colspan="2" style="width: 70%;">สรุปผลการพัฒนาคุณภาพผู้เรียน</td> <td rowspan="3" style="width: 14%;">หมายเหตุ</td> </tr> <tr> <td colspan="2" style="border-left: none;">จำนวนนักเรียนที่ได้ระดับผลการเรียน</td> </tr> <tr> <td><?php echo $num_all_std_dev.'&nbsp;&nbsp;คน'; ?></td> <td style="width: 13.8px;">ผ่าน</td> <td>ไม่ผ่าน</td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_atte_pass; ?></td> <td><?php echo $data_atte_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $summary_atte_pass_per; ?></td> <td><?php echo $summary_atte_nopass_per; ?></td> <td></td> </tr> </tbody> </table> <table cellspacing="0" style="width: 92%; text-align: center; font-size: 24px;margin-left: 30px;"> <thead style="border: none;"> <tr class="text-middle"> <td rowspan="2" style=" vertical-align: middle;width: 12.74%;border-top: none;">ผลการประเมิน</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินคุณลักษณะอันพึงประสงค์</td> <td colspan="4" style="width: 35%;padding: 5px;border-top: none;">ผลการประเมินการอ่าน คิดวิเคราะห์ และเขียน</td> <td style=" vertical-align: middle;width: 11.08%;border-top: none;"></td> </tr> <tr> <td style="width: 7%;border-left: none;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;">ดีเยี่ยม</td> <td style="width: 7%;">ดี</td> <td style="width: 7%;">ผ่าน</td> <td style="width: 7%;">ไม่ผ่าน</td> <td style="width: 7%;"></td> </tr> </thead> <tbody> <tr> <td>จำนวนที่ได้</td> <td><?php echo $data_desirable_verygood; ?></td> <td><?php echo $data_desirable_good; ?></td> <td><?php echo $data_desirable_pass; ?></td> <td><?php echo $data_desirable_nopass; ?></td> <td><?php echo $data_read_think_write_verygood; ?></td> <td><?php echo $data_read_think_write_good; ?></td> <td><?php echo $data_read_think_write_pass; ?></td> <td><?php echo $data_read_think_write_nopass; ?></td> <td></td> </tr> <tr> <td>คิดเป็นร้อยละ</td> <td><?php echo $get_per_desirable_verygood; ?></td> <td><?php echo $get_per_desirable_good; ?></td> <td><?php echo $get_per_desirable_pass; ?></td> <td><?php echo $get_per_desirable_nopass; ?></td> <td><?php echo $get_per_read_think_write_verygood; ?></td> <td><?php echo $get_per_read_think_write_good; ?></td> <td><?php echo $get_per_read_think_write_pass; ?></td> <td><?php echo $get_per_read_think_write_nopass; ?></td> <td></td> </tr> </tbody> </table> <div> <table style="width: 80%;margin-left: 50px;margin-top: 40px;font-size: 14px;" > <tbody style="border:none;"> <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;font-size: 24px;">ตัวชี้วัดคุณลักษณะอันพึงประสงค์</p> <p style="line-height: 0.9;font-size: 22px;">1.รักชาติ ศาสน์ กษัตริย์</p> <p style="line-height: 0.9;font-size: 22px;">2.ซื่อสัตย์สุจริต</p> <p style="line-height: 0.9;font-size: 22px;">3.มีวินัย</p> <p style="line-height: 0.9;font-size: 22px;">4.ใฝ่เรียนรู้</p> <p style="line-height: 0.9;font-size: 22px;">5.อยู่อย่างพอเพียง</p> <p style="line-height: 0.9;font-size: 22px;">6.มุ่งมั่นในการทำงาน</p> <p style="line-height: 0.9;font-size: 22px;">7.รักความเป็นไทย</p> <p style="line-height: 0.9;font-size: 22px;">8.มีจิตสาธารณะ</p> </td> </tr> </tbody> </table> <table style="width: 80%;margin-left:700px;margin-top: -193px;font-size: 14px;"> <tbody style="border:none;"> <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;margin-top: -92px;font-size: 24px;">เกณฑ์ระดับคุณภาพคุณลักษณะอันพึงประสงค์</p> <p style="line-height: 0.9;font-size: 22px;">3 ดีเยี่ยม คะแนน 2.5-3.0</p> <p style="line-height: 0.9;font-size: 22px;">2 ดี คะแนน 1.5-2.4</p> <p style="line-height: 0.9;font-size: 22px;">1 ผ่าน คะแนน 0.5-1.4</p> <p style="line-height: 0.9;font-size: 22px;">0 ไม่ผ่าน คะแนน 0-0.4</p> </td> </tr> </tbody> </table> <table style="width: 80%;margin-left:700px;margin-top: 240px;font-size: 14px;"> <tbody style="border:none;"> <tr> <td style="width: 40%;border: none;"> <p style="margin-left: -20px;margin-top: -91px;font-size: 24px;">เกณฑ์ระดับคุณภาพการอ่าน คิดวิเคราะห์และเขียน</p> <p style="line-height: 0.9;font-size: 22px;">3 ดีเยี่ยม คะแนน 2.5-3.0</p> <p style="line-height: 0.9;font-size: 22px;">2 ดี คะแนน 1.5-2.4</p> <p style="line-height: 0.9;font-size: 22px;">1 ผ่าน คะแนน 0.5-1.4</p> <p style="line-height: 0.9;font-size: 22px;">0 ไม่ผ่าน คะแนน 0-0.4</p> </td> </tr> </tbody> </table> <p style="margin-top: -163px;margin-left: 40px;font-size: 24px;margin-bottom: -12px;">ตัวชี้วัดการอ่าน คิดวิเคราะห์และเขียน </p> <table style="margin-left: 35px;margin-top: 15px;font-size: 14px;"> <tbody style="border:none;font-size: 22px;"> <?php echo $text_rtw_desc; ?> </tbody> </table> </div> <?php } ?> </page> </div> <?php } ?> </div> <script> $(document).ready(function() { get_print(); setTimeout(window.close, 0); }); function get_print() { window.print(); } </script><file_sep>/includes/name-tab.js $(document).ready(function() { get_name_tab(); get_img_tab(); }); function get_img_tab() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_img_tab" }); $.getJSON('includes/process.php', formData, function(data, textStatus, xhr) { $("#get_img_tab").html(data.get_img_tab); }); } function get_name_tab() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_name_tab" }); $.getJSON('includes/process.php', formData, function(data, textStatus, xhr) { $("#full_name_th").html(data.full_name_th); }); }<file_sep>/modules/regis_course_teaching/back/edit_student.js var opPage = 'regis_course_teaching'; $(document).ready(function() { get_course_teaching_student(); get_teaching_student_only(); hide_class_std() ; }); function hide_class_std() { var formData = new Array(); var course_id=_get.courseID; formData.push({ "name": "acc_action", "value": "hide_class_std" }); formData.push({ "name": "data_id_first", "value": course_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#search_class_modal").html(data); get_std_list_new(); }) } $(document).delegate('#checkbox_all', 'click', function(event) { if(this.checked) { // check select status $('.checkbox_data').each(function() { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); }else{ $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } }); $(document).delegate('#btn__conf_add_std', 'click', function(event) { var tempValue=$("input[name='checkbox_delete[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var course_id=$("#course_id_").val(); var term_search=_get.term; var year_search=_get.year; var formData = new Array(); formData.push({ "name": "acc_action", "value": "data_add_std" }); formData.push({ "name": "data_val", "value": tempValue}); formData.push({ "name": "course_id", "value": course_id}); formData.push({ "name": "term_search", "value": term_search }); formData.push({ "name": "year_search", "value": year_search }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_teaching_student_only(); get_std_list_new(); $('.modal').modal('hide'); }) }); $(document).delegate('.bt_delete', 'click', function(event) { var data_id = $(this).attr('data-id'); $(document).delegate('#btn_to_deleteReStd', 'click', function(event) { $.post('modules/' + opPage + '/process.php', { 'acc_action' : 'data_remove_std', 'data_val' : data_id }, function(response) { data_id=''; $(".modal").modal("hide"); get_std_list_new(); get_teaching_student_only() ; }); }); }); function get_std_list_new() { var course_id=_get.courseID; var term_search=_get.term; var year_search=_get.year; var search_class_modal=$("#search_class_modal").val(); var formData = $( "#frm_data_search_modal" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_std_list_new" }); formData.push({ "name": "course_id", "value": course_id }); formData.push({ "name": "term_search", "value": term_search }); formData.push({ "name": "year_search", "value": year_search }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#std_list").html(data.std_list); }) } function get_teaching_student_only() { var data_room; var formData = new Array(); if (_get.room==0) { var search_room_modal=$("#search_room_modal").val() data_room=search_room_modal; }else{ data_room=_get.room; } formData.push({ "name": "acc_action", "value": "get_teaching_student_only" }); formData.push({ "name": "data_id", "value": _get.id}); formData.push({ "name": "data_room", "value":data_room }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#std_list_only").html(data.std_list_only); }) } function add_data_proportion() { var course_id=_get.courseID; var formData = $( "#frm_data_teaching" ).serializeArray(); formData.push({ "name": "acc_action", "value": "add_data_proportion" }); formData.push({ "name": "course_id", "value": course_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); }) } function update_objective_conclude() { var course_id=_get.courseID; var objective_data_all_id=$('#objective_data_all_id').val(); var formData = $( "#frm_data_objective" ).serializeArray(); formData.push({ "name": "acc_action", "value": "update_objective_conclude" }); formData.push({ "name": "course_id", "value": course_id }); formData.push({ "name": "objective_data_all_id", "value": objective_data_all_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); }) } function add_objective_conclude() { var course_id=_get.courseID; var formData = $( "#frm_data_objective_plus" ).serializeArray(); formData.push({ "name": "acc_action", "value": "add_objective_conclude" }); formData.push({ "name": "course_id", "value": course_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { }) } function get_registed_course_teaching() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_registed_course_teaching" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#data_table_regis_course_teaching').html(data); }) } $(document).delegate('#btn_add_teaching', 'click', function(event) { add_data_proportion(); update_objective_conclude(); add_objective_conclude(); get_registed_course_teaching() ; /* var course_id=_get.courseID; var formData = new Array(); formData.push({ "name": "acc_action", "value": "add_teaching" }); formData.push({ "name": "course_id", "value": course_id }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); get_registed_course_teaching() ; })*/ }) $(document).delegate('#btn_plus_objective', 'click', function(event) { plus_objective(); }) function plus_objective() { var formData = $( "#frm_data_objective_plus" ).serializeArray(); formData.push({ "name": "acc_action", "value": "plus_objective" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#data_objective_place_plus').html(data); }) } function get_course_teaching_student() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_course_teaching_student" }); formData.push({ "name": "data_id", "value": _get.id}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#course_id_from_search").html(data.courseID); $("#course_name_from_search").html(data.name+'(ลงทะเบียนแล้ว)'); $("#course_id_").val(data.course_data_ID); get_propotion_objective(data.course_data_ID); }) } function get_propotion_objective(data_id_first) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_propotion_objective" }); formData.push({ "name": "data_id_first", "value": data_id_first }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#comulative").val(data.comulative); $("#mid_exam").val(data.mid_exam); $("#final_exam").val(data.final_exam); $("#data_objective_place").html(data.objective_list); $("#objective_data_all_id").val(data.objective_data_all_id); }) } $(document).delegate('#btn_modal_std_search', 'click', function(event) { get_std_list_new(); })<file_sep>/modules/regis_course/index.js var opPage = 'regis_course'; $(document).ready(function() { get_data(); get_data_year_search(); get_data_registered(); get_data_registered_edit(); $(".chk_delete_btn_h").css("display","none"); get_term_year_now(); }); $(document).delegate('#btn_set_term_year', 'click', function(event) { var formData = new Array(); var term_set=$("#term_set").val(); var year_set=$("#year_set").val(); formData.push({ "name": "acc_action", "value": "set_term_year" }); formData.push({ "name": "term_set", "value": term_set }); formData.push({ "name": "year_set", "value": year_set }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { window.location.reload(); }); }); function get_term_year_now() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_term_year_now" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { var term=data.term; if(data.status_rang==3 || data.status_rang==4){ $("#term_search_id_"+term).attr('selected','selected'); $("#term_search_id_1_2").css('display','none'); }else{ $("#term_search_id_1").css('display','none'); $("#term_search_id_2").css('display','none'); $("#term_search_id_1_2").attr('selected','selected'); } var year=data.year; var year_now=data.year_now; var year_last=year_now-5;; var year_set=document.getElementById("year_set"); year_set.innerHTML += '<option selected="selected" value="'+(year_now+2)+'"> ปีการศึกษา'+(year_now+2)+'</option>'; year_set.innerHTML += '<option selected="selected" value="'+(year_now+1)+'"> ปีการศึกษา'+(year_now+1)+'</option>'; for (var i = year_now; i >= year_last; i--) { if (i==year) { year_set.innerHTML += '<option selected="selected" value="'+i+'"> ปีการศึกษา'+i+'</option>'; }else{ year_set.innerHTML += '<option value="'+i+'">ปีการศึกษา '+i+'</option>'; } } }) } function chk_to_hide_edit(value) { var course_status_val=$("#course_status").val(); chk_to_hide_department_edit(course_status_val); } function chk_to_hide_department_edit(value) { var class_level_val=$("#class_level").val(); if (value==1) { $("#department").removeAttr("disabled"); if (class_level_val=="m1" || class_level_val=="m2" || class_level_val=="m3" || class_level_val=="m4" || class_level_val=="m5" || class_level_val=="m6") { $("#unit_chk").removeAttr("disabled"); }else{ $("#unit_chk").attr("disabled","disabled"); } }else{ $("#unit_chk").attr("disabled","disabled"); $("#department").attr("disabled","disabled"); } } $(document).delegate('.btn_remove_registed', 'click', function(event) { var data_id_re = $(this).attr('data-id'); var data_term = $(this).attr('data-term'); var data_year = $(this).attr('data-year'); $(document).delegate('#btn__save_canlcel_course', 'click', function(event) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "remove_registed" }); formData.push({ "name": "data_id", "value": data_id_re }); formData.push({ "name": "data_term", "value": data_term }); formData.push({ "name": "data_year", "value": data_year }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_data_registered($(".chk_delete_btn_h").css("display")); get_data_registered_edit(); get_data_year_search(); $('.modal').modal('hide'); $(".chk_delete_btn").css("display","block"); }); }); }); $(document).delegate('.btn_edit', 'click', function(event) { hide_edit_col(); }) $(document).delegate('#btn_edit', 'click', function(event) { show_edit_col(); }) function hide_edit_col() { $ $(".chk_delete_btn_h").css("display","none"); $(".btn_edit").attr('id',"btn_edit"); } function show_edit_col() { $(".chk_delete_btn_h").css("display","block"); $(".chk_delete_btn_h").css("borderBottom","1px solid #fff"); $("#btn_edit").addClass("btn_edit"); $(".btn_edit").attr('id',""); } function get_data_year_search() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_data_year_search" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".data_year_search").html(data.year_list); }) } $(document).delegate('#btn_data_year_search_2', 'click', function(event) { get_data_registered(0); }) $(document).delegate('#btn_data_year_search_3', 'click', function(event) { get_data_registered_edit(1); }) function get_data_registered(chk_edit_after) { var formData = $( "#frm_data_search_reiged_2" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_registered" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".table_list_registed").html(data.course); }) } function get_data_registered_edit(chk_edit_after) { var formData = $( "#frm_data_search_reiged_3" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data_registered_edit" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".table_list_registed_edit").html(data.course); }) } function save_regis_course(tempValue){ var formData = new Array(); formData.push({ "name": "acc_action", "value": "save_regis_course" }); formData.push({ "name": "data_val", "value": tempValue}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { tempValue=''; get_data(); $('.modal').modal('hide'); $("#modalRegisted").modal("show"); get_data_registered($(".chk_delete_btn_h").css("display")); get_data_registered_edit(); get_data_year_search(); }) } $(document).delegate('#chk_value_select', 'click', function(event) { var tempValue=$("input[name='checkbox_regis_course[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); if (tempValue!="") { $("#modalRegister").modal("show"); }else{ $("#modalNoSelect").modal("show"); } }); $(document).delegate('#btn__save_regis_course', 'click', function(event) { var tempValue=$("input[name='checkbox_regis_course[]']:checked").map(function(n){ if(this.checked){return this.value;}; }).get().join(','); var term =$("#term").val(); var year =$("#year").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "chk_regiseted_course" }); formData.push({ "name": "data_val", "value": tempValue }); formData.push({ "name": "term", "value": term }); formData.push({ "name": "year", "value": year }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { if (data!="") { $(".modal").modal("hide"); $("#text_chk_alert").html(data); $("#modalChkRegis").modal("show"); }else{ save_regis_course(tempValue); } }); }); $(document).delegate('#btn__save', 'click', function(event) { var courseID =$("#courseID").val(); if(courseID!='') { var formData = $( "#frm_data_edit" ).serializeArray(); formData.push({ "name": "acc_action", "value": "save_data" }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $(".modal").modal("hide"); $("#modalEdited").modal("show"); get_data(); get_data_registered($(".chk_delete_btn_h").css("display")); window.location.reload(); }); }else{ $("#courseID").removeClass("form-set"); //$(".modal").modal("hide"); $("#courseID").addClass("form-set-null-data_edit"); $("#courseID").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } }); function get_data(status) { var formData = $( "#frm_search" ).serializeArray(); formData.push({ "name": "acc_action", "value": "get_data" }); formData.push({ "name": "status", "value": status }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list").html(data.table_list); }); } $(document).delegate('#btn_courseID_search', 'click', function(event) { get_data(1); }); $(document).delegate('#btn_department_class_search', 'click', function(event) { get_data(); }); $(document).delegate('#btn_cancel_checked', 'click', function(event) { $('.checkbox_data').each(function() { //loop through each checkbox this.checked = false; //select all checkboxes with class "checkbox1" }); }); function remove_class() { for (var i = 1 ; i <= 8; i++) { $("#dep_"+i).removeAttr("selected"); } for (var i = 1 ; i <= 6; i++) { $("#p"+i).removeAttr("selected"); } for (var i = 1 ; i <= 6; i++) { $("#m"+i).removeAttr("selected"); } $("#unit_05").removeAttr("selected"); $("#unit_10").removeAttr("selected"); $("#unit_15").removeAttr("selected"); $("#unit_20").removeAttr("selected"); $("#unit_25").removeAttr("selected"); $("#unit_30").removeAttr("selected"); $("#course_status_1").removeAttr("selected"); $("#course_status_2").removeAttr("selected"); } function chk_class_to_en_unit(class_level_data) { if (class_level_data=="p1" || class_level_data=="p2" || class_level_data=="p3" || class_level_data=="p4" || class_level_data=="p5" || class_level_data=="p6") { $("#unit_chk").attr("disabled","disabled"); }else{ $("#unit_chk").removeAttr("disabled"); } } function select_teacher_to_course(teacher_id) { var teacher_id_array = teacher_id.split('-'); var teacher_id_length =teacher_id_array.length; for (var i = 0; i < teacher_id_length; i++) { $(".checkbox_data_teacher_"+teacher_id_array[i]).attr("checked","checked"); } } function get_teacher_to_course_registed(registered_id) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_teacher_to_course_registed" }); formData.push({ "name": "registered_id", "value": registered_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#teacher_course_place").html(data.teacher_listed); select_teacher_to_course(data.teacher_id); }); } function insert_teacher_to_course(teacher_id,registered_id) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "insert_teacher_to_course" }); formData.push({ "name": "teacher_id", "value": teacher_id }); formData.push({ "name": "registered_id", "value": registered_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_teacher_to_course_registed(registered_id); get_data_registered_edit(); }); } $(document).delegate('.room_btn_chk', 'click', function(event) { var course_teacher_id = $(this).attr('course-teacher-id'); var room_val = $(this).val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "set_room_teacher" }); formData.push({ "name": "course_teacher_id", "value": course_teacher_id }); formData.push({ "name": "room_val", "value": room_val }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_data_registered_edit(); }); }); $(document).delegate('.btn_room_detail', 'click', function(event) { var data_id_registered_room = $(this).attr('data-id-registered-room'); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_room_detail" }); formData.push({ "name": "data_id_registered_room", "value": data_id_registered_room }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#course_detail_header").html(data.course_detail_header); $("#teacher_list_box").html(data.teacher_list_box); }); }); $(document).delegate('#btn_courseID_search', 'click', function(event) { var teacher_search_data =$("#teacher_search_data").val(); var data_id_registered=$("#data_id_registered_val").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_teacher_list" }); formData.push({ "name": "data_id_registered", "value": data_id_registered }); formData.push({ "name": "teacher_search_data", "value": teacher_search_data }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_teacher_to_course_registed(data_id_registered) $("#table_teacher_list").html(data); }); }); $(document).delegate('.btn_teacher_list', 'click', function(event) { var data_id_registered = $(this).attr('data-id-registered'); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_teacher_list" }); formData.push({ "name": "data_id_registered", "value": data_id_registered }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#data_id_registered_val").val(data_id_registered); get_teacher_to_course_registed(data_id_registered) $("#table_teacher_list").html(data); }); }); $(document).delegate('.btn_getdata_edit', 'click', function(event) { $("#courseID").addClass("form-set"); remove_class() ; var data_id = $(this).attr('data-id'); var formData = new Array(); formData.push({ "name": "acc_action", "value": "getdata_edit" }); formData.push({ "name": "data_id", "value": data_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { var class_level_data=data.class_level; var department_data=data.department; var unit_data=data.unit; var status_data=data.status; $("#"+class_level_data).attr("selected","selected"); $("#"+department_data).attr("selected","selected"); $("#unit_"+unit_data).attr("selected","selected"); $("#course_status_"+status_data).attr("selected","selected"); chk_class_to_en_unit(class_level_data); $("#data_id_course").val(data.data_id_course); $("#courseID").val(data.courseID); $("#name").val(data.name); $("#hr_learn").val(data.hr_learn); if (status_data==2) { $("#unit_chk").attr("disabled","disabled"); $("#department").attr("disabled","disabled"); }else{ $("#unit_chk").removeAttr("disabled"); $("#department").removeAttr("disabled"); } }); }); $('input').on('keydown', function(event) { var x = event.which; if (x === 13) { get_data(); event.preventDefault(); } });<file_sep>/modules/menu/class_modules.php <?php class ClassData extends Databases { var $role; var $role_id; public function __construct() { $this->role = new ClassRole(); $this->role_id = (int)$_SESSION['ss_user_id']; // You don't have permission to access } /*************************************** PROCESS DB ****************************************/ public function get_data_list($arr_search_val,$pages_current,$sort_column,$sort_by){ ## SQL CONDITION ## $sql_condition = " DataID > 0 "; $data_name = $arr_search_val['data_name']; $s_status = $arr_search_val['s_status']; if (isset($data_name) && $data_name != "") { $sql_condition .= " AND ( boxI_name LIKE '%{$data_name}%' OR boxI_nameEn LIKE '%{$data_name}%') "; } if (isset($s_status) && $s_status != "") { $sql_condition .= " AND ( status = '{$s_status}' ) "; } ## SQL CONDITION ## ## PAGINATION ## $this->sql = " SELECT count(DataID) as data_id_total FROM tbl_menu WHERE {$sql_condition} "; $this->select(); $this->setRows(); $dataidtotal = (int)$this->rows[0]['data_id_total']; $pagination = new pagination(); $pages = (int)$pages_current; $rowsperpage = 20; $arrpage = $pagination->calculate_pages($dataidtotal, $rowsperpage, $pages); $sequence = ($arrpage['current'] == 1) ? 1 : ($arrpage['current'] * $rowsperpage)-1 ; ## PAGINATION ## ## DATA TBLE ## $data_response = array(); $data_response['data_list'] = ""; if($dataidtotal > 0){ $arr_status = array('Save Draft','Published'); $sql_order_by = " sequence ASC "; $sql = "SELECT * FROM tbl_menu WHERE {$sql_condition} AND DataID!=1 ORDER BY {$sql_order_by} {$arrpage['limit']} "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID = $this->rows[$key]['DataID']; $Title_Show = $this->rows[$key]['boxI_nameEn']; $sequence = (int)$this->rows[$key]['sequence']; $status = (int)$this->rows[$key]['status']; $update_time = $this->rows[$key]['update_time']; $arr_status = array("<span class=\"label label-important\">Save Draft</span>","<span class=\"label label-info\">Published</span>","<span class=\"label label-default\">Close</span>"); $edit_hyperlink = "index.php?op=menu-from&id={$DataID}" ; $data_response['data_list'] .= "<tr> <td style=\"text-align: center;\"> <div class=\"checkbox check-success\"> <input type=\"checkbox\" value=\"{$DataID}\" name=\"checkbox_delete[]\" id=\"checkbox{$DataID}\" class=\"checkbox_data\"> <label for=\"checkbox{$DataID}\">&nbsp;</label> </div> </td> <td style=\"text-align: center;\"><a href=\"{$edit_hyperlink}\">{$Title_Show }</a> </td> <td style=\"text-align: center;\">".DateThai($update_time,"date_en")."</td> <!--<td style=\"text-align: center;\">{$arr_status[$status]}</td> <td style=\"text-align: center;\"><input class=\"span2\" id=\"sequence_{$DataID}\" name=\"sequence_{$DataID}\" data-id=\"{$sequence}\" type=\"text\" style=\"width:50px; text-align:center;\" value=\"{$sequence}\">--> <a class=\"btn btn-inverse btn_sequence\" data-id=\"{$DataID}\" href=\"javascript:;\"><i class=\"fa fa-arrows-v\"></i></a></td>"; $data_response['data_list'] .= "<td style=\"text-align: center;\"><a class=\"btn btn-inverse btn_edit \" data-id=\"{$DataID}\" href=\"javascript:;\"><i class=\"fa fa-edit\"></i></a>" ; /*$data_response['data_list'] .= "<a class=\"btn btn-danger bt_delete\" data-id=\"{$DataID}\" href=\"javascript:;\"><i class=\"fa fa-trash-o\"></i></a>";*/ $data_response['data_list'] .= "</td></tr>"; $sequence++; }} ## DATA TBLE ## /*$data_response['data_pagination'] .= "<li><a href=\"javascript:;\" data-id=\"{$arrpage['previous']}\" class=\"chg_pagination\">&laquo;</a></li>"; for($p=0; $p<count($arrpage['pages']); $p++){ $activepages = ($arrpage['pages'][$p]==$arrpage['current']) ? "active" : ""; $data_response['data_pagination'] .= "<li class=\"{$activepages}\"><a href=\"javascript:;\" data-id=\"{$arrpage['pages'][$p]}\" class=\"chg_pagination\">{$arrpage['pages'][$p]}</a></li>"; } $data_response['data_pagination'] .= " <li><a href=\"javascript:;\" data-id=\"{$arrpage['next']}\" class=\"chg_pagination\">&raquo;</a></li>";*/ return json_encode($data_response); // return $data_response; } public function get_data_from($DataID){ $data_response = array(); $this->sql = "SELECT * FROM tbl_menu WHERE DataID={$DataID} " ; $this->select(); $this->setRows(); $data_response['boxI_name'] = unchkhtmlspecialchars($this->rows[0]['boxI_name']); $data_response['boxI_nameEn'] = unchkhtmlspecialchars($this->rows[0]['boxI_nameEn']); $data_response['boxI_desc'] = unchkhtmlspecialchars($this->rows[0]['boxI_desc']); $data_response['boxI_descEn'] = unchkhtmlspecialchars($this->rows[0]['boxI_descEn']); $data_response['boxII_name'] = unchkhtmlspecialchars($this->rows[0]['boxII_name']); $data_response['boxII_nameEn'] = unchkhtmlspecialchars($this->rows[0]['boxII_nameEn']); $data_response['boxII_desc'] = unchkhtmlspecialchars($this->rows[0]['boxII_desc']); $data_response['boxII_descEn'] = unchkhtmlspecialchars($this->rows[0]['boxII_descEn']); $data_response['boxIII_name'] = unchkhtmlspecialchars($this->rows[0]['boxIII_name']); $data_response['boxIII_nameEn'] = unchkhtmlspecialchars($this->rows[0]['boxIII_nameEn']); $data_response['boxIII_desc'] = unchkhtmlspecialchars($this->rows[0]['boxIII_desc']); $data_response['boxIII_descEn'] = unchkhtmlspecialchars($this->rows[0]['boxIII_descEn']); $data_response['boxIV_name'] = unchkhtmlspecialchars($this->rows[0]['boxIV_name']); $data_response['boxIV_nameEn'] = unchkhtmlspecialchars($this->rows[0]['boxIV_nameEn']); $data_response['boxIV_desc'] = unchkhtmlspecialchars($this->rows[0]['boxIV_desc']); $data_response['boxIV_descEn'] = unchkhtmlspecialchars($this->rows[0]['boxIV_descEn']); $data_response['status'] = $this->rows[0]['status']; $data_response['tag_title'] = $this->rows[0]['tag_title']; $data_response['tag_keyword'] = $this->rows[0]['tag_keyword']; $data_response['tag_description'] = $this->rows[0]['tag_description']; return json_encode($data_response); } public function get_data($DataID){ $this->sql = "SELECT * FROM tbl_menu WHERE DataID={$DataID} " ; $this->select(); return $this->getRows(); } public function get_data_uniquevalue($field_name,$sql_where){ $this->sql = "SELECT {$field_name} FROM tbl_menu WHERE {$sql_where} " ; $this->select(); $this->setRows(); return trim($this->rows[0][$field_name]); } public function insert_data($insert,$user_id){ $this->sql = "INSERT INTO tbl_menu(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $new_id = $this->insertID(); $this->sql = "INSERT INTO tbl_log(title_action,menu_name,data_id,update_by,update_time) VALUES ('เพิ่มข้อมูล Menu','Menu','{$new_id}','{$user_id}',now())"; $this->query(); $this->sql = " SELECT sequence FROM tbl_menu ORDER BY sequence DESC, update_time DESC , create_time DESC LIMIT 0,1 "; $this->select(); $this->setRows(); $sequence_new = $this->rows[0]['sequence']+1; $this->sql = "UPDATE tbl_menu SET sequence=$sequence_new WHERE DataID='".$new_id."'"; $this->query(); // $this->sql = "UPDATE tbl_keyword SET article_id=$new_id WHERE article_id = 0 AND type_page = 2"; // $this->query(); $this->sql = "UPDATE tbl_menu_gallery SET menuID = $new_id , status = $new_id WHERE menuID = 0 AND status = 0 "; $this->query(); } public function update_data($update,$DataID,$user_id){ $this->sql = "INSERT INTO tbl_log(title_action,menu_name,data_id,update_by,update_time) VALUES ('แก้ไขข้อมูล Menu','Menu','{$DataID}','{$user_id}',now())"; $this->query(); $this->sql = "UPDATE tbl_menu SET ".implode(",",$update)." WHERE DataID='".$DataID."'"; $this->query(); // // $this->sql = "UPDATE tbl_keyword SET article_id=$new_id WHERE article_id = {$DataID}"; // // $this->query(); // $this->sql = "UPDATE tbl_menu_gallery SET menuID=$DataID WHERE menuID == 0"; // $this->query(); } public function get_data_delete($data_val,$user_id){ $arr_id = explode(",", $data_val); for ($i=0; $i < count($arr_id) ; $i++) { $targetfile = "../../../file_managers/menu/"; $this->sql = " SELECT FileName FROM tbl_menu_gallery WHERE menuID = {$arr_id[$i]}"; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $FileName = $this->rows[$key]['FileName']; if(@file_exists($targetfile."thumbnails/{$FileName}")){ @unlink($targetfile."thumbnails/{$FileName}"); } if(@file_exists($targetfile."photo/{$FileName}")){ @unlink($targetfile."photo/{$FileName}"); } } $this->sql ="DELETE FROM tbl_menu_gallery WHERE menuID = {$arr_id[$i]}"; $this->query(); $this->sql = "SELECT sequence FROM tbl_menu WHERE DataID = {$arr_id[$i]}"; $this->select(); $this->setRows(); $sequence_new = $this->rows[0]['sequence']-1; $sequence = $this->rows[0]['sequence']; $this->sql = "UPDATE tbl_menu SET sequence=sequence-1 WHERE sequence > {$sequence}"; $this->query(); $this->sql ="DELETE FROM tbl_menu WHERE DataID = {$arr_id[$i]}"; $this->query(); // $this->sql ="DELETE FROM tbl_keyword WHERE article_id = {$arr_id[$i]} AND type_page = 2"; // $this->query(); $this->sql = "INSERT INTO tbl_log(title_action,menu_name,data_id,update_by,update_time) VALUES ('ลบข้อมูล Menu','Menu','{$arr_id[$i]}','{$user_id}',now())"; $this->query(); } } public function ex_sequence_data($data_id,$sequence_old,$sequence,$user_id){ if($sequence_old > $sequence){ $st_limit = ($sequence-1); $ct_limit = ($sequence_old-$sequence); $this->sql = " SELECT sequence FROM tbl_menu WHERE DataID > 0 ORDER BY sequence ASC, update_time DESC , create_time DESC LIMIT {$st_limit},1 "; $this->select(); $this->setRows(); $sequence_new = $this->rows[0]['sequence']; $this->sql = "UPDATE tbl_menu SET sequence=sequence+1 WHERE DataID > 0 AND DataID IN (SELECT * FROM (SELECT DataID FROM tbl_menu WHERE DataID > 0 ORDER BY sequence ASC, update_time DESC , create_time DESC limit {$st_limit}, {$ct_limit}) AS t) ORDER BY sequence ASC, update_time DESC , create_time DESC "; $this->query(); $this->sql = "UPDATE tbl_menu SET sequence='{$sequence_new}' WHERE DataID={$data_id}"; $this->query(); }else if($sequence_old < $sequence){ $st_limit = ($sequence-1); $this->sql = " SELECT sequence FROM tbl_menu WHERE DataID > 0 ORDER BY sequence ASC, update_time DESC , create_time DESC LIMIT {$st_limit},1 "; $this->select(); $this->setRows(); $sequence_new = $this->rows[0]['sequence']; $st_limit = ($sequence_old-1); $ct_limit = ($sequence-$sequence_old)+1; $this->sql = "UPDATE tbl_menu SET sequence=sequence+1 WHERE sequence <= {$sequence_new} AND sequence > {$st_limit} AND DataID <> {$data_id} ORDER BY sequence ASC, update_time DESC , create_time DESC "; $this->query(); $this->sql = "UPDATE tbl_menu SET sequence='{$sequence_new}' WHERE DataID='{$data_id}'"; $this->query(); $this->sql = "INSERT INTO tbl_log(title_action,menu_name,data_id,update_by,update_time) VALUES ('จัดอันดับข้อมูล Menu','Menu','{$data_id}','{$user_id}',now())"; $this->query(); } } public function ex_add_thumb($insert){ $this->sql = "INSERT INTO tbl_menu_gallery(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $photo_id = $this->insertID(); $this->sql = "UPDATE tbl_menu_gallery SET sequence=$photo_id WHERE DataID='".$photo_id."'"; $this->query(); return $photo_id; } public function get_thumb($data_id){ $sql_condition = "WHERE menuID={$data_id} AND Type = 0 "; $sql_order_by = " sequence ASC "; $sql = "SELECT DataID,FileName FROM tbl_menu_gallery {$sql_condition} "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID = $value['DataID']; $FileName = $value['FileName'];//unchkhtmlspecialchars $file_name = (@file_exists("../../../file_managers/menu/thumbnails/{$FileName}")) ? $FileName : "thumbnail.jpg"; $data_response .= " <center> <div class=\"col-lg-12 col-md-10\"> <p class=\"small no-margin\"><img src=\"../file_managers/menu/thumbnails/{$FileName}?".time()."\" style=\"width:auto;\" class=\"img-rounded m-r-25 m-b-10\"></p> <div class=\"btn-group btn-group-xs text-center\"> <a href=\"javascript:;\" data-id=\"{$DataID}\" class=\" btn btn-danger btn_remove_thumb\">Remove</a> </div> <hr/> </div> </center>"; $sequence++; } return $data_response; } public function remove_thumb($data_id){ $targetfile = "../../../file_managers/menu/"; $this->sql = " SELECT FileName FROM tbl_menu_gallery WHERE DataID = {$data_id} LIMIT 0,1 "; $this->select(); $this->setRows(); $FileName = $this->rows[0]['FileName']; if(@file_exists($targetfile."thumbnails/{$FileName}")){ @unlink($targetfile."thumbnails/{$FileName}"); } $this->sql ="DELETE FROM tbl_menu_gallery WHERE DataID={$data_id} "; $this->query(); return "y"; } public function ex_add_award($insert){ $this->sql = "INSERT INTO tbl_menu_gallery(".implode(",",array_keys($insert)).") VALUES (".implode(",",array_values($insert)).")"; $this->query(); $photo_id = $this->insertID(); $this->sql = "UPDATE tbl_menu_gallery SET sequence=$photo_id WHERE DataID='".$photo_id."'"; $this->query(); return $photo_id; } public function get_photo_award($data_id){ $sql_condition = " menuID={$data_id} AND Type = 1"; $sql_order_by = " sequence ASC "; $sql = "SELECT DataID,FileName FROM tbl_menu_gallery WHERE {$sql_condition} ORDER BY {$sql_order_by} "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID = $value['DataID']; $FileName = $value['FileName'];//unchkhtmlspecialchars $file_name = (@file_exists("../../../file_managers/menu/photo/{$FileName}")) ? $FileName : "thumbnail.jpg"; $data_response .= " <div class=\"col-lg-3 col-md-3\"> <div class=\"row\"> <div class=\"col-lg-12 col-md-12\"> <p class=\"small no-margin text-center\"> <img src=\"../file_managers/menu/photo/{$FileName}?".time()."\" style=\"width:200px;\" class=\"img-rounded m-r-25 m-b-10\"> </p> <p class=\"small no-margin text-center\"> <a href=\"javascript:;\" data-id=\"{$DataID}\" class=\" btn-sm btn-danger btn_remove_award\">Remove</a> </p> </div> </div> <hr/> </div>"; $sequence++; } return $data_response; } public function remove_file_award($data_id){ $targetfile = "../../../file_managers/menu/"; $this->sql = " SELECT FileName FROM tbl_menu_gallery WHERE DataID = {$data_id} LIMIT 0,1 "; $this->select(); $this->setRows(); $FileName = $this->rows[0]['FileName']; if(@file_exists($targetfile."photo/{$FileName}")){ @unlink($targetfile."photo/{$FileName}"); } $this->sql ="DELETE FROM tbl_menu_gallery WHERE DataID={$data_id} "; $this->query(); return "y"; } /*************************************** PROCESS DB ****************************************/ } ?><file_sep>/modules/regis_course/index.php <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="circle-bg-violet"> <img class="head-img-circle" src="assets/images/1.png"> </div> <div class="text-head-title"> <p>ลงทะเบียนรายวิชา</p> </div> <div class="text-head-desc"> <p>ใช้สำหรับลงทะเบียน เพิ่มรายวิชาตามโครงสร้างหลักสูตรของสถานศึกษาเข้าสู่ระบบ</p> </div> <div class="row pd-50 pt-80 stage-set" > <div class="col-sm-12 col-xs-12 mt-30"> <?php if ($_SESSION['ss_status']==4){ ?> <p class="text-bold text-before-box" >ภาคเรียนและปีการศึกษาปัจจุบัน</p> <?php }else{ ?> <p class="text-bold text-before-box" >กำหนดภาคเรียนและปีการศึกษาปัจจุบัน</p> <?php } ?> <form id="frm_data"> <table> <tbody style="border: none;"> <tr> <td> <select id="term_set" name="term_set" class="form-control search-class-depart ml-10"> <option id="term_search_id_1" value="1">ภาคเรียนที่ 1</option> <option id="term_search_id_2" value="2">ภาคเรียนที่ 2</option> <option id="term_search_id_1_2" value="">ภาคเรียนที่ 1,2</option> </select> </td> <td> <select id="year_set" name="year_set" class="form-control search-course-depart ml-10"> </select> </td> <?php if ($_SESSION['ss_status']==2){ ?> <td> <div class="ml-20" style="margin-top: -2px"> <div data-toggle="modal" data-target="#modalAddTermYear" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </td> <?php } ?> </tr> </tbody> </table> </form> </div> </div> <div class="row"> <div class="hr-co-text-depart mt-nega-30"></div> </div> <div class=" ml-50 mr-50" > <div class="row"> <ul class="nav nav-tabs" role="tablist"> <?php if ($_SESSION['ss_status']==2){ ?> <li role="presentation" class="active"><a class="text-black" href="#all_sub_tab" aria-controls="all_sub_tab" role="tab" data-toggle="tab">เลือกวิชาลงทะเบียน</a></li> <li role="presentation" ><a class="text-black" href="#registed_tab" aria-controls="registed_tab" role="tab" data-toggle="tab">รายวิชาที่ลงทะเบียนแล้ว</a></li> <li role="presentation" ><a class="text-black" href="#teacher_tab" aria-controls="teacher_tab" role="tab" data-toggle="tab">กำหนดผู้สอนและห้องเรียน</a></li> <?php }else{ ?> <li role="presentation" class="active" ><a class="text-black" href="#teacher_tab" aria-controls="teacher_tab" role="tab" data-toggle="tab">กำหนดผู้สอนและห้องเรียน</a></li> <?php } ?> </ul> </div> <div class="tab-content"> <div role="tabpanel" class="tab-pane fade <?php if ($_SESSION['ss_status']==2){ echo "in active";} ?>" id="all_sub_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">เลือกวิชาลงทะเบียน</h4> </div> </div> <div class="row search-box-regis-course stage-set" > <div class="col-sm-5 col-xs-12"> <form id="frm_search"> <p class="text-bold text-search set-text-search-1" >ค้นหาจากรายวิชา</p> <div class="input-group form-serch-width-regis"> <input id="courseID_search" name="courseID_search" type="text" class="form-control form-set-search" placeholder="*รหัสวิชา" aria-describedby="basic-addon1"> </div> <div class="btn-search-poi-regis-1"> <div id="btn_courseID_search" class="btn-search "><span class="glyphicon glyphicon-search" aria-hidden="true"></span></div> </div> </div> <div class="col-sm-7 col-xs-12"> <p class="text-bold text-search set-text-search-2" >ค้นหาจาก</p> <select id="department_search" name="department_search" class="form-control search-group"> <option value="">ทุกกลุ่มสาระ</option> <option value="2">คณิตศาสตร์</option> <option value="1">ภาษาไทย</option> <option value="8">ภาษาต่างประเทศ</option> <option value="3">วิทยาศาสตร์</option> <option value="31">วิทยาศาสตร์และเทคโนโลยี</option> <option value="4">สังคมศึกษา ศาสนาและวัฒนธรรม</option> <option value="71">การงานอาชีพ</option> <option value="7">การงานอาชีพและเทคโนโลยี</option> <option value="5">สุขศึกษาและพลศึกษา</option> <option value="6">ศิลปะ</option> <option value="dev_mode">กิจกรรมพัฒนาผู้เรียน</option> </select> <select id="class_level_search" name="class_level_search" class="form-control search-group"> <option value="">ทุกระดับชั้น</option> <option value="p1"> ป.1</option> <option value="p2"> ป.2</option> <option value="p3"> ป.3</option> <option value="p4"> ป.4</option> <option value="p5"> ป.5</option> <option value="p6"> ป.6</option> <option value="m1"> ม.1</option> <option value="m2"> ม.2</option> <option value="m3"> ม.3</option> <option value="m4"> ม.4</option> <option value="m5"> ม.5</option> <option value="m6"> ม.6</option> </select> <div class="btn-search-poi-regis"> <div id="btn_department_class_search" class="btn-search"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> </div> </div> </div> </form> </div> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th></th> <th style="text-align: left;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th style="text-align: left;">ประเภท</th> <th>น.น./นก.</th> <th>เวลาเรียน</th> <th>ระดับชั้น</th> </tr> </thead> <tbody id="table_list" class="body-table"> </tbody> </table> </div> </div> </div> <div id="btn_cancel_checked" class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" id="chk_value_select" class="btn-violet"> ลงทะเบียน </div> </div> <div role="tabpanel" class="tab-pane fade " id="registed_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">รายวิชาที่ลงทะเบียนแล้ว</h4> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th style="text-align: left;padding-left: 30px;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th style="text-align: left;">ประเภท</th> <th>น.น./นก.</th> <th>เวลาเรียน</th> <th>ระดับชั้น</th> <th>ยกเลิก</th> </tr> </thead> <tbody class="body-table table_list_registed"> </tbody> </table> </div> </div> </div> </div> <div role="tabpanel" class="tab-pane fade <?php if ($_SESSION['ss_status']==4){ echo "in active";} ?>" id="teacher_tab"> <div class="row mt-30" "> <div class="text-title-table"> <h4 class="text-bold">กำหนดผู้สอนและห้องเรียน</h4> </div> </div> <div class="row mt-10"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet" > <thead class="header-table"> <tr> <th style="text-align: left;padding-left: 30px;">รหัสวิชา</th> <th style="text-align: left;">รายวิชา</th> <th style="text-align: left;">ประเภท</th> <th>น.น./นก.</th> <th>เวลาเรียน</th> <th>ระดับชั้น</th> <th>ครูผู้สอน</th> <th>ห้อง</th> </tr> </thead> <tbody class="body-table table_list_registed_edit"> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> </div><file_sep>/modules/up_class/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_POST['acc_action']) and $_POST['acc_action'] == "reverse_upclass"){ $log_upclass_id= $_POST['log_upclass_id']; $data_year_old= $_POST['data_year_old']; $data_year_new= $_POST['data_year_new']; echo $class_data->reverse_upclass($data_year_old,$data_year_new,$log_upclass_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "data_upclassed"){ echo $class_data->data_upclassed(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "up_class_m"){ echo $class_data->up_class_m($_GET['value_set']); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "up_class_p"){ echo $class_data->up_class_p($_GET['value_set']); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "up_class"){ echo $class_data->up_class(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_year"){ echo $class_data->get_year(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "data_year_search_student"){ $data_class_search= $_GET['data_class_search']; echo $class_data->data_year_search_student($data_class_search); }<file_sep>/modules/attend_class/backup/class_modules.php <?php class ClassData extends Databases { public function get_week_between($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data_response=' <option value="1-10">สัปดาห์ที่ 1-10</option> <option value="11-20">สัปดาห์ที่ 11-20</option> <option value="21-31">สัปดาห์ที่ 21-31</option> <option value="31-40">สัปดาห์ที่ 31-40</option> '; }else{ $data_response=' <option value="1-10">สัปดาห์ที่ 1-10</option> <option value="11-20">สัปดาห์ที่ 11-20</option> '; } echo json_encode($data_response); } public function get_count_adttend_class_val($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; echo json_encode($week_name); } /*public function set_count_adttend_class_val($coures_id_list_val,$set_count_adttend_class_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT COUNT(*) as num_row FROM tbl_set_count_adttend_class WHERE registed_courseID =$registed_courseID "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $this->sql ="UPDATE tbl_set_count_adttend_class SET week_name=$set_count_adttend_class_val WHERE registed_courseID=$registed_courseID "; $this->query(); }else{ $this->sql ="INSERT INTO tbl_set_count_adttend_class(registed_courseID,week_name) VALUES($registed_courseID,$set_count_adttend_class_val) "; $this->query(); } }*/ public function chk_value_attend_1($score_status){ if ($score_status=="1") { $data_response="selected"; } return $data_response; } public function chk_value_attend_l($score_status){ if ($score_status=="ล") { $data_response="selected"; } return $data_response; } public function chk_value_attend_p($score_status){ if ($score_status=="ป") { $data_response="selected"; } return $data_response; } public function chk_value_attend_k($score_status){ if ($score_status=="ข") { $data_response="selected"; } return $data_response; } public function chk_value_attend_n($score_status){ if ($score_status=="น") { $data_response="selected"; } return $data_response; } public function chk_value_attend__($score_status){ if ($score_status=="0" || $score_status=="-") { $data_response="selected"; } return $data_response; } public function get_score_col($std_ID,$registed_courseID,$start_data,$end_data){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT * FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $attendID=$value['DataID']; $week=$value['week']; $score_status=$value['score_status']; $data_response['score_col'].=" <td class=\"relative\"> <select disabled=\"disabled\" name=\"attend_score_std[]\" class=\"select-table-form class_col_set_new class_col_attend_{$week} value_attend_week_{$week}\"> <option value=\"1\" {$this->chk_value_attend_1($score_status)}>1</option> <option value=\"ล\" {$this->chk_value_attend_l($score_status)}>ล</option> <option value=\"ป\" {$this->chk_value_attend_p($score_status)}>ป</option> <option value=\"ข\" {$this->chk_value_attend_k($score_status)}>ข</option> <option value=\"น\" {$this->chk_value_attend_n($score_status)}>น</option> <option value=\"-\" {$this->chk_value_attend__($score_status)}>-</option> </select> </td> "; } return $data_response; } public function get_score_col_total($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT SUM(score_status) as sum_score_status FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); return $this->rows[0]['sum_score_status']; } public function get_all_attendID($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT count(*) as num_attend_row FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); $num_attend_row=$this->rows[0]['num_attend_row']; $this->sql ="SELECT * FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { if ($num_row_std==$no_std) { if ($num_set==$num_attend_row) { $attendID.=$value['DataID']; }else{ $attendID.=$value['DataID'].'-'; } }else{ $attendID.=$value['DataID'].'-'; } $num_set++; } return $attendID; } public function get_detail_std($coures_id_list_val,$start_data,$end_data,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $all_attendID.=$this->get_all_attendID($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std); $score_col=$this->get_score_col($std_ID,$registed_courseID,$start_data,$end_data); $score_col_total=$this->get_score_col_total($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std); $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$fname.' '.$lname.'</td> '.$score_col['score_col'].' <td>'.$score_col_total.'</td> </tr> '; $no_std++; } $data_response['all_attendID'].=$all_attendID; return $data_response; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data='p'; }else{ $data='m'; } return $data; } public function get_registed_courseID($coures_id_list_val,$term_set,$year_set){ $data_response = array(); $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_std_id_all($coures_id_list_val,$room_search){ $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; if ($num_row_std==$no_std) { $std_id_all.=$std_ID; }else{ $std_id_all.=$std_ID.'-'; } $no_std++; } $data_response=$std_id_all; return $data_response; } public function get_week_list_data($coures_id_list_val,$length_list_val,$room_search){ $data_response = array(); list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start; $detail_std=$this->get_detail_std($coures_id_list_val,$start_data,$end_data,$room_search); $data_response['detail_std']=$detail_std['detail_std']; $data_response['all_attendID']=$detail_std['all_attendID']; $data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); //$data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_week_list($length_list_val){ $data_response = array(); if ($length_list_val=='1-10') { for ($i=1; $i <=10 ; $i++) { $data_response['week_list'].=' <option value="attend_'.$i.'">สัปดาห์ที่ '.$i.'</option>'; $data_response['week_header'].='<td rowspan="3"><p>สัปดาห์ที่ '.$i.'</p></td>'; } }elseif($length_list_val=='11-20'){ for ($i=11; $i <=20 ; $i++) { $data_response['week_list'].=' <option value="attend_'.$i.'">สัปดาห์ที่ '.$i.'</option>'; $data_response['week_header'].='<td rowspan="3"><p>สัปดาห์ที่ '.$i.'</p></td>'; } } $data_response['week_header'].=' <td>รวม</td>'; return json_encode($data_response); } public function search_course_detail($coures_id_list,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level_co']=$class_level.'/'.$room_search; return json_encode($data_response); } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } return json_encode($data_response); } public function get_registed_courseID_set($courseID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$courseID AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_coures_id_list(){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $courseID=$value['DataID']; $registed_courseID=$this->get_registed_courseID_set($courseID,$term_set,$year_set); $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$courseID.'">'.$courseID_long.'</option> '; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='1,2' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$DataID.'">'.$courseID_long.'</option> '; } return json_encode($data_response); } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/regis_student/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_term_year_now"){ echo $class_data->get_term_year_now(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "chk_id"){ $std_ID=$_GET['std_ID']; $card_ID=$_GET['card_ID']; echo $class_data->chk_id($std_ID,$card_ID); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_years"){ echo $class_data->get_years(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_day"){ $mouth=$_GET['mouth']; echo $class_data->get_day($mouth); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $arr_sql = array(); $arr_sql_class_room = array(); $year_main=$_POST['year_main']; $day=$_POST['day']; $mouth=$_POST['mouth']; $years=$_POST['years']-543; $password="<PASSWORD>"; $birthday=$years.'-'.$mouth.'-'.$day; $arr_sql["std_ID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['std_ID'])))."'"; $arr_sql["card_ID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['card_ID'])))."'"; $arr_sql["password"]= "'".MD5($password)."'"; $arr_sql_class_room["std_ID"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['std_ID'])))."'"; $arr_sql_class_room["class_level"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['class_level'])))."'"; $arr_sql_class_room["room"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['room'])))."'"; $arr_sql_class_room["year"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['year_main'])))."'"; $arr_sql_class_room["status"]=1; $arr_sql["name_title"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['name_title'])))."'"; $arr_sql["fname"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['fname'])))."'"; $arr_sql["lname"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['lname'])))."'"; $arr_sql["birthday"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($birthday)))."'"; $arr_sql["blood_group"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['blood_group'])))."'"; $arr_sql["address"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['address'])))."'"; $arr_sql["parent_name_title"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_name_title'])))."'"; $arr_sql["parent_fname"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_fname'])))."'"; $arr_sql["parent_lname"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_lname'])))."'"; $arr_sql["tell"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['tell'])))."'"; $arr_sql["parent_address"]="'".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['parent_address'])))."'"; $arr_sql["cdate"]="now()"; if ($class_data->insert_data($arr_sql,$arr_sql_class_room)) { echo "Y"; }else{ echo "N"; } }<file_sep>/modules/save_score/back/test.php <?php public function get_std_exam($coures_id_list_val,$course_teachingID,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_mid_exam=$this->get_score_mid_exam($std_ID,$course_teachingID); $score_final_exam=$this->get_score_final_exam($std_ID,$course_teachingID); $score_total=$score_mid_exam+$score_final_exam; $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_exam.=$std_ID; }else{ $std_id_all_exam.=$std_ID.'-'; } $data_response.=' <tr> <td>1</td> <td>'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input name="score_mid_exam[]" disabled="disabled" class="select-table-form value_score_mid class_col_set_new_edit class_col_exam_mid text-center" type="text" value="'.$score_mid_exam.'"></td> <td class="relative"><input name="score_final_exam[]" disabled="disabled" class="select-table-form value_score_final class_col_set_new_edit class_col_exam_final text-center" type="text" value="'.$score_final_exam.'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_exam" type="text" hidden="hidden" value="'.$std_id_all_exam.'" name="">'; return $data_response; }<file_sep>/modules/conclusion/class_modules/learning_result_desirable.php <?php class ClassData extends Databases { public function get_loop_data($class_level,$year,$term){ $this->sql ="SELECT DISTINCT(department) AS department,courseID FROM tbl_sub_pp6 WHERE status=1 AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) ORDER BY pp6_ID ASC "; $this->select(); $this->setRows(); $order=1; $amount_std_all=0; $amount_data_desirable_verygood=0; $amount_data_desirable_good=0; $amount_data_desirable_pass=0; $amount_data_desirable_nopass=0; foreach($this->rows as $key => $value) { $department_set=$value['department']; $courseID=$value['courseID']; $department=$this->get_department($department_set); $amount_std=$this->get_amount_std($department_set,$class_level,$year,$term); $desirable=$this->get_desirable($department_set,$class_level,$year,$term); $data_response.=' <tr> <td>'.$order.'</td> <td>'.$courseID.'</td> <td style="text-align:left;padding-left:15px;">'.$department.'</td> <td>'.$amount_std.'</td> <td>'.$desirable['data_desirable_verygood'].'</td> <td>'.$desirable['data_desirable_good'].'</td> <td>'.$desirable['data_desirable_pass'].'</td> <td>'.$desirable['data_desirable_nopass'].'</td> <td></td> </tr> '; $amount_std_all=$amount_std_all+$amount_std; $amount_data_desirable_verygood=$amount_data_desirable_verygood+$desirable['data_desirable_verygood']; $amount_data_desirable_good=$amount_data_desirable_good+$desirable['data_desirable_good']; $amount_data_desirable_pass=$amount_data_desirable_pass+$desirable['data_desirable_pass']; $amount_data_desirable_nopass=$amount_data_desirable_nopass+$desirable['data_desirable_nopass']; } $data_response.=' <tr class="text-middle"> <td colspan="3" style="width: 5%;height: 0px;text-align: center;"> รวม </td> <td>'.$amount_std_all.'</td> <td>'.$amount_data_desirable_verygood.'</td> <td>'.$amount_data_desirable_good.'</td> <td>'.$amount_data_desirable_pass.'</td> <td>'.$amount_data_desirable_nopass.'</td> <td></td> </tr> <tr class="text-middle"> <td colspan="3" style="width: 5%;height: 0px;text-align: center;"> ร้อยละ </td> <td>100.00</td> <td>'.number_format(($amount_data_desirable_verygood*100)/$amount_std_all,2).'</td> <td>'.number_format(($amount_data_desirable_good*100)/$amount_std_all,2).'</td> <td>'.number_format(($amount_data_desirable_pass*100)/$amount_std_all,2).'</td> <td>'.number_format(($amount_data_desirable_nopass*100)/$amount_std_all,2).'</td> <td></td> </tr> <tr class="text-middle"> <td colspan="4" style="width: 5%;height: 0px;text-align: center;"> ภาพรวมคิดเป็นร้อยละ </td> <td colspan="4" style="width: 5%;height: 0px;text-align: center;">100.00</td> <td style="width: 5%;height: 0px;text-align: center;"></td> </tr> '; return $data_response; } public function get_desirable($department_set,$class_level,$year,$term){ $this->sql ="SELECT * FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) "; $this->select(); $this->setRows(); $data_desirable_nopass=0; $data_desirable_pass=0; $data_desirable_good=0; $data_desirable_verygood=0; foreach($this->rows as $key => $value) { $score_desirable=$value['score_desirable']; if ($score_desirable<1) { $data_desirable_nopass++; }elseif($score_desirable<1.5){ $data_desirable_pass++; }elseif($score_desirable<2.5){ $data_desirable_good++; }elseif($score_desirable>=2.5){ $data_desirable_verygood++; } } $data_response['data_desirable_nopass']=$data_desirable_nopass; $data_response['data_desirable_pass']=$data_desirable_pass; $data_response['data_desirable_good']=$data_desirable_good; $data_response['data_desirable_verygood']=$data_desirable_verygood; return $data_response; } public function get_amount_std($department_set,$class_level,$year,$term){ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_sub_pp6 WHERE status=1 AND department=$department_set AND pp6_ID in( SELECT DataID FROM tbl_pp6 WHERE class_level='$class_level' AND term='$term' AND year='$year' ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_desirable_data($class_level,$year,$term,$image_logo,$footer_text_cen_normal){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $class_front_text='ประถมศึกษาปีที่'; }else{ $class_front_text='มัธยมศึกษาปีที่'; } $loop_data=$this->get_loop_data($class_level,$year,$term); $data_response['std_list'].=' <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:16px"> <img class="logo-print-size-level" src="'.$image_logo.'"> <p >รายงานการพัฒนาคุณลักษณะอันพึงประสงค์ตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 20px;">ระดับชั้น <span style="font-weight: normal;">'.$class_front_text.' '.substr($class_level,1).'</span> </span> <span style="margin-right: 20px;">ภาคเรียนที่ <span style="font-weight: normal;">'.$term.'</span> </span> <span>ปีการศึกษา <span style="font-weight: normal;">'.$year.'</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 14px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >ที่</div> </th> <th rowspan="2" class="rotate" style="width: 10%;height: 0px;text-align: center;"> <div >รหัสวิชา</div> </th> <th rowspan="2" style="width: 25%;vertical-align: middle;text-align: center;"> สาระการเรียนรู้ </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >จำนวนนักเรียน</div> </th> <th colspan="4" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >ระดับคุณภาพ</div> </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >หมายเหตุ</div> </th> </tr> <tr class="text-middle"> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> ดีเยี่ยม <br> (3) </th> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> ดี <br> (2) </th> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> ผ่าน <br> (1) </th> <th class="rotate" style="width: 5%;height: 0px;text-align: center;"> ไม่ผ่าน <br> (0) </th> </tr> </thead> <tbody > '.$loop_data.' </tbody> </table> <div style="margin-top:40px;"> '.$footer_text_cen_normal.' </div> </page> </div> '; return $data_response; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_registed_course ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }else{ $name_title="นางสาว"; } return $name_title; } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_department($data){ switch ($data) { case 1: $department='ภาษาไทย'; break; case 2: $department='คณิตศาสตร์'; break; case 3: $department='วิทยาศาสตร์'; break; case 31: $department='วิทยาศาสตร์และเทคโนโลยี'; break; case 4: $department='สังคมศึกษา ศาสนาและวัฒนธรรม'; break; case 41: $department='สังคมศึกษา'; break; case 42: $department='ภูมิศาสตร์'; break; case 43: $department='ประวัติศาสตร์'; break; case 5: $department='สุขศึกษาและพลศึกษา'; break; case 6: $department='ศิลปะ'; break; case 7: $department='การงานอาชีพฯ'; break; case 71: $department='การงานอาชีพ'; break; case 8: $department='ภาษาต่างประเทศ'; break; case 9: $department='หน้าที่พลเมือง'; break; case 10: $department='ศิลปะพื้นบ้าน'; break; case 11: $department='ศักยภาพ'; break; case 12: $department='ภาษาจีน'; break; default: $department=''; } return $department; } public function get_grade($total){ if ($total<50) { $grade='0.0'; }elseif($total<55){ $grade='1.0'; }elseif($total<60){ $grade='1.5'; }elseif($total<65){ $grade='2.0'; }elseif($total<70){ $grade='2.5'; }elseif($total<75){ $grade='3.0'; }elseif($total<80){ $grade='3.5'; }elseif($total>=80){ $grade='4.0'; } return $grade; } }<file_sep>/modules/save_score/back/class_modules.php <?php class ClassData extends Databases { public function get_end_data_find($start_data,$end_data){ $end_data_last=$end_data+1; return $end_data_last-$start_data; } public function set_col_header($length_list_val){ $data_response = array(); list($start_data,$end_data) = split('[-]', $length_list_val); $data_response['end_data_find']=$this->get_end_data_find($start_data,$end_data); return json_encode($data_response); } public function get_score_col_total($std_ID,$registed_courseID){ $num_of_i=0; $this->sql ="SELECT count(score) as num_of_i FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID AND score=-1; "; $this->select(); $this->setRows(); $num_of_i=$this->rows[0]['num_of_i']; $this->sql ="SELECT SUM(score) as score_total FROM tbl_objective_score_std WHERE staID='$std_ID' AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $score_total_data=$this->rows[0]['score_total']; if ($score_total_data==0) { $score_total=0; }else{ $score_total=$score_total_data; } return $score_total+$num_of_i; } public function get_total_proportion($data_id){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$data_id "; $this->select(); $this->setRows(); $data_response['mid_exam'] =$this->rows[0]['mid_exam']; $data_response['final_exam'] =$this->rows[0]['final_exam']; return $data_response; } public function get_total_ob_conclude($data_objective_ob){ $this->sql ="SELECT score FROM tbl_objective_conclude WHERE DataID=$data_objective_ob "; $this->select(); $this->setRows(); return $this->rows[0]['score']; } public function get_score_col($std_ID,$data_objective,$registed_courseID,$start_data){ $arr_id = explode("-", $data_objective); for ($i=0; $i < count($arr_id) ; $i++) { if ($arr_id[$i]=='') { $arr_id[$i]=0; }else{ $arr_id[$i]=$arr_id[$i]; } $total_ob_conclude=$this->get_total_ob_conclude($arr_id[$i]); $this->sql ="SELECT * FROM tbl_objective_score_std WHERE staID='$std_ID' AND objectiveID={$arr_id[$i]} AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $score=0; }else{ if ($score==-1) { $score='ร'; }else{ $score=$score; } } $data_response.='<td class="relative" ><input onkeyup="chk_score_over(this,this.value)" class_name_change="'.$DataID.'" value_set="'.$score.'" data_main_chk_over="'.$total_ob_conclude.'" name="objective_score_std[]" disabled="disabled" class="select-table-form class_col_set_new class_name_'.$DataID.' class_col_'.$start_data.'" type="text" value="'.$score.'"></td>'; $start_data++; } return $data_response; } public function get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$start_data,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); $score_col=$this->get_score_col($std_ID,$data_objective,$registed_courseID,$start_data); $score_col_total=$this->get_score_col_total($std_ID,$registed_courseID); $data_response.='<tr> <td>'.$no_std.'</td> <td style="text-align:left;padding-left:4%;">'.$name_title.$fname.' '.$lname.'</td> '.$score_col.' <td>'.$score_col_total.'</td> </tr> '; $no_std++; } return $data_response; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data='p'; }else{ $data='m'; } return $data; } public function get_std_id_all($coures_id_list_val,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; if ($num_row_std==$no_std) { $std_id_all.=$std_ID; }else{ $std_id_all.=$std_ID.'-'; } $no_std++; } $data_response=$std_id_all; return $data_response; } public function get_proportion_cumulative($coures_id_list_val){ $this->sql ="SELECT SUM(cumulative_before_mid + cumulative_after_mid) as cumulative_sum FROM tbl_proportion WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); return $this->rows[0]['cumulative_sum']; } public function get_objective_list($coures_id_list_val,$length_list_val,$room_search){ $data_response = array(); //$data_response['proportion_cumulative']=$this->get_proportion_cumulative($coures_id_list_val); list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start; $this->sql ="SELECT * FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val LIMIT $find_start,$find_end "; $this->select(); $this->setRows(); $chk_loop=1; foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $no_order=$value['no_order']; $score=$value['score']; $data_response['objective_list'].=' <option value="'.$no_order.'">ข้อที่ '.$no_order.'</option>'; $data_response['ob_title_table_col'].='<td>'.$no_order.'</td>'; $data_response['ob_score_max_table_col'].='<td>'.$score.'</td>'; if ($find_end==$chk_loop) { $data_objective.=$DataID; }else{ $data_objective.=$DataID.'-'; } $chk_loop++; } $data_response['ob_score_max_table_col'].='<td style="background-color:#f3e7f9;">'.$this->get_proportion_cumulative($coures_id_list_val).'</td>'; $registed_courseID=$this->get_registed_courseID($coures_id_list_val); $data_response['registed_courseID']=$registed_courseID; $data_response['detail_std']=$this->get_detail_std($coures_id_list_val,$registed_courseID,$data_objective,$start_data,$room_search); $data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_registed_courseID($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_config($legth_score,$coures_id_list_val,$room_search){ $data_response = array(); if ($legth_score=="save-score-pick") { $data_response=$this->get_pick($coures_id_list_val); }elseif($legth_score=="save-score-exam"){ $data_response=$this->get_exam($coures_id_list_val,$room_search); }elseif($legth_score=="save-score-desirable"){ $data_response=$this->get_desirable($coures_id_list_val,$room_search); }elseif($legth_score=="save-score-read"){ $data_response=$this->get_read($coures_id_list_val,$room_search); } return json_encode($data_response); } public function get_selected($num_loop_class){ if (isset($_SESSION['status_active'])) { $active_length=$_SESSION['status_active']; $text='chk_active_'.$num_loop_class; if($active_length==$text){ return "selected"; } } } public function search_course_detail($coures_id_list,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level_co']=$class_level.'/'.$room_search; return json_encode($data_response); } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } return json_encode($data_response); } public function get_coures_id_list(){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$DataID.'">'.$courseID_long.'</option> '; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='1,2' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$DataID.'">'.$courseID_long.'</option> '; } return json_encode($data_response); } public function get_course_teachingID($DataID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_propotion_total($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_proportion WHERE courseID=$coures_id_list_val"; $this->select(); $this->setRows(); $data_response['mid_exam']=$this->rows[0]['mid_exam']; $data_response['final_exam']=$this->rows[0]['final_exam']; $mid_exam=$this->rows[0]['mid_exam']; $final_exam=$this->rows[0]['final_exam']; $data_response['total']=$mid_exam+$final_exam; return $data_response; } public function get_std_exam($coures_id_list_val,$course_teachingID,$room_search){ $total_total_proportion=$this->get_total_proportion($coures_id_list_val); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_mid_exam=$this->get_score_mid_exam($std_ID,$course_teachingID); $score_final_exam=$this->get_score_final_exam($std_ID,$course_teachingID); $score_total=$score_mid_exam['score']+$score_final_exam['score']; $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_exam.=$std_ID; }else{ $std_id_all_exam.=$std_ID.'-'; } $data_response.=' <tr> <td>'.$num_set.'</td> <td style="text-align:left;padding-left:10%;">'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input onkeyup="chk_score_over(this,this.value)" class_name_change="1'.$score_mid_exam['DataID'].'" data_main_chk_over="'.$total_total_proportion['mid_exam'].'" value_set="'.$score_mid_exam['score'].'" name="score_mid_exam[]" disabled="disabled" class="class_name_1'.$score_mid_exam['DataID'].' select-table-form value_score_mid class_col_set_new_edit class_col_exam_mid text-center" type="text" value="'.$score_mid_exam['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over(this,this.value)" class_name_change="2'.$score_final_exam['DataID'].'" data_main_chk_over="'.$total_total_proportion['final_exam'].'" value_set="'.$score_final_exam['score'].'" name="score_final_exam[]" disabled="disabled" class="class_name_2'.$score_final_exam['DataID'].' select-table-form value_score_final class_col_set_new_edit class_col_exam_final text-center" type="text" value="'.$score_final_exam['score'].'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_exam" type="text" hidden="hidden" value="'.$std_id_all_exam.'" name="">'; return $data_response; } public function get_score_final_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_final_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_score_mid_exam($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_mid_exam_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='' || $score==0) { $data_response['score']=0; }else{ if ($score==-1) { $data_response['score']='ร'; }else{ $data_response['score']=$score; } } return $data_response; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_score_desirable_1($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_1 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_2($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_2 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_3($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_3 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_4($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_4 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_5($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_5 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_6($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_6 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_7($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_7 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_desirable_8($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_desirable_8 WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_std_desirable($coures_id_list_val,$course_teachingID,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $score_desirable_1=$this->get_score_desirable_1($std_ID,$course_teachingID); $score_desirable_2=$this->get_score_desirable_2($std_ID,$course_teachingID); $score_desirable_3=$this->get_score_desirable_3($std_ID,$course_teachingID); $score_desirable_4=$this->get_score_desirable_4($std_ID,$course_teachingID); $score_desirable_5=$this->get_score_desirable_5($std_ID,$course_teachingID); $score_desirable_6=$this->get_score_desirable_6($std_ID,$course_teachingID); $score_desirable_7=$this->get_score_desirable_7($std_ID,$course_teachingID); $score_desirable_8=$this->get_score_desirable_8($std_ID,$course_teachingID); $score_total=round(($score_desirable_1['score']+$score_desirable_2['score']+$score_desirable_3['score']+$score_desirable_4['score']+$score_desirable_5['score']+$score_desirable_6['score']+$score_desirable_7['score']+$score_desirable_8['score'])/8,2); $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_desirable.=$std_ID; }else{ $std_id_all_desirable.=$std_ID.'-'; } $data_response.=' <tr> <td>'.$num_set.'</td> <td style="text-align:left;padding-left:4%;">'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input name="score_final_desirable_1[]" value_set="'.$score_desirable_1['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="1'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_1'.$score_desirable_1['DataID'].' select-table-form value_score_desirable_1 class_col_set_new_edit class_col_desirable_1 text-center" type="text" value="'.$score_desirable_1['score'].'"></td> <td class="relative"><input name="score_final_desirable_2[]" value_set="'.$score_desirable_2['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="2'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_2'.$score_desirable_2['DataID'].' select-table-form value_score_desirable_2 class_col_set_new_edit class_col_desirable_2 text-center" type="text" value="'.$score_desirable_2['score'].'"></td> <td class="relative"><input name="score_final_desirable_3[]" value_set="'.$score_desirable_3['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="3'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_3'.$score_desirable_3['DataID'].' select-table-form value_score_desirable_3 class_col_set_new_edit class_col_desirable_3 text-center" type="text" value="'.$score_desirable_3['score'].'"></td> <td class="relative"><input name="score_final_desirable_4[]" value_set="'.$score_desirable_4['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="4'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_4'.$score_desirable_4['DataID'].' select-table-form value_score_desirable_4 class_col_set_new_edit class_col_desirable_4 text-center" type="text" value="'.$score_desirable_4['score'].'"></td> <td class="relative"><input name="score_final_desirable_5[]" value_set="'.$score_desirable_5['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="5'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_5'.$score_desirable_1['DataID'].' select-table-form value_score_desirable_5 class_col_set_new_edit class_col_desirable_5 text-center" type="text" value="'.$score_desirable_5['score'].'"></td> <td class="relative"><input name="score_final_desirable_6[]" value_set="'.$score_desirable_6['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="6'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_6'.$score_desirable_6['DataID'].' select-table-form value_score_desirable_6 class_col_set_new_edit class_col_desirable_6 text-center" type="text" value="'.$score_desirable_6['score'].'"></td> <td class="relative"><input name="score_final_desirable_7[]" value_set="'.$score_desirable_7['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="7'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_7'.$score_desirable_7['DataID'].' select-table-form value_score_desirable_7 class_col_set_new_edit class_col_desirable_7 text-center" type="text" value="'.$score_desirable_7['score'].'"></td> <td class="relative"><input name="score_final_desirable_8[]" value_set="'.$score_desirable_8['score'].'" onkeyup="chk_score_over_fix(this,this.value)" class_name_change="8'.$score_desirable_1['DataID'].'" disabled="disabled" class="class_name_8'.$score_desirable_8['DataID'].' select-table-form value_score_desirable_8 class_col_set_new_edit class_col_desirable_8 text-center" type="text" value="'.$score_desirable_8['score'].'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_desirable" type="text" hidden="hidden" value="'.$std_id_all_desirable.'" name="">'; return $data_response; } public function get_score_read($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_read_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_write($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_write_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_score_think($std_ID,$course_teachingID){ $data_response = array(); $this->sql ="SELECT * FROM tbl_think_score WHERE course_teachingID=$course_teachingID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $data_response['DataID']=$this->rows[0]['DataID']; $score=$this->rows[0]['score']; if ($score=='') { $data_response['score']=0; }else{ $data_response['score']=$score; } return $data_response; } public function get_std_read($coures_id_list_val,$course_teachingID,$room_search){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $get_score_read=$this->get_score_read($std_ID,$course_teachingID); $get_score_write=$this->get_score_write($std_ID,$course_teachingID); $get_score_think=$this->get_score_think($std_ID,$course_teachingID); $score_total=round(($get_score_read['score']+$get_score_write['score']+$get_score_think['score'])/3,2); $fname=$value['fname']; $lname=$value['lname']; if ($num_row_std==$num_set) { $std_id_all_read.=$std_ID; }else{ $std_id_all_read.=$std_ID.'-'; } $data_response.=' <tr> <td>'.$num_set.'</td> <td style="text-align:left;padding-left:10%;">'.$name_title.$fname.' '.$lname.'</td> <td class="relative "><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_read['score'].'" class_name_change="1'.$get_score_read['DataID'].'" name="score_read[]" disabled="disabled" class="class_name_1'.$get_score_read['DataID'].' select-table-form value_score_read class_col_set_new_edit class_col_read text-center" type="text" value="'.$get_score_read['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_write['score'].'" class_name_change="2'.$get_score_write['DataID'].'" name="score_write[]" disabled="disabled" class="class_name_2'.$get_score_write['DataID'].' select-table-form value_score_write class_col_set_new_edit class_col_write text-center" type="text" value="'.$get_score_write['score'].'"></td> <td class="relative"><input onkeyup="chk_score_over_fix(this,this.value)" value_set="'.$get_score_think['score'].'" class_name_change="3'.$get_score_think['DataID'].'" name="score_think[]" disabled="disabled" class="class_name_3'.$get_score_think['DataID'].' select-table-form value_score_think class_col_set_new_edit class_col_think text-center" type="text" value="'.$get_score_think['score'].'"></td> <td>'.$score_total.'</td> </tr> '; $num_set++; } $data_response.='<input id="std_id_all_read" type="text" hidden="hidden" value="'.$std_id_all_read.'" name="">'; return $data_response; } public function get_read($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $std_read=$this->get_std_read($coures_id_list_val,$course_teachingID,$room_search); $data_response=' <input id="teaching_id_find" type="text" hidden="hidden" name="" value='.$course_teachingID.'> <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div class="row pd-50 stage-set" > <div class="col-sm-12 col-xs-12 mt-nega-20"> <div class="set-line"> <p class="text-bold text-inline">คะแนนอ่าน เขียน คิด วิเคราะห์</p> </div> </div> </div> <div class="ml-36 mr-50 mt-nega-50" > <div class="col-sm-12 col-xs-12"> <div class="set-line"> <p class="text-inline">คะแนน</p> <select onchange="open_edit_read()" id="read_select" name="read_select" class="form-control search-drop-sub-id mr-30"> <option value="read">การอ่าน</option> <option value="write">การเขียน</option> <option value="think">การคิด วิเคราะห์</option> </select> <p class=" text-inline" >ระบุคะแนนทั้งหมดเป็น</p> <div class="input-group form-serch-width-small"> <input id="input_set_data_seem_read" type="text" class="form-control form-set" aria-describedby="basic-addon1"> </div> <div class="btn-search-save-score"> <div id="btn_set_data_seem_read" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </div> </div> </div> <div class=" ml-50 mr-50 mt-30" > <div class="row"> <div class="col-md-12"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "4" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "4" width="50%" style=" vertical-align: middle;">ชื่อ-สกุล</td> </tr> <tr> <td colspan="10">คะแนนอ่าน เขียน คิด วิเคราะห์</td> </tr> <tr> <td width="120px">การอ่าน</td> <td width="120px">การเขียน</td> <td width="120px">การคิด วิเคราะห์</td> <td width="120px">รวมเฉลี่ย</td> </tr> <tr class="table-bg-white"> <td>3</td> <td>3</td> <td>3</td> <td>3.00</td> </tr> </thead> <tbody class="body-table"> '.$std_read.' </tbody> </table> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <div class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalReadScore" class="btn-violet"> บันทึก </div> </div> </div> '; return $data_response; } public function get_desirable($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $std_desirable=$this->get_std_desirable($coures_id_list_val,$course_teachingID,$room_search); $data_response=' <input id="teaching_id_find" type="text" hidden="hidden" name="" value='.$course_teachingID.'> <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div class="row pd-50 stage-set" > <div class="col-sm-12 col-xs-12 mt-nega-20"> <div class="set-line"> <p class="text-bold text-inline">คะแนนคุณลักษณะอันพึงประสงค์</p> </div> </div> </div> <div class="ml-36 mr-50 mt-nega-50" > <div class="col-sm-12 col-xs-12"> <div class="set-line"> <p class="text-inline">คะแนน</p> <select onchange="open_edit_desirable()" id="desirable_select" name="desirable_select" class="form-control search-drop-sub-id mr-30"> <option value="desirable_1">ข้อที่ 1</option> <option value="desirable_2">ข้อที่ 2</option> <option value="desirable_3">ข้อที่ 3</option> <option value="desirable_4">ข้อที่ 4</option> <option value="desirable_5">ข้อที่ 5</option> <option value="desirable_6">ข้อที่ 6</option> <option value="desirable_7">ข้อที่ 7</option> <option value="desirable_8">ข้อที่ 8</option> </select> <p class=" text-inline" >ระบุคะแนนทั้งหมดเป็น</p> <div class="input-group form-serch-width-small"> <input id="input_set_data_seem_desirable" type="text" class="form-control form-set" aria-describedby="basic-addon1"> </div> <div class="btn-search-save-score"> <div id="btn_set_data_seem_desirable" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </div> </div> </div> <div class=" ml-50 mr-50 mt-30" > <div class="row"> <div class="col-md-12"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "4" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "4" width="35%" style=" vertical-align: middle;">ชื่อ-สกุล</td> </tr> <tr> <td colspan="10">คะแนนคุณลักษณะอันพึงประสงค์</td> </tr> <tr> <td>ข้อที่ 1</td> <td>ข้อที่ 2</td> <td>ข้อที่ 3</td> <td>ข้อที่ 4</td> <td>ข้อที่ 5</td> <td>ข้อที่ 6</td> <td>ข้อที่ 7</td> <td>ข้อที่ 8</td> <td>รวมเฉลี่ย</td> </tr> <tr class="table-bg-white"> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3</td> <td>3.00</td> </tr> </thead> <tbody class="body-table"> '.$std_desirable.' </tbody> </table> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <div class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalDesirableScore" class="btn-violet"> บันทึก </div> </div> </div> '; return $data_response; } public function get_exam($coures_id_list_val,$room_search){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $propotion_total=$this->get_propotion_total($coures_id_list_val); $course_teachingID=$this->get_course_teachingID($coures_id_list_val,$term_set,$year_set); $std_exam=$this->get_std_exam($coures_id_list_val,$course_teachingID,$room_search); $data_response=' <input id="teaching_id_find" type="text" hidden="hidden" name="" value='.$course_teachingID.'> <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div id="course_detal_box" class="ml-50 mr-50 mt-10" > <div class="row"> <div class="box-search-depart"> <table> <tbody style="border: none;"> <tr > <td class="text-before-box3 text-bold" style="float: right;padding-left:45px;"> คะแนน </td> <td width="200px"> <form> <select onchange="open_edit_exam()" id="exam_score_select" name="exam_score_select" class="form-control search-drop-length-ob mt-5"> <option value="mid">กลางภาค</option> <option value="final">ปลายภาค</option> </select> </form> </td> </tr> </tbody> <table> </div> </div> </div> <div class=" ml-50 mr-50 mt-30" > <div class="row"> <div class="col-md-12"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "4" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "4" width="60%" style=" vertical-align: middle;">ชื่อ-สกุล</td> </tr> <tr> <td colspan="10">คะแนนสอบ</td> </tr> <tr> <td>กลางภาค</td> <td>ปลายภาค</td> <td>รวม</td> </tr> <tr class="table-bg-white"> <td>'.$propotion_total['mid_exam'].'</td> <td>'.$propotion_total['final_exam'].'</td> <td>'.$propotion_total['total'].'</td> </tr> </thead> <tbody class="body-table"> '.$std_exam.' </tbody> </table> </div> </div> <div class="btn-group-set-add-delete row pd-60 "> <div class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalExamScore" class="btn-violet"> บันทึก </div> </div> </div> '; return $data_response; } public function get_pick($coures_id_list_val,$active_length){ $data_response = array(); $this->sql ="SELECT count(*) as num_row FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; $num=0; $loop_set=ceil($num_row/10); $scrap=$num_row%10; if ($num_row<=10) { if ($num_row==10) { $length_list="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-10\">ตัวชี้วัดข้อที่ 1-10 </option>" ; }elseif($num_row<10){ if ($num_row==1) { $length_list="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-1\">ตัวชี้วัดข้อที่ 1</option>" ; }else{ $length_list="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-{$num_row}\">ตัวชี้วัดข้อที่ 1-{$num_row} </option>" ; } } }else{ $num_loop_class=1; for ($i=1; $i <=$loop_set ; $i++) { if ($i==1) { $length_list.="<option class=\"chk_active_1\" status=\"chk_active_1\" value=\"1-10\">ตัวชี้วัดข้อที่ 1-10 </option>" ; }else{ if ($loop_set==$i) { if ($scrap==0) { $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$loop_set}0\">ตัวชี้วัดข้อที่ {$num}1-{$loop_set}0 </option>" ; }else{ if ($scrap==1) { $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$num}1\">ตัวชี้วัดข้อที่ {$num}1 </option>" ; }else{ $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$num}{$scrap}\">ตัวชี้วัดข้อที่ {$num}1-{$num}{$scrap} </option>" ; } } }else{ $length_list.="<option {$this->get_selected($num_loop_class)} class=\"chk_active_{$num_loop_class}\" status=\"chk_active_{$num_loop_class}\" value=\"{$num}1-{$i}0\">ตัวชี้วัดข้อที่ {$num}1-{$i}0 </option>" ; } } $num++; $num_loop_class++; } } $this->sql ="SELECT no_order,detail FROM tbl_objective_conclude WHERE courseID=$coures_id_list_val ORDER BY no_order ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $no_order=$value['no_order']; $detail=$value['detail']; $objective_conclude_desc.=' <tr> <td width="80px">ตัวชี้วัดที่ '.$no_order.'</td> <td >'.$detail.'</td> </tr> '; } $data_response=' <div id="hr-co-text-depart_course" class="row"> <div class="hr-co-text-depart"></div> </div> <div id="text_header_config" class="row pd-50 stage-set" > <div class="col-sm-12 col-xs-12 mt-nega-20"> <div class="set-line"> <p class="text-bold text-before-box fs-18">คะแนนเก็บ</p> </div> </div> </div> <div id="course_config_box" class="ml-36 mr-50 mt-nega-50" > <div class="col-sm-12 col-xs-12"> <div class="set-line"> <div id="rate_score_box" class="col-sm-12 col-xs-12" style="display: block;"> <div class="row"> <table> <tbody style="border: none;"> <tr > <td class="text-before-box3 text-bold" style="float: right;"> ช่วงคะแนน </td> <td width="250px"> <select onchange="get_objective_list()" id="length_list_val" name="length_list_val" class="form-control search-drop-length-ob mt-5"> '.$length_list.' </select> </td> </tr> <tr > <td class="text-before-box3 text-bold" style="float: right;"> คะแนน </td> <td width="200px"> <select onchange="open_edit_score()" id="objective_list" name="objective_list" class="form-control search-drop-length-ob mt-5"> </select> </td> <td class="text-before-box3 text-bold" style="float: right;"> ระบุคะแนนทั้งหมดเป็น </td> <td> <div class="input-group form-serch-width-small"> <input id="input_set_data_seem" type="text" class="form-control form-set" aria-describedby="basic-addon1"> </div> </td> <td> <div class="btn-search-save-score "> <div id="btn_set_data_seem" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <!--table--> <div class=" ml-50 mr-50 mt-80" > <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped-violet border-set-violet" style="text-align: center;"> <thead class="header-table"> <tr class="text-middle"> <td rowspan = "5" width="8%" style=" vertical-align: middle;">เลขที่</td> <td rowspan = "5" width="40%" style=" vertical-align: middle;">ชื่อ-สกุล</td> <td colspan="11">คะแนนเก็บ</td> </tr> <tr> <td id="end_data_find" colspan="10">ตัวชี้วัดทื่/คะแนน</td> <td rowspan = "2">รวม</td> </tr> <tr id="ob_title_table_col"> </tr> <tr id="ob_score_max_table_col" class="table-bg-white"> </tr> </thead> <form id="frm_objective_score_std"> <tbody id="detail_std" class="body-table"> </tbody> </form> </table> </div> </div> </div> <div class="btn-group-set-add-delete row pd-30 "> <div class="btn-grey"> ยกเลิก </div> <div data-toggle="modal" data-target="#modalConScore" class="btn-violet"> บันทึก </div> </div> </div> <div class=" ml-50 mr-50 " > <div class="row"> <div class="col-md-12"> <table> <tbody class="border-none"> '.$objective_conclude_desc.' </tbody> </table> </div> </div> </div> '; return $data_response; } } ?><file_sep>/modules/chk_grade/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_grade"){ echo $class_data->get_grade(); }<file_sep>/index.php <?php /* * Web-Based Instruction PHP Programming * Copyright (C) 2007-2015 * This is the integration file for PHP (versions 5) */ @ob_start(); @session_start(); if( !$_SESSION['ss_user_id'] ){ header('location:login.php'); } if ($_SERVER["SERVER_NAME"]=='192.168.3.11') { header('location:index.php?op=messages-error404'); } require_once('init.php'); /////// CLASS ROLE MANAGEMENT ///// require_once(HOME_PATH.'src/class_role.php'); $role = new ClassRole(); $_db = new Databases(); $user_role_id = (int)$_SESSION['ss_user_id']; function cURLData($url, $data){ $postData = http_build_query($data); $ch = curl_init(); curl_setopt_array( $ch, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData, CURLOPT_FOLLOWLOCATION => true )); $response = curl_exec($ch); curl_close ($ch); //close curl handle return $response; } $BACKOFFICE_ACCOUNT_NAME = "{$_SESSION['ss_prefix_name']} {$_SESSION['ss_first_name']} {$_SESSION['ss_last_name']}"; //BODY_PAGE if(!empty($_GET['op'])){ $OPURL = trim($_GET['op']); $GETOP = explode("-",$OPURL); $OPEN_PAGE = "modules/".$GETOP[0]; $MODAL_PAGE = "modules/".$GETOP[0]."/modal.php"; $CONFIG_PAGE = "{$OPEN_PAGE}/{$GETOP[1]}.php"; $CONFIG_JS_PAGE = "{$OPEN_PAGE}/{$GETOP[1]}.js"; $CONFIG_CSS_PAGE = "{$OPEN_PAGE}/{$GETOP[1]}.css"; if (empty($GETOP[1]) || !file_exists($CONFIG_PAGE)) { header('location:index.php?op=messages-error404'); } }else{ $OPEN_PAGE = "modules/home"; $CONFIG_PAGE = $OPEN_PAGE."/index.php"; $CONFIG_JS_PAGE = $OPEN_PAGE."/index.js"; $CONFIG_CSS_PAGE = $OPEN_PAGE."/index.css"; $MODAL_PAGE = $OPEN_PAGE."/modal.php"; } $POSTDATA = array(); foreach ($_GET as $key => $value) { $POSTDATA[$key] = $value; } foreach ($_POST as $key => $value) { $POSTDATA[$key] = $value; } //OTHER_JS_PAGE $CONFIG_JS_PAGE = (file_exists($CONFIG_JS_PAGE)) ? '<script src="'.$CONFIG_JS_PAGE.'" type="text/javascript"></script>' : ''; $CONFIG_CSS_PAGE = (file_exists($CONFIG_CSS_PAGE)) ? '<link href="'.$CONFIG_CSS_PAGE.'" rel="stylesheet" type="text/css" />' : ''; $view_user_ath = $role->ath_chk_role($user_role_id); // USER AUTHEN MENU /*$view_user_ath = $role->ath_user_reletion_tasks('view_user_ath',$user_role_id); $view_acp = $role->ath_user_reletion_tasks('view_acp',$user_role_id); $view_prt = $role->ath_user_reletion_tasks('view_prt',$user_role_id); $view_mst = $role->ath_user_reletion_tasks('view_mst',$user_role_id); $view_mct = $role->ath_user_reletion_tasks('view_mct',$user_role_id); $view_eps = $role->ath_user_reletion_tasks('view_eps',$user_role_id); $reset_rps = $role->ath_user_reletion_tasks('reset_rps',$user_role_id); $view_usr = $role->ath_user_reletion_tasks('view_usr',$user_role_id);*/ ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>ระบบวัดและประเมินผล</title> <!-- Bootstrap --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/custom.css" rel="stylesheet"> <link href="assets/css/margin-padding.css" rel="stylesheet"> <link rel="icon" type="image/gif/png" href="assets/images/logo.png"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" media="screen and (max-width:768px)" href="assets/css/extrasmall.css"> <link rel="stylesheet" type="text/css" media="screen and (min-width:768px)" href="assets/css/small.css"> <link rel="stylesheet" type="text/css" media="screen and (min-width:992px)" href="assets/css/medium.css"> <link rel="stylesheet" type="text/css" media="screen and (min-width:1200px)" href="assets/css/large.css"> <link href="assets/css/responsive.css" rel="stylesheet"> <link href="assets/css/modal-alert.css" rel="stylesheet"> <!--[if lte IE 9]> <link href="assets/pages/css/ie9.css" rel="stylesheet" type="text/css" /> <![endif]--> <script type="text/javascript"> window.onload = function() { // fix for windows 8 if (navigator.appVersion.indexOf("Windows NT 6.2") != -1) document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="assets/pages/css/windows.chrome.fix.css" />' } var _get = function () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = pair[1]; // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]], pair[1] ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(pair[1]); } } return query_string; } (); </script> </head> <body class="fixed-header" style="background-color: white;"> <section class="nav-tab"> <div class="container-flult" > <?php include(HOME_PATH."includes/mobile-menu.php");?> <?php include(HOME_PATH."includes/left-tab.php");?> <div class="col-sm-9"><!-- user tab--> <?php include(HOME_PATH."includes/name-tab.php");?> <div class="row main-content" id="content"><!-- main content--> <?php include(HOME_PATH.$CONFIG_PAGE);?> </div> </div> </div> </section> <?php include(HOME_PATH.$MODAL_PAGE);?> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script type="text/javascript" src="assets/js/jquery.js"></script> <script type="text/javascript" src="assets/js/jquery.nailthumb.1.1.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/custom.js"></script> <script src="assets/js/pdfmake.min.js"></script> <script src="assets/js/vfs_fonts.js"></script> <!-- <script src="assets/js/modal-alert.js"></script>--> <!-- END PAGE LEVEL JS --> <script src="includes/name-tab.js"></script> <?=$CONFIG_JS_PAGE;?> <?=$CONFIG_CSS_PAGE;?> </body> </html> <file_sep>/init.php <?php if( !session_id() ){ session_start(); } $_domain_url = 'http'; if( isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]){ $_domain_url .= 's'; } $_domain_url .= '://'.$_SERVER['SERVER_NAME'].'/'; if( $_SERVER['SERVER_NAME'] != 'localhost' ){ // serverhost define( 'BASE_PATH', dirname(__DIR__).'/'); define( 'MAIN_BACKOFFICE', 'sratong-app/'); }else{ // localhost define('BASE_PATH', str_replace('\\','/',dirname(__DIR__)).'/'); define( 'MAIN_BACKOFFICE', 'sratong-app/'); } define( 'HOME_PATH', BASE_PATH.MAIN_BACKOFFICE); define( 'HOME_URL', $_domain_url.MAIN_BACKOFFICE); define( 'BASE_URL', $_domain_url); // Main Class require_once(HOME_PATH.'config.php'); require_once(HOME_PATH.'src/database.php'); require_once(HOME_PATH.'src/function.php'); define( 'TODAY', date('Y-m-d')); define( 'TOTIME', date('H:i:s')); define( 'DATETIME', date('Y-m-d H:i:s')); define( 'LASTTIME', time()*1000); define( 'MICROTIME', microtime()); define("TITLE_PAGE", "Evaluation System"); <file_sep>/modules/attend_class/class_modules.php <?php class ClassData extends Databases { public function get_day_list($length_list_val,$registed_course_id,$room_search){ $this->sql ="SELECT status,status_form FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE DataID in( SELECT registed_courseID FROM tbl_registed_course_teaching WHERE DataID=$registed_course_id ) ) "; $this->select(); $this->setRows(); $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($status==1) { $sql_condition="AND room='$room_search'"; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="AND room='$room_search'"; }else{ $sql_condition=""; } } $data_response = array(); $this->sql ="SELECT COUNT(*) as num_attend_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id $sql_condition "; $this->select(); $this->setRows(); $data_response['num_attend_day']=$this->rows[0]['num_attend_day']; $data_response['week_title']='สัปดาห์ที่ '.$length_list_val.''; $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id $sql_condition ORDER BY attend_class_week_listID ASC "; $this->select(); $this->setRows(); $data_count=0; foreach($this->rows as $key => $value) { $attend_class_week_listID=$value['attend_class_week_listID']; $day_name=$this->get_day_name($attend_class_week_listID); $data_response['week_header'].='<td class="set_header_width" width="70px">'.$day_name.'</td>'; $data_count++; } $data_response['week_header'].='<td id="header_sum_score">0</td>'; $data_response['week_header'].='<td >100</td>'; $data_response['data_count']=$data_count; echo json_encode($data_response); } public function get_day_name($day_id){ $this->sql ="SELECT * FROM tbl_attend_class_week_list WHERE DataID=$day_id "; $this->select(); $this->setRows(); return $this->rows[0]['name']; } public function set_hr($registed_course_id,$value_day,$hr_set){ $this->sql ="UPDATE tbl_set_attend_day SET hr=$hr_set WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$value_day"; $this->query(); $this->sql ="SELECT DataID FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$value_day "; $this->select(); $this->setRows(); $DataID=$this->rows[0]['DataID']; $this->sql ="DELETE FROM tbl_attend_class_std WHERE set_attend_day_id=$DataID" ; $this->query(); echo json_encode('1'); } public function set_day($registed_course_id,$value_day,$hr_set,$room_search,$coures_id_list_val){ $this->sql ="SELECT COUNT(*) as num_row_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$value_day AND room='$room_search' "; $this->select(); $this->setRows(); $num_row_day=$this->rows[0]['num_row_day']; if ($num_row_day==0) { $this->sql ="SELECT hr_learn,class_level FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $hr_learn=$this->rows[0]['hr_learn']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $main_hr_set=40; }else{ $main_hr_set=20; } $this->sql ="SELECT SUM(hr) as amount_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND room='$room_search' "; $this->select(); $this->setRows(); $amount_hr=$this->rows[0]['amount_hr']; $find_hr_amount_now=$main_hr_set*($amount_hr+$hr_set); if ($find_hr_amount_now<=$hr_learn) { $this->sql ="INSERT INTO tbl_set_attend_day(registed_course_teachingID,attend_class_week_listID,hr,room) VALUES($registed_course_id,$value_day,$hr_set,'$room_search')"; $this->query(); $data_response=1; }else{ $data_response=0; } }else{ $this->sql ="DELETE FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$value_day AND room='$room_search'" ; $this->query(); $data_response=1; } echo json_encode($data_response); } public function get_hr_list($hr){ if ($hr==1) { $data_response=' <option selected value="1">1</option> <option value="2">2</option> <option value="3">3</option> '; }elseif($hr==2) { $data_response=' <option value="1">1</option> <option selected value="2">2</option> <option value="3">3</option> '; }elseif($hr==3) { $data_response=' <option value="1">1</option> <option value="2">2</option> <option selected value="3">3</option> '; } return $data_response; } public function get_day_set($registed_course_id,$room_search){ $this->sql ="SELECT status,status_form FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE DataID in( SELECT registed_courseID FROM tbl_registed_course_teaching WHERE DataID=$registed_course_id ) ) "; $this->select(); $this->setRows(); $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($status==1) { $sql_condition="AND room='$room_search'"; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="AND room='$room_search'"; }else{ $sql_condition=""; } } $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id $sql_condition "; $this->select(); $this->setRows(); $monday=""; $tuesday=""; $wednesday =""; $thursday =""; $friday=""; $monday_hr="disabled"; $tuesday_hr="disabled"; $wednesday_hr="disabled"; $thursday_hr="disabled"; $friday_hr="disabled"; $hr_list_1='<option value="1">1</option><option value="2">2</option><option value="3">3</option>'; $hr_list_2='<option value="1">1</option><option value="2">2</option><option value="3">3</option>'; $hr_list_3='<option value="1">1</option><option value="2">2</option><option value="3">3</option>'; $hr_list_4='<option value="1">1</option><option value="2">2</option><option value="3">3</option>'; $hr_list_5='<option value="1">1</option><option value="2">2</option><option value="3">3</option>'; foreach($this->rows as $key => $value) { $day_find=$value['attend_class_week_listID']; $hr=$value['hr']; if ($day_find==1) { $monday='checked'; $monday_hr=""; $hr_list_1=$this->get_hr_list($hr); } if ($day_find==2) { $tuesday='checked'; $tuesday_hr=""; $hr_list_2=$this->get_hr_list($hr); } if ($day_find==3) { $wednesday='checked'; $wednesday_hr=""; $hr_list_3=$this->get_hr_list($hr); } if ($day_find==4) { $thursday='checked'; $thursday_hr=""; $hr_list_4=$this->get_hr_list($hr); } if ($day_find==5) { $friday='checked'; $friday_hr=""; $hr_list_5=$this->get_hr_list($hr); } } $data_response['btn_place']=' <td class="text-before-box3 text-bold mt-10" style="float: right;"> วันที่สอน </td> <td> <div data-toggle="modal" data-target="#modalSetTime" class="btn-violet"> ระบุวันที่สอน </div> </td> '; $data_response['modal_group_set']=' <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input class="day_set_1" onclick="set_day(this)" '.$monday.' type="checkbox" name="day_set" value="1">จันทร์</label> </div> <div> <select '.$monday_hr.' onchange="set_hr(this,1)" style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_1"> '.$hr_list_1.' </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10 "> <label><input class="day_set_2" onclick="set_day(this)" '.$tuesday.' type="checkbox" name="day_set" value="2">อังคาร</label> </div> <div> <select '.$tuesday_hr.' onchange="set_hr(this,2)" style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_2"> '.$hr_list_2.' </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input class="day_set_3" onclick="set_day(this)" '.$wednesday.' type="checkbox" name="day_set" value="3">พุธ</label> </div> <div> <select '.$wednesday_hr.' onchange="set_hr(this,3)" style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_3"> '.$hr_list_3.' </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input class="day_set_4" onclick="set_day(this)" '.$thursday.' type="checkbox" name="day_set" value="4">พฤหัสบดี</label> </div> <div> <select '.$thursday_hr.' onchange="set_hr(this,4)" style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_4"> '.$hr_list_4.' </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input class="day_set_5" onclick="set_day(this)" '.$friday.' type="checkbox" name="day_set" value="5">ศุกร์</label> </div> <div> <select '.$friday_hr.' onchange="set_hr(this,5)" style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_5"> '.$hr_list_5.' </select> </div> </td> '; echo json_encode($data_response); } public function get_week_between($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data_response=' <option value="1-10">สัปดาห์ที่ 1-10</option> <option value="11-20">สัปดาห์ที่ 11-20</option> <option value="21-31">สัปดาห์ที่ 21-31</option> <option value="31-40">สัปดาห์ที่ 31-40</option> '; }else{ $data_response=' <option value="1-10">สัปดาห์ที่ 1-10</option> <option value="11-20">สัปดาห์ที่ 11-20</option> '; } echo json_encode($data_response); } public function get_count_adttend_class_val($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; echo json_encode($week_name); } /*public function set_count_adttend_class_val($coures_id_list_val,$set_count_adttend_class_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT COUNT(*) as num_row FROM tbl_set_count_adttend_class WHERE registed_courseID =$registed_courseID "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $this->sql ="UPDATE tbl_set_count_adttend_class SET week_name=$set_count_adttend_class_val WHERE registed_courseID=$registed_courseID "; $this->query(); }else{ $this->sql ="INSERT INTO tbl_set_count_adttend_class(registed_courseID,week_name) VALUES($registed_courseID,$set_count_adttend_class_val) "; $this->query(); } }*/ public function chk_value_attend_1($score_status){ if ($score_status=="1") { $data_response="selected"; } return $data_response; } public function chk_value_attend_l($score_status){ if ($score_status=="ล") { $data_response="selected"; } return $data_response; } public function chk_value_attend_p($score_status){ if ($score_status=="ป") { $data_response="selected"; } return $data_response; } public function chk_value_attend_k($score_status){ if ($score_status=="ข") { $data_response="selected"; } return $data_response; } public function chk_value_attend_n($score_status){ if ($score_status=="น") { $data_response="selected"; } return $data_response; } public function chk_value_attend__($score_status){ if ($score_status=="0" || $score_status=="-") { $data_response="selected"; } return $data_response; } public function get_score_col($std_ID,$registed_courseID,$start_data,$end_data){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT * FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $attendID=$value['DataID']; $week=$value['week']; $score_status=$value['score_status']; $data_response['score_col'].=' <td class="relative"> <select name="attend_score_std[]" class="select-table-form class_col_set_new class_col_attend_1 value_attend_week_1"> <option value="1" selected="">1</option> <option value="ล">ล</option> <option value="ป">ป</option> <option value="ข">ข</option> <option value="-">-</option> </select> </td> '; } return $data_response; } public function get_score_col_total($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT SUM(score_status) as sum_score_status FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); return $this->rows[0]['sum_score_status']; } public function get_all_attendID($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT count(*) as num_attend_row FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); $num_attend_row=$this->rows[0]['num_attend_row']; $this->sql ="SELECT * FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { if ($num_row_std==$no_std) { if ($num_set==$num_attend_row) { $attendID.=$value['DataID']; }else{ $attendID.=$value['DataID'].'-'; } }else{ $attendID.=$value['DataID'].'-'; } $num_set++; } return $attendID; } public function get_detail_std_admin($coures_id_list_val,$room_search,$registed_course_teaching_id,$length_list_val,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); if ($status==1) { $sql_condition=" AND tbl_std_class_room.room='$room_search' AND tbl_std_class_room.status=1 AND tbl_std_class_room.year='$year_set' AND"; $sql_condition_count="WHERE tbl_student.std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ if($status_form==25 || $status_form==26 || $status_form==27){ $sql_condition=" AND tbl_std_class_room.room='$room_search' AND tbl_std_class_room.status=1 AND tbl_std_class_room.year='$year_set' AND"; $sql_condition_count="WHERE tbl_student.std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition=" AND tbl_std_class_room.status=1 AND tbl_std_class_room.year='$year_set' AND "; $sql_condition_count="WHERE tbl_student.std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) AND "; } } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student $sql_condition_count std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT tbl_student.std_ID,tbl_student.fname,tbl_student.lname,tbl_student.name_title,tbl_std_class_room.room FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID $sql_condition tbl_student.std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) ORDER BY tbl_std_class_room.class_level,tbl_std_class_room.room, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN tbl_student.std_ID THEN 4 END "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $room=$value['room']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $term_set='1,2'; } $attend_data=$this->get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status,$status,$status_form,$room_search); if($status==1){ $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; }elseif($status==2){ if($status_form==25 || $status_form==26 || $status_form==27){ $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; }else{ $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td>'.$room.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; } } $no_std++; } $data_response['all_attendID'].=$all_attendID; $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id AND room='$room_search' "; $this->select(); $this->setRows(); $num_hr=$this->rows[0]['num_hr']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $week_all=40; }else{ $week_all=20; } $data_response['num_day']=($num_hr)*$week_all; return $data_response; } public function get_detail_std($coures_id_list_val,$room_search,$registed_course_teaching_id,$length_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); if ($status==1) { $sql_condition=" AND tbl_std_class_room.room='$room_search' AND tbl_std_class_room.status=1 AND tbl_std_class_room.year='$year_set' AND"; $sql_condition_count="WHERE tbl_student.std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ if($status_form==25 || $status_form==26 || $status_form==27){ $sql_condition=" AND tbl_std_class_room.room='$room_search' AND tbl_std_class_room.status=1 AND tbl_std_class_room.year='$year_set' AND"; $sql_condition_count="WHERE tbl_student.std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND status=1 AND year='$year_set' ) AND"; }else{ $sql_condition=" AND tbl_std_class_room.status=1 AND tbl_std_class_room.year='$year_set' AND "; $sql_condition_count="WHERE tbl_student.std_ID in( SELECT std_ID FROM tbl_std_class_room WHERE status=1 AND year='$year_set' ) AND "; } } $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student $sql_condition_count std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT tbl_student.std_ID,tbl_student.fname,tbl_student.lname,tbl_student.name_title,tbl_std_class_room.room FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID $sql_condition tbl_student.std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) ORDER BY tbl_std_class_room.room ASC, CASE WHEN name_title LIKE '%dekchai%' THEN 0 WHEN name_title LIKE '%nai%' THEN 1 WHEN name_title LIKE '%dekying%' THEN 2 WHEN name_title LIKE '%nangsaw%'THEN 3 WHEN tbl_student.std_ID THEN 4 END "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $room=$value['room']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $term_set='1,2'; } $attend_data=$this->get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status,$status,$status_form,$room_search); if($status==1){ $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; }elseif($status==2){ if($status_form==25 || $status_form==26 || $status_form==27){ $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; }else{ $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td>'.$std_ID.'</td> <td>'.$room.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; } } $no_std++; } $data_response['all_attendID'].=$all_attendID; $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id AND room='$room_search' "; $this->select(); $this->setRows(); $num_hr=$this->rows[0]['num_hr']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $week_all=40; }else{ $week_all=20; } $data_response['num_day']=($num_hr)*$week_all; return $data_response; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function add_attend($value_loop,$course_teaching_stdID,$set_attend_day_id,$length_list_val,$attend_value_1,$attend_value_2,$attend_value_3){ $this->sql ="DELETE FROM tbl_attend_class_std WHERE set_attend_day_id=$set_attend_day_id AND course_teaching_std_id=$course_teaching_stdID AND week=$length_list_val "; $this->query(); if ($value_loop==3) { $this->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$length_list_val,'$attend_value_1'); "; $this->query(); $this->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$length_list_val,'$attend_value_2'); "; $this->query(); $this->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$length_list_val,'$attend_value_3'); "; $this->query(); }elseif($value_loop==2){ $this->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$length_list_val,'$attend_value_1'); "; $this->query(); $this->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$length_list_val,'$attend_value_2'); "; $this->query(); } elseif($value_loop==1){ $this->sql ="INSERT INTO tbl_attend_class_std(course_teaching_std_id,set_attend_day_id,week,status) VALUES($course_teaching_stdID,$set_attend_day_id,$length_list_val,'$attend_value_1'); "; $this->query(); } echo json_encode("1"); } public function insert_value_in_attend($registed_course_id,$value,$week,$set_attend_day_id,$course_teaching_stdID,$attend_class_week_listID){ $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$attend_class_week_listID "; $this->select(); $this->setRows(); $hr=$this->rows[0]['hr']; if ($hr==$value) { $this->sql ="DELETE FROM tbl_attend_class_std WHERE set_attend_day_id=$set_attend_day_id AND course_teaching_std_id=$course_teaching_stdID AND week=$week "; $this->query(); $data_response['status']='deleted'; }else{ $data_response['status']='no'; $value_loop=$hr-$value; if ($value_loop==3) { $data_response['place']=' <select style="width:75px;" class="form-control search-drop-length-ob mt-5 attend_value_1"> <option value="ล">ลา</option> <option value="ป">ป่วย</option> <option value="ข">ขาด</option> <option value="น">หนี</option> </select> <select style="width:75px;" class="form-control search-drop-length-ob mt-5 attend_value_2"> <option value="ล">ลา</option> <option value="ป">ป่วย</option> <option value="ข">ขาด</option> <option value="น">หนี</option> </select> <select style="width:75px;" class="form-control search-drop-length-ob mt-5 attend_value_3"> <option value="ล">ลา</option> <option value="ป">ป่วย</option> <option value="ข">ขาด</option> <option value="น">หนี</option> </select> <input hidden value="'.$value_loop.'" id="value_loop" type="text" > <input hidden value="'.$course_teaching_stdID.'" id="course_teaching_stdID" type="text" > <input hidden value="'.$set_attend_day_id.'" id="set_attend_day_id" type="text" > '; }elseif ($value_loop==2) { $data_response['place']=' <select style="width:75px;" class="form-control search-drop-length-ob mt-5 attend_value_1"> <option value="ล">ลา</option> <option value="ป">ป่วย</option> <option value="ข">ขาด</option> <option value="น">หนี</option> </select> <select style="width:75px;" class="form-control search-drop-length-ob mt-5 attend_value_2"> <option value="ล">ลา</option> <option value="ป">ป่วย</option> <option value="ข">ขาด</option> <option value="น">หนี</option> </select> <input hidden value="'.$value_loop.'" id="value_loop" type="text" > <input hidden value="'.$course_teaching_stdID.'" id="course_teaching_stdID" type="text" > <input hidden value="'.$set_attend_day_id.'" id="set_attend_day_id" type="text" > '; }elseif ($value_loop==1) { $data_response['place']=' <select style="width:75px;" class="form-control search-drop-length-ob mt-5 attend_value_1"> <option value="ล">ลา</option> <option value="ป">ป่วย</option> <option value="ข">ขาด</option> <option value="น">หนี</option> </select> <input hidden value="'.$value_loop.'" id="value_loop"> <input hidden value="'.$course_teaching_stdID.'" id="course_teaching_stdID" type="text" > <input hidden value="'.$set_attend_day_id.'" id="set_attend_day_id" type="text" > '; } } echo json_encode($data_response); } public function get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status,$status_class,$status_form,$room_search){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; if ($status_class==1) { $sql_condition="AND room='$room_search'"; }else{ if ($status_form==25 || $status_form==26 || $status_form==27) { $sql_condition="AND room='$room_search'"; }else{ $sql_condition=""; } } $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id $sql_condition ORDER BY attend_class_week_listID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $hr=$value['hr']; $attend_class_week_listID=$value['attend_class_week_listID']; $attend_class_std=$this->get_attend_class_std($DataID,$std_ID,$registed_courseID,$length_list_val); $data_list=''; if ($attend_class_std['num_row']>0) { $num_row=$attend_class_std['num_row']; $total_att=$hr-$num_row; for ($i=$hr; $i >=0 ; $i--) { if ($i==$total_att) { $data_list.='<option selected value="'.$i.'">'.$i.'</option> '; }else{ $data_list.='<option value="'.$i.'">'.$i.'</option> '; } } $data_response.=' <td class="relative"> <select onchange="insert_value_in_attend(this.value,'.$length_list_val.','.$DataID.','.$course_teaching_stdID.','.$attend_class_week_listID.')" class="select-table-form class_col_set_new "> '.$data_list.' </select> </td> '; }else{ for ($i=$hr; $i >=0 ; $i--) { $data_list.='<option value="'.$i.'">'.$i.'</option> '; } $data_response.=' <td class="relative"> <select onchange="insert_value_in_attend(this.value,'.$length_list_val.','.$DataID.','.$course_teaching_stdID.','.$attend_class_week_listID.')" class="select-table-form class_col_set_new "> '.$data_list.' </select> </td> '; } } $this->sql ="SELECT COUNT(*) as num_no_class FROM tbl_attend_class_std WHERE course_teaching_std_id=$course_teaching_stdID "; $this->select(); $this->setRows(); $num_no_class=$this->rows[0]['num_no_class']; $this->sql ="SELECT SUM(hr) as num_hr FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id AND room='$room_search' "; $this->select(); $this->setRows(); $num_hr=$this->rows[0]['num_hr']; if ($class_level_status=='p') { $week_all=40; }else{ $week_all=20; } $total_day=$num_hr*$week_all; $total_attend=$total_day-$num_no_class; $data_response.=' <td class="relative"> '.$total_attend.' </td> '; $total_attend_per=round((($total_day-$num_no_class)*100)/$total_day); $data_response.=' <td class="relative"> '.$total_attend_per.' </td> '; return $data_response; } public function get_attend_class_std($set_attend_day_id,$std_ID,$registed_courseID,$length_list_val){ $data_response = array(); $this->sql ="SELECT COUNT(*) as num_row FROM tbl_attend_class_std WHERE set_attend_day_id=$set_attend_day_id AND week=$length_list_val AND course_teaching_std_id IN( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $data_response['num_row']=$this->rows[0]['num_row']; return $data_response; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data='p'; }else{ $data='m'; } return $data; } public function get_registed_courseID($coures_id_list_val,$term_set,$year_set){ $data_response = array(); $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_std_id_all($coures_id_list_val,$room_search){ $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE stdID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE stdID in( SELECT std_ID FROM tbl_std_class_room WHERE room='$room_search' AND year='$year_set' ) AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; if ($num_row_std==$no_std) { $std_id_all.=$std_ID; }else{ $std_id_all.=$std_ID.'-'; } $no_std++; } $data_response=$std_id_all; return $data_response; } public function get_week_list_data_admin($coures_id_list_val,$length_list_val,$room_search,$registed_course_teaching_id,$term_data,$year_data){ $data_response = array(); /* list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start;*/ $detail_std=$this->get_detail_std_admin($coures_id_list_val,$room_search,$registed_course_teaching_id,$length_list_val,$term_data,$year_data); $data_response['detail_std']=$detail_std['detail_std']; $data_response['all_attendID']=$detail_std['all_attendID']; $data_response['num_day']=$detail_std['num_day']; //$data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); //$data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_week_list_data($coures_id_list_val,$length_list_val,$room_search,$registed_course_teaching_id){ $data_response = array(); /* list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start;*/ $detail_std=$this->get_detail_std($coures_id_list_val,$room_search,$registed_course_teaching_id,$length_list_val); $data_response['detail_std']=$detail_std['detail_std']; $data_response['all_attendID']=$detail_std['all_attendID']; $data_response['num_day']=$detail_std['num_day']; //$data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); //$data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_registed_course_id($coures_id_list,$term_set,$year_set){ if ($term_set=='' && $year_set=='') { $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list /*AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) )*/ "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$coures_id_list ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function search_course_detail($coures_id_list,$room_search,$term_data,$year_data){ $data_response = array(); $data_response['registed_course_id']=$this->get_registed_course_id($coures_id_list,$term_data,$year_data); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; $class_level_data=$this->rows[0]['class_level']; $data_response['status_form']=$this->rows[0]['status_form']; $status=$this->rows[0]['status']; if ($status==2) { $data_response['unit']='-'; }else{ $data_response['unit']=$this->rows[0]['unit']; } $status_form=$this->rows[0]['status_form']; $class_level=$this->get_class_level_new($class_level_data); if ($status==1) { $data_response['class_level_co']=$class_level.'/'.$room_search; }elseif($status==2){ if ($status_form==25 || $status_form==26 || $status_form==27) { $data_response['class_level_co']=$class_level.'/'.$room_search; }else{ $data_response['class_level_co']=$class_level; } } if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6') { for ($i=1; $i <=40 ; $i++) { $data_response['week_menu_data'].=' <option value="'.$i.'">สัปดาห์ที่ '.$i.'</option> '; } }else{ for ($i=1; $i <=20 ; $i++) { $data_response['week_menu_data'].=' <option value="'.$i.'">สัปดาห์ที่ '.$i.'</option> '; } } echo json_encode($data_response); } public function get_class_level_admin($coures_id_list_val,$term_set,$year_set){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['status']=$this->rows[0]['status']; $data_response['status_form']=$this->rows[0]['status_form']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6') { $term_set='1,2'; } $user_status=$_SESSION['ss_status']; $user_id=$_SESSION['ss_user_id']; if ($user_status==1) { $this->sql ="SELECT room FROM tbl_room_teacher WHERE course_teacherID in( SELECT DataID FROM tbl_course_teacher WHERE teacher_id=$user_id AND regis_course_id in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; }else{ $this->sql =" SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT std_ID FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ) ORDER BY room ASC "; } $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $chk_room_export=$this->get_chk_room_export_teacher($room,$term_set,$year_set,$coures_id_list_val,$user_status); if ($user_status==2) { if ($chk_room_export>0) { $data_response['room'].=' <option>'.$room.'</option>'; } }else{ if ($chk_room_export==0) { $data_response['room'].=' <option>'.$room.'</option>'; } } } return json_encode($data_response); } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['status']=$this->rows[0]['status']; $data_response['status_form']=$this->rows[0]['status_form']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6') { $term_set='1,2'; } $user_status=$_SESSION['ss_status']; $user_id=$_SESSION['ss_user_id']; if ($user_status==1) { $this->sql ="SELECT room FROM tbl_room_teacher WHERE course_teacherID in( SELECT DataID FROM tbl_course_teacher WHERE teacher_id=$user_id AND regis_course_id in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; }else{ $this->sql =" SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT std_ID FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ) ORDER BY room ASC "; } $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $chk_room_export=$this->get_chk_room_export_teacher($room,$term_set,$year_set,$coures_id_list_val,$user_status); if ($user_status==2) { if ($chk_room_export>0) { $data_response['room'].=' <option>'.$room.'</option>'; } }else{ if ($chk_room_export==0) { $data_response['room'].=' <option>'.$room.'</option>'; } } } return json_encode($data_response); } public function get_chk_room_export_teacher($room,$term_set,$year_set,$courseID,$user_status){ $registed_courseID=$this->get_registed_courseID($courseID,$term_set,$year_set); if ($user_status==2) { $sql_condition="AND status=1"; }else{ $sql_condition=""; } $this->sql ="SELECT COUNT(*) as num_row FROM tbl_room_export WHERE room=$room $sql_condition AND sended_status!=99 AND registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_chk_room_export($room,$term_set,$year_set,$courseID){ $this->sql ="SELECT COUNT(*) as num_row FROM tbl_room_export WHERE room=$room AND sended_status!=99 AND registed_courseID IN( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$courseID ) "; $this->select(); $this->setRows(); return $this->rows[0]['num_row']; } public function get_registed_courseID_set($courseID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$courseID AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_coures_id_list(){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) AND DataID in( SELECT regis_course_id FROM tbl_course_teacher WHERE teacher_id=$user_id ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; $data_dicision=$this->get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set); $data_response['coures_id_list'].=$data_dicision; } echo json_encode($data_response); } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_coures_id_list_admin($term_set,$year_set){ $user_id=$_SESSION['ss_user_id']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $status=$value['status']; $class_level=$value['class_level']; $data_dicision=$this->get_data_dicision_admin($DataID,$courseID_long,$class_level,$status,$term_set,$year_set); $data_response['coures_id_list'].=$data_dicision; } if ($data_response['coures_id_list']=='') { $data_response['coures_id_list']='<option value="">ไม่พบรายวิชา</option>'; } return json_encode($data_response); } public function get_data_dicision($DataID,$courseID_long,$class_level,$status,$term_set,$year_set){ if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $this->sql ="SELECT COUNT(*) as num_row_not_in FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' AND DataID not in( SELECT registed_courseID FROM tbl_room_export ) "; $this->select(); $this->setRows(); $num_row_not_in=$this->rows[0]['num_row_not_in']; $this->sql ="SELECT COUNT(*) as num_row_in_99 FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export WHERE sended_status=99 ) "; $this->select(); $this->setRows(); $num_row_in_99=$this->rows[0]['num_row_in_99']; if ($num_row_not_in>0 && $num_row_in_99==0) {//no have both in room export $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; }elseif($num_row_not_in==0){//have in room export $this->sql ="SELECT COUNT(*) as num_row_not_99 FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' AND DataID in( SELECT registed_courseID FROM tbl_room_export WHERE sended_status!=99 ) "; $this->select(); $this->setRows(); $num_row_not_99=$this->rows[0]['num_row_not_99']; if ($num_row_in_99>0 && $num_row_not_99==0) {//have only 99 in room export $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; }elseif($num_row_not_99>0){//have only another in room export $this->sql =" SELECT distinct room FROM tbl_std_class_room WHERE std_ID in( SELECT std_ID FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$DataID AND term='$term_set' AND year='$year_set' ) ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); $set_amount=0; $room_amount=0; foreach($this->rows as $key => $value) { $room=$value['room']; $chk_room_export=$this->get_chk_room_export($room,$term_set,$year_set,$DataID); if ($chk_room_export==1) { $set_amount++; } $room_amount++; } if ($set_amount<$room_amount) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; } } } return $data_response; } public function get_data_dicision_admin($DataID,$courseID_long,$class_level,$status,$term_set,$year_set){ $this->sql ="SELECT COUNT(*) AS num_row FROM tbl_room_export WHERE status=1 AND registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE year='$year_set' AND term='$term_set' AND courseID=$DataID ) "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $data_response='<option value="'.$DataID.'">'.$courseID_long.'</option>'; } return $data_response; } public function get_year(){ $this->sql ="SELECT distinct(year) as year FROM tbl_pp6 ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year= $value['year']; if($key==0){ $data_response.=' <option selected="selected" value="'.$year.'">'.$year.'</option> '; }else{ $data_response.=' <option value="'.$year.'">'.$year.'</option> '; } } return json_encode($data_response); } }<file_sep>/modules/report/major.php <?php require __DIR__.'/vendor/autoload.php'; use Spipu\Html2Pdf\Html2Pdf; use Spipu\Html2Pdf\Exception\Html2PdfException; use Spipu\Html2Pdf\Exception\ExceptionFormatter; if (isset($_POST['data_id'])) { try { $data_id=$_POST['data_id']; $room_search=$_POST['room_search']; $status=$_POST['status']; $page=$_POST['page']; ob_start(); //$stylesheet = file_get_contents(__DIR__.'\pdf_form.php'); /// here call you external css file include dirname(__FILE__).'/major_form.php'; $content = ob_get_clean(); $html2pdf = new Html2Pdf('P', 'A4', 'fr'); $html2pdf->pdf->SetDisplayMode('fullpage'); $html2pdf->addFont('THSarabun', '', dirname(__FILE__).'/html2pdf/fonts/THSarabun.php'); $html2pdf->setDefaultFont('THSarabun'); $html2pdf->writeHTML($content); $html2pdf->output('my_doc.pdf'); } catch (Html2PdfException $e) { $formatter = new ExceptionFormatter($e); echo $formatter->getHtmlMessage(); } } ?> <file_sep>/modules/regis_teacher/index.js var opPage = 'regis_teacher'; $(document).ready(function() { get_teacher(); years_set(); }); $(function () { $('[data-toggle="tooltip"]').tooltip() }) $('#uploadBtn_select').on('click', function() { $('#uploadBtn').trigger('click'); }); $( "#uploadBtn" ).change(function() { $("#modalWaitUp").modal("show"); var file_data = $('#uploadBtn').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); //alert(form_data); $.ajax({ url: 'modules/regis_teacher/upload_one.php', // point to server-side PHP script dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(data){ $(".modal").modal("hide"); $("#table_list").html(data); $("#modalteachershow").modal("show"); //alert(php_script_response); // display response from the PHP script, if any } }); }); $(document).delegate('#exit_std', 'click', function(event) { window.location.reload(); }); function form_reset(form_se) { $("#"+form_se)[0].reset(); } $(document).delegate('#btn__save', 'click', function(event) { var positionID =$("#positionID").val(); var fname_th =$("#fname_th").val(); var lname_th =$("#lname_th").val(); var fname_en =$("#fname_en").val(); var lname_en =$("#lname_en").val(); var day_set =$("#day_set").val(); var mouth_set =$("#mouth_set").val(); var years_set =$("#years_set").val(); if (day_set !=0 && mouth_set!=0 && years_set!=0) { $("#day_set").removeClass("born-box-day-red"); $("#mouth_set").removeClass("born-box-day-red"); $("#years_set").removeClass("born-box-day-red"); if(positionID !='' && fname_th !='' && lname_th !='' && fname_en !='' && lname_en !='') { var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "save_data" }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { // console.log(data); // return false; $(".modal").modal("hide"); $("#modalRegistered").modal("show"); window.location.reload(); }); }else{ $(".modal").modal("hide"); if (positionID=='') { $("#positionID").removeClass("form-set"); $("#positionID").addClass("form-set-null-data"); $("#positionID").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } if (fname_th=='') { $("#fname_th").removeClass("form-set"); $("#fname_th").addClass("form-set-null-data"); $("#fname_th").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } if (lname_th=='') { $("#lname_th").removeClass("form-set"); $("#lname_th").addClass("form-set-null-data"); $("#lname_th").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } if (fname_en=='') { $("#fname_en").removeClass("form-set"); $("#fname_en").addClass("form-set-null-data"); $("#fname_en").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } if (lname_en=='') { $("#lname_en").removeClass("form-set"); $("#lname_en").addClass("form-set-null-data"); $("#lname_en").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } } }else{ $(".modal").modal("hide"); $("#mouth_set").removeClass("form-set"); $("#mouth_set").addClass("born-box-day-red"); $("#mouth_set").attr( "placeholder", "กรุณาใส่ข้อมูล" ); $("#years_set").removeClass("form-set"); $("#years_set").addClass("born-box-day-red"); $("#years_set").attr( "placeholder", "กรุณาใส่ข้อมูล" ); $("#day_set").removeClass("form-set"); $("#day_set").addClass("born-box-day-red"); $("#day_set").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } }); $('#id_search').on('keydown', function(event) { var x = event.which; if (x === 13) { get_teacher('id'); event.preventDefault(); } }); $('#name_search').on('keydown', function(event) { var x = event.which; if (x === 13) { get_teacher('name'); event.preventDefault(); } }); $(document).delegate('#btn_id_search', 'click', function(event) { get_teacher('id'); }); $(document).delegate('#btn_name_search', 'click', function(event) { get_teacher('name'); }); $(document).delegate('.bt_change_pass', 'click', function(event) { var data_id = $(this).attr('data-id'); $(document).delegate('#btn_to_change_pass', 'click', function(event) { $.post('modules/' + opPage + '/process.php', { 'acc_action' : 'change_pass', 'data_val' : data_id }, function(response) { $("#modalChangePass").modal("hide"); data_id=''; $("#modalChaged").modal("show"); }); }); }); $(document).delegate('.bt_delete', 'click', function(event) { var data_id = $(this).attr('data-id'); $(document).delegate('#btn_to_delete', 'click', function(event) { $.post('modules/' + opPage + '/process.php', { 'acc_action' : 'data_remove', 'data_val' : data_id }, function(response) { data_id=''; $(".modal").modal("hide"); get_teacher() ; }); }); }); function get_teacher(status) { var formData = new Array(); if (status=='id') { var data_search=$("#id_search").val(); }else if(status=='name'){ var data_search=$("#name_search").val(); } formData.push({ "name": "acc_action", "value": "get_teacher" }); formData.push({ "name": "status", "value": status }); formData.push({ "name": "data_search", "value": data_search }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#table_list_teacher").html(data); }); } function years_set() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_years" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#years_set").html(data.set_years); }); } <file_sep>/modules/attend_class/backup2/class_modules.php <?php class ClassData extends Databases { public function get_day_list($length_list_val,$registed_course_id){ $data_response = array(); $this->sql ="SELECT COUNT(*) as num_attend_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id "; $this->select(); $this->setRows(); $data_response['num_attend_day']=$this->rows[0]['num_attend_day']; $data_response['week_title']='สัปดาห์ที่ '.$length_list_val.''; $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id ORDER BY attend_class_week_listID ASC "; $this->select(); $this->setRows(); $data_count=0; foreach($this->rows as $key => $value) { $attend_class_week_listID=$value['attend_class_week_listID']; $day_name=$this->get_day_name($attend_class_week_listID); $data_response['week_header'].='<td class="set_header_width" width="70px">'.$day_name.'</td>'; $data_count++; } $data_response['week_header'].='<td id="header_sum_score">0</td>'; $data_response['week_header'].='<td >100</td>'; $data_response['data_count']=$data_count; echo json_encode($data_response); } public function get_day_name($day_id){ $this->sql ="SELECT * FROM tbl_attend_class_week_list WHERE DataID=$day_id "; $this->select(); $this->setRows(); return $this->rows[0]['name']; } public function set_day($registed_course_id,$value_day,$hr_set){ $this->sql ="SELECT COUNT(*) as num_row_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$value_day "; $this->select(); $this->setRows(); $num_row_day=$this->rows[0]['num_row_day']; if ($num_row_day==0) { $this->sql ="INSERT INTO tbl_set_attend_day(registed_course_teachingID,attend_class_week_listID,hr) VALUES($registed_course_id,$value_day,$hr_set)"; $this->query(); }else{ $this->sql ="DELETE FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id AND attend_class_week_listID=$value_day" ; $this->query(); } echo json_encode("1"); } public function get_day_set($registed_course_id){ $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_id "; $this->select(); $this->setRows(); $monday=""; $tuesday=""; $wednesday =""; $thursday =""; $friday=""; $monday_hr="disabled"; $tuesday_hr="disabled"; $wednesday_hr="disabled"; $thursday_hr="disabled"; $friday_hr="disabled"; foreach($this->rows as $key => $value) { $day_find=$value['attend_class_week_listID']; if ($day_find==1) { $monday='checked'; $monday_hr=""; } if ($day_find==2) { $tuesday='checked'; $tuesday_hr=""; } if ($day_find==3) { $wednesday='checked'; $wednesday_hr=""; } if ($day_find==4) { $thursday='checked'; $thursday_hr=""; } if ($day_find==5) { $friday='checked'; $friday_hr=""; } } $data_response=' <td class="text-before-box3 text-bold mt-10" style="float: right;"> วันที่สอน </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input onclick="set_day(this)" '.$monday.' type="checkbox" name="day_set" value="1">จันทร์</label> </div> <div> <select '.$monday_hr.' style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_1"> <option value="3">3</option> <option value="2">2</option> <option value="1">1</option> </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10 "> <label><input onclick="set_day(this)" '.$tuesday.' type="checkbox" name="day_set" value="2">อังคาร</label> </div> <div> <select '.$tuesday_hr.' style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_2"> <option value="3">3</option> <option value="2">2</option> <option value="1">1</option> </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input onclick="set_day(this)" '.$wednesday.' type="checkbox" name="day_set" value="3">พุธ</label> </div> <div> <select '.$wednesday_hr.' style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_3"> <option value="3">3</option> <option value="2">2</option> <option value="1">1</option> </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input onclick="set_day(this)" '.$thursday.' type="checkbox" name="day_set" value="4">พฤหัสบดี</label> </div> <div> <select '.$thursday_hr.' style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_4"> <option value="3">3</option> <option value="2">2</option> <option value="1">1</option> </select> </div> </td> <td style="padding-left:25px;"> <div class="checkbox mr-20 ml-10"> <label><input onclick="set_day(this)" '.$friday.' type="checkbox" name="day_set" value="5">ศุกร์</label> </div> <div> <select '.$friday_hr.' style="width:75px;" class="form-control search-drop-length-ob mt-5 hr_set_5"> <option value="3">3</option> <option value="2">2</option> <option value="1">1</option> </select> </div> </td> '; echo json_encode($data_response); } public function get_week_between($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data_response=' <option value="1-10">สัปดาห์ที่ 1-10</option> <option value="11-20">สัปดาห์ที่ 11-20</option> <option value="21-31">สัปดาห์ที่ 21-31</option> <option value="31-40">สัปดาห์ที่ 31-40</option> '; }else{ $data_response=' <option value="1-10">สัปดาห์ที่ 1-10</option> <option value="11-20">สัปดาห์ที่ 11-20</option> '; } echo json_encode($data_response); } public function get_count_adttend_class_val($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT * FROM tbl_set_count_adttend_class WHERE registed_courseID=$registed_courseID "; $this->select(); $this->setRows(); $week_name=$this->rows[0]['week_name']; echo json_encode($week_name); } /*public function set_count_adttend_class_val($coures_id_list_val,$set_count_adttend_class_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT COUNT(*) as num_row FROM tbl_set_count_adttend_class WHERE registed_courseID =$registed_courseID "; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $this->sql ="UPDATE tbl_set_count_adttend_class SET week_name=$set_count_adttend_class_val WHERE registed_courseID=$registed_courseID "; $this->query(); }else{ $this->sql ="INSERT INTO tbl_set_count_adttend_class(registed_courseID,week_name) VALUES($registed_courseID,$set_count_adttend_class_val) "; $this->query(); } }*/ public function chk_value_attend_1($score_status){ if ($score_status=="1") { $data_response="selected"; } return $data_response; } public function chk_value_attend_l($score_status){ if ($score_status=="ล") { $data_response="selected"; } return $data_response; } public function chk_value_attend_p($score_status){ if ($score_status=="ป") { $data_response="selected"; } return $data_response; } public function chk_value_attend_k($score_status){ if ($score_status=="ข") { $data_response="selected"; } return $data_response; } public function chk_value_attend_n($score_status){ if ($score_status=="น") { $data_response="selected"; } return $data_response; } public function chk_value_attend__($score_status){ if ($score_status=="0" || $score_status=="-") { $data_response="selected"; } return $data_response; } public function get_score_col($std_ID,$registed_courseID,$start_data,$end_data){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT * FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $attendID=$value['DataID']; $week=$value['week']; $score_status=$value['score_status']; $data_response['score_col'].=' <td class="relative"> <select name="attend_score_std[]" class="select-table-form class_col_set_new class_col_attend_1 value_attend_week_1"> <option value="1" selected="">1</option> <option value="ล">ล</option> <option value="ป">ป</option> <option value="ข">ข</option> <option value="-">-</option> </select> </td> '; } return $data_response; } public function get_score_col_total($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT SUM(score_status) as sum_score_status FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); return $this->rows[0]['sum_score_status']; } public function get_all_attendID($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT count(*) as num_attend_row FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); $num_attend_row=$this->rows[0]['num_attend_row']; $this->sql ="SELECT * FROM tbl_attend_class WHERE course_teaching_stdID=$course_teaching_stdID AND week BETWEEN $start_data AND $end_data ORDER BY week ASC "; $this->select(); $this->setRows(); $num_set=1; foreach($this->rows as $key => $value) { if ($num_row_std==$no_std) { if ($num_set==$num_attend_row) { $attendID.=$value['DataID']; }else{ $attendID.=$value['DataID'].'-'; } }else{ $attendID.=$value['DataID'].'-'; } $num_set++; } return $attendID; } public function get_detail_std($coures_id_list_val,$room_search,$registed_course_teaching_id,$length_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term_set='1,2'; } $registed_courseID=$this->get_registed_courseID($coures_id_list_val,$term_set,$year_set); $this->sql ="SELECT COUNT(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID IN( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; $fname=$value['fname']; $lname=$value['lname']; $name_title_data=$value['name_title']; $name_title=$this->get_name_title($name_title_data); $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p') { $term_set='1,2'; } $attend_data=$this->get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status,$status); /*$all_attendID.=$this->get_all_attendID($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std); $score_col=$this->get_score_col($std_ID,$registed_courseID,$start_data,$end_data); */ //$score_col_total=$this->get_score_col_total($std_ID,$registed_courseID,$start_data,$end_data,$num_row_std,$no_std); $data_response['detail_std'].='<tr> <td>'.$no_std.'</td> <td style="text-align:left;padding-left:7%;">'.$name_title.$fname.' '.$lname.'</td> '.$attend_data.' </tr> '; $no_std++; } $data_response['all_attendID'].=$all_attendID; $this->sql ="SELECT COUNT(*) as num_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id "; $this->select(); $this->setRows(); $num_day=$this->rows[0]['num_day']; $class_level_status=$this->get_class_level_status($coures_id_list_val); if ($class_level_status=='p' || $status==2) { $week_all=40; }else{ $week_all=20; } $data_response['num_day']=($num_day)*$week_all; return $data_response; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function get_attend_data($registed_course_teaching_id,$std_ID,$registed_courseID,$length_list_val,$class_level_status,$status_class){ $this->sql ="SELECT * FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' "; $this->select(); $this->setRows(); $course_teaching_stdID=$this->rows[0]['DataID']; $this->sql ="SELECT * FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id ORDER BY attend_class_week_listID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $attend_class_week_listID=$this->rows[0]['attend_class_week_listID']; $attend_class_std=$this->get_attend_class_std($DataID,$std_ID,$registed_courseID,$length_list_val); if ($attend_class_std['attend_id']!='') { $status=$attend_class_std['status']; if ($status=='ล') { $status_l='selected="selected"'; }else{ $status_l=''; } if ($status=='ป') { $status_p='selected="selected"'; }else{ $status_p=''; } if ($status=='ข') { $status_k='selected="selected"'; }else{ $status_k=''; } if ($status=='น') { $status_n='selected="selected"'; }else{ $status_n=''; } $data_response.=' <td class="relative"> <select onchange="save_attend(this,'.$attend_class_std['attend_id'].','.$course_teaching_stdID.','.$DataID.','.$length_list_val.')" class="select-table-form class_col_set_new "> <option value="1" >1</option> <option '.$status_l.' value="ล">ล</option> <option '.$status_p.' value="ป">ป</option> <option '.$status_k.' value="ข">ข</option> <option '.$status_n.' value="น">น</option> </select> </td> '; }else{ $data_response.=' <td class="relative"> <select onchange="save_attend(this,0,'.$course_teaching_stdID.','.$DataID.','.$length_list_val.')" class="select-table-form class_col_set_new "> <option value="1">1</option> <option value="ล">ล</option> <option value="ป">ป</option> <option value="ข">ข</option> <option value="น">น</option> </select> </td> '; } } $this->sql ="SELECT COUNT(*) as num_no_class FROM tbl_attend_class_std WHERE course_teaching_std_id=$course_teaching_stdID "; $this->select(); $this->setRows(); $num_no_class=$this->rows[0]['num_no_class']; $this->sql ="SELECT COUNT(*) as num_day FROM tbl_set_attend_day WHERE registed_course_teachingID=$registed_course_teaching_id "; $this->select(); $this->setRows(); $num_day=$this->rows[0]['num_day']; if ($class_level_status=='p' || $status_class==2) { $week_all=40; }else{ $week_all=20; } $total_day=$num_day*$week_all; $total_attend=$total_day-$num_no_class; $data_response.=' <td class="relative"> '.$total_attend.' </td> '; $total_attend_per=round((($total_day-$num_no_class)*100)/$total_day); $data_response.=' <td class="relative"> '.$total_attend_per.' </td> '; return $data_response; } public function get_attend_class_std($set_attend_day_id,$std_ID,$registed_courseID,$length_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_attend_class_std WHERE set_attend_day_id=$set_attend_day_id AND week=$length_list_val AND course_teaching_std_id IN( SELECT DataID FROM tbl_course_teaching_std WHERE registed_courseID=$registed_courseID AND stdID='$std_ID' ) "; $this->select(); $this->setRows(); $data_response['attend_id']=$this->rows[0]['DataID']; $data_response['week']=$this->rows[0]['week']; $data_response['status']=$this->rows[0]['status']; return $data_response; } public function get_class_level_status($coures_id_list_val){ $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $data='p'; }else{ $data='m'; } return $data; } public function get_registed_courseID($coures_id_list_val,$term_set,$year_set){ $data_response = array(); $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_std_id_all($coures_id_list_val,$room_search){ $this->sql ="SELECT count(*) as num_row_std FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $num_row_std=$this->rows[0]['num_row_std']; $this->sql ="SELECT * FROM tbl_student WHERE room='$room_search' AND std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val ) ) "; $this->select(); $this->setRows(); $no_std=1; foreach($this->rows as $key => $value) { $std_ID=$value['std_ID']; if ($num_row_std==$no_std) { $std_id_all.=$std_ID; }else{ $std_id_all.=$std_ID.'-'; } $no_std++; } $data_response=$std_id_all; return $data_response; } public function get_week_list_data($coures_id_list_val,$length_list_val,$room_search,$registed_course_teaching_id){ $data_response = array(); /* list($start_data, $end_data) = split('[-]', $length_list_val); $find_start=$start_data-1; $find_end=$end_data-$find_start;*/ $detail_std=$this->get_detail_std($coures_id_list_val,$room_search,$registed_course_teaching_id,$length_list_val); $data_response['detail_std']=$detail_std['detail_std']; $data_response['all_attendID']=$detail_std['all_attendID']; $data_response['num_day']=$detail_std['num_day']; $data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); //$data_response['std_id_all']=$this->get_std_id_all($coures_id_list_val,$room_search); $data_response['data_objectiveID_of_title']=$data_objective; return json_encode($data_response); } public function get_registed_course_id($coures_id_list){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT * FROM tbl_registed_course_teaching WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND courseID=$coures_id_list ) "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function search_course_detail($coures_id_list,$room_search){ $data_response = array(); $data_response['registed_course_id']=$this->get_registed_course_id($coures_id_list); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list "; $this->select(); $this->setRows(); $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['unit']=$this->rows[0]['unit']; $data_response['hr_learn']=$this->rows[0]['hr_learn']; $class_level_data=$this->rows[0]['class_level']; $status=$this->rows[0]['status']; $class_level=$this->get_class_level_new($class_level_data); $data_response['class_level_co']=$class_level.'/'.$room_search; if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' || $status==2) { for ($i=1; $i <=40 ; $i++) { $data_response['week_menu_data'].=' <option value="'.$i.'">สัปดาห์ที่ '.$i.'</option> '; } }else{ for ($i=1; $i <=20 ; $i++) { $data_response['week_menu_data'].=' <option value="'.$i.'">สัปดาห์ที่ '.$i.'</option> '; } } echo json_encode($data_response); } public function get_class_level($coures_id_list_val){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $data_response = array(); $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$coures_id_list_val AND DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' OR term='1,2' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) "; $this->select(); $this->setRows(); $class_level_data=$this->rows[0]['class_level']; $data_response['class_level']=$this->get_class_level_new($class_level_data); if ($class_level_data=='p1' || $class_level_data=='p2' || $class_level_data=='p3' || $class_level_data=='p4' || $class_level_data=='p5' || $class_level_data=='p6' ) { $term_set='1,2'; } $this->sql ="SELECT distinct room FROM tbl_student WHERE std_ID in( SELECT stdID FROM tbl_course_teaching_std WHERE registed_courseID in( SELECT DataID FROM tbl_registed_course WHERE courseID=$coures_id_list_val AND term='$term_set' AND year='$year_set' ) ) ORDER BY room ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $room=$value['room']; $data_response['room'].=' <option>'.$room.'</option>'; } return json_encode($data_response); } public function get_registed_courseID_set($courseID,$term_set,$year_set){ $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID=$courseID AND term='$term_set' AND year='$year_set' "; $this->select(); $this->setRows(); return $this->rows[0]['DataID']; } public function get_coures_id_list(){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term_set=$this->rows[0]['term']; $year_set=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='$term_set' AND year='$year_set' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $courseID=$value['DataID']; $registed_courseID=$this->get_registed_courseID_set($courseID,$term_set,$year_set); $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$courseID.'">'.$courseID_long.'</option> '; } $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID in( SELECT courseID FROM tbl_registed_course WHERE term='1,2' AND DataID IN( SELECT registed_courseID FROM tbl_registed_course_teaching ) ) ORDER BY courseID ASC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $courseID_long=$value['courseID']; $data_response['coures_id_list'].=' <option value="'.$DataID.'">'.$courseID_long.'</option> '; } echo json_encode($data_response); } public function get_class_level_new($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } }<file_sep>/modules/graduate/class_modules.php <?php class ClassData extends Databases { public function edit_status($class_room_modal_id,$status_val){ $this->sql ="UPDATE tbl_std_class_room SET status=$status_val WHERE DataID = $class_room_modal_id"; $this->query(); return '1'; } public function data_add($data_val){ $arr_id = explode(",", $data_val); for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="UPDATE tbl_std_class_room SET status=2 WHERE DataID = {$arr_id[$i]}"; $this->query(); } return '1'; } public function get_status_text($status){ if ($status==1) { $data_response='กำลังศึกษา'; }elseif($status==2){ $data_response='สำเร็จการศึกษา'; }elseif($status==3){ $data_response='ย้าย'; }elseif($status==4){ $data_response='ลาออก'; }elseif($status==5){ $data_response='เสียชีวิต'; }elseif($status==6){ $data_response='กำลังดำเนินการ'; } return $data_response; } public function get_std_list($class_level,$room,$year){ $data_response = array(); $this->sql =" SELECT tbl_student.std_ID,tbl_student.name_title,tbl_student.fname,tbl_student.lname,tbl_std_class_room.class_level,tbl_std_class_room.room,tbl_std_class_room.DataID as std_class_room_ID,tbl_std_class_room.status FROM tbl_student,tbl_std_class_room WHERE tbl_student.std_ID=tbl_std_class_room.std_ID AND tbl_std_class_room.class_level='$class_level' AND tbl_std_class_room.room='$room' AND tbl_std_class_room.year='$year' ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $std_class_room_ID=$value['std_class_room_ID']; $std_ID=$value['std_ID']; $name_title_data=$value['name_title']; $fname=$value['fname']; $lname=$value['lname']; $class_level_data=$value['class_level']; $room=$value['room']; $status=$value['status']; $status_text=$this->get_status_text($status); $name_title=$this->get_name_title($name_title_data); $class_level=$this->get_class_level($class_level_data); if($status==2){ $data_response['std_list'].=' <tr> <td style="text-align: center;"> <input checked="checked" disabled="disabled" class="checkbox_data" type="checkbox" value="'.$std_class_room_ID.'" name="checkbox_add[]" id="checkbox'.$std_class_room_ID.'"> </td> <td style="text-align: left;width: 10%">'.$std_ID.'</td> <td style="width: 25%">'.$name_title.$fname.'</td> <td style="width: 25%">'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> <span data-id="'.$std_class_room_ID.'" class="glyphicon glyphicon glyphicon-edit edit-icon-table btn_getdata_edit" aria-hidden="true" data-toggle="modal" data-target="#modalEdit"></span> </td> <td style="text-align: center;color:#999"> <img data-id-registered="699" style="width:20px;margin-top: -8px;margin-left: 5px;" src="assets/images/education.png"> </td> </tr> '; }else{ $data_response['std_list'].=' <tr> <td style="text-align: center;"> <input checked="checked" class="checkbox_data" type="checkbox" value="'.$std_class_room_ID.'" name="checkbox_add[]" id="checkbox'.$std_class_room_ID.'"> </td> <td style="text-align: left;width: 10%">'.$std_ID.'</td> <td style="width: 25%">'.$name_title.$fname.'</td> <td style="width: 25%">'.$lname.'</td> <td style="text-align: center;">'.$class_level.'</td> <td style="text-align: center;">'.$room.'</td> <td style="text-align: center;"> <span data-id="'.$std_class_room_ID.'" class="glyphicon glyphicon glyphicon-edit edit-icon-table btn_getdata_edit" aria-hidden="true" data-toggle="modal" data-target="#modalEdit"></span> </td> <td style="text-align: center;">'.$status_text.'</td> </tr> '; } } if ($data_response['std_list']=='') { $data_response['std_list']=''; } echo json_encode($data_response); } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } public function get_name_title($name_title_data){ if ($name_title_data=="dekchai") { $name_title="เด็กชาย"; }elseif($name_title_data=="dekying"){ $name_title="เด็กหญิง"; }elseif($name_title_data=="nai"){ $name_title="นาย"; }elseif($name_title_data=="nangsaw"){ $name_title="นางสาว"; } return $name_title; } public function getdata_edit($data_id){ $data_response = array(); $this->sql ="SELECT status FROM tbl_std_class_room WHERE DataID=$data_id "; $this->select(); $this->setRows(); $data_response['status']=$this->rows[0]['status']; echo json_encode($data_response); } public function get_year(){ $data_response = array(); $this->sql ="SELECT DISTINCT(year) FROM tbl_std_class_room WHERE class_level='p6' OR class_level='m3' OR class_level='m6' ORDER BY year DESC "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $year=$value['year']; $data_response['year'].=' <option "'.$year.'">'.$year.'</option> '; } echo json_encode($data_response); } } <file_sep>/assets/js/custom.js function addTopMenu() { $('#leftMenu').css("animationName","menuSlide"); setTimeout(function(){ $('#leftMenu').css("top","0px");}, 1000); } function closeTopMenu(){ $('#leftMenu').css("animationName","menuSlideClose"); setTimeout(function(){ $('#leftMenu').css("top","-250px");}, 1000); }<file_sep>/modules/mobile_api/host/test.php <?php @session_start(); require_once('config.php'); require_once('src/database.php'); include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## echo "string"; ?><file_sep>/src/filemanager.class.php <?php class Filemanager { public $SOURCE; public $DESTINATION; public $FILES; public $FILES_PATH; public $FILES_ERROR; public $EXTENSION; public function __construct(){ $this->FILES = null; $this->FILES_PATH = null; $this->FILES_ERROR = null; $this->EXTENSION = array("jpg","jpeg","gif","png"); } protected function scan_files() { // Check Dir if(is_dir($this->SOURCE)){ $files = scandir($this->SOURCE); // dir $this->FILES = $files; return $this; } // Check File if( !file_exists($this->SOURCE) ) return null; $this->FILES = $this->SOURCE; // file return $this; } protected function prepare() { if(is_array( $this->FILES )){ // Cycle through all source files foreach ($this->FILES as $file) { if (in_array($file, array(".",".."))) continue; $ex = @explode(".",$file); $end = @end($ex); if (!in_array($end, $this->EXTENSION)) continue; $this->FILES_PATH[] = $this->SOURCE.$file; } } else{ $this->FILES_PATH = array(); $this->FILES_PATH[] = $this->SOURCE.$this->FILES; } } public function clear() { $this->FILES = null; $this->FILES_PATH = null; } public function data( $source, $destination=null, $data=null) { $this->SOURCE = $source; $this->DESTINATION = $destination; if($data) $this->FILES = $data; else self::scan_files(); //scan // Prepare self::prepare(); return $this; } public function move( $source, $destination=null, $data=null) { self::data($source, $destination, $data); $check_error = false; $key_error = array(); if( $this->FILES_PATH ){ foreach( $this->FILES_PATH as $key => $source_path ){ // Check Copy Error if (!@copy($source_path, $this->DESTINATION.basename($source_path))) { $key_error[] = $key; $check_error = true; } } if( $check_error === true ){ foreach( $key_error as $key ){ unset($this->FILES_PATH[$key]); } } } return $this; } public function delete() { if($this->FILES_PATH){ foreach($this->FILES_PATH as $file) { if ( !is_dir($file) && file_exists($file)) { @unlink($file); } } return sizeof($this->FILES_PATH); } return 0; } } // Identify directories //$source = BASE_PATH."img/progressbar.gif"; /* $source = BASE_PATH."img/"; $destination = HOME_PATH."file_managers/"; $u = new Filemanager(); echo '<pre>'; print_r($u); $test = array('loading.gif');//,'progressbar.gif' print_r($u->data($source,$destination,$test)->delete()); */ <file_sep>/modules/conclusion/form/learning_result.php <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="../../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <link href="../../../assets/css/print_conclusion.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" rel="stylesheet" type="text/css"> <script type="text/javascript" src="../../../assets/js/jquery.js"></script> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 2px; } --> </style> <?php @session_start(); include ('../logo.php'); require_once('../../../init.php'); include('../class_modules.php'); $class_data = new ClassData(); $class_label=$_GET['class_label']; $room=$_GET['room']; $term=$_GET['term']; $year=$_GET['year']; ?> <div style="background-color: rgb(82, 86, 89);min-height: 100%"> <div style="font-size:16px;background-color: white;min-height: 100%;padding-right: 30px; padding-left: 30px;margin-right: auto;margin-left: auto;width: 80%"> <div style="page-break-after:always;"> <page > <div style="text-align: center;line-height: 0.6;font-weight: bold;padding-top: 20px;font-size:18px"> <img class="logo-print-size" src="<?php echo $image_logo ?>"> <p >แบบประกาศผลการเรียนแยกตามระดับชั้น</p> <p >โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อ.เมือง จ.ร้อยเอ็ด</p> <p> <span style="margin-right: 30px;">ระดับชั้น <span style="font-weight: normal;">ประถมศึกษาปีที่ 1</span></span> <span style="margin-right: 20px;">กลางปี</span> <span>ปีการศึกษา <span style="font-weight: normal;">2560</span> </span> </p> <p style="margin-top: 20px;"> <span style="margin-right: 40px;">ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> <span>ครูประจำชั้น <span style="font-weight: normal;">.........................................................................................</span> </span> </p> </div> <table cellspacing="0" style=" text-align: center; font-size: 16px;width:100%;margin-top: 20px;"> <thead> <tr class="text-middle"> <th rowspan="2" class="rotate" style="width: 3%;height: 0px;text-align: center;"> <div >เลขที่</div> </th> <th rowspan="2" class="rotate" style="width: 5%;height: 0px;text-align: center;"> <div >รหัส</div> </th> <th rowspan="2" style="width: 30%;vertical-align: middle;text-align: center;">ชื่อ-สกุล</th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ภาษาไทย </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ภาษาไทย </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ภาษาไทย </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ภาษาไทย </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> คะแนนรวม </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ร้อยละ </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> ลำดับที่ </div> </th> </tr> <tr> <th style="text-align: center;">100</th> <th style="text-align: center;">100</th> <th style="text-align: center;">100</th> <th style="text-align: center;">100</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody > <tr> <td>1</td> <td>09323</td> <td>chanut chumjan</td> <td>20</td> <td>20</td> <td>20</td> <td>20</td> <td>20</td> <td>20</td> <td>20</td> </tr> </tbody> </table> </page> </div> </div> </div> <script> /* $(document).ready(function() { get_print(); setTimeout(window.close, 0); }); function get_print() { window.print(); }*/ </script><file_sep>/modules/maneger_student/edit.js var opPage = 'maneger_student'; $(document).ready(function() { get_data_form(); }); function isNumber(data){ data = data +"e1"; // Disallow eng. notation "10e2"+"e1" is NaN var clean = parseFloat(data,10) / data ; // 1 if parsed cleanly return (clean && (data/data) === 1.0); // Checks for NaN } function send_data() { var formData = $( "#frm_data" ).serializeArray(); formData.push({ "name": "acc_action", "value": "save_data" }); formData.push({ "name": "data_id", "value": _get.id}); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { // console.log(data); // return false; window.location = 'index.php?op=maneger_student-index'; $(".modal").modal("hide"); $("#modalEdited").modal("show"); $("#std_ID").attr( "placeholder", "" ); $("#card_ID").attr( "placeholder", "" ); form_reset("frm_data"); get_data_form(std_ID); }); } $(document).delegate('#btn__save', 'click', function(event) { $("#std_ID").addClass("form-set"); $("#card_ID").addClass("form-set"); var std_ID =$("#std_ID").val(); var card_ID =$("#card_ID").val(); if(std_ID!='' && card_ID!='') { var num_card_ID=card_ID.length; if (num_card_ID>13) { $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "รหัสบัตรประชาชนเกิน 13 หลัก" ); $("#card_ID").val(""); }else if(num_card_ID<13){ $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "รหัสบัตรประชาชนไม่ถึง 13 หลัก" ); $("#card_ID").val(""); }else{ var card_id_sck=isNumber(card_ID); if (card_id_sck==true) { send_data(); }else{ $(".modal").modal("hide"); $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "ใส่ข้อมูลเป็นตัวเลขเท่านั้น" ); $("#card_ID").val(""); } } }else{ $(".modal").modal("hide"); if(std_ID==""){ $("#std_ID").removeClass("form-set"); $("#std_ID").addClass("form-set-null-data"); $("#std_ID").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } if(card_ID==""){ $("#card_ID").removeClass("form-set"); $("#card_ID").addClass("form-set-null-data"); $("#card_ID").attr( "placeholder", "กรุณาใส่ข้อมูล" ); } } }); function get_data_form(std_ID) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_data_form" }); formData.push({ "name": "data_id", "value": _get.id}); formData.push({ "name": "new_data_id", "value": std_ID}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus) { // console.log(data); $("#std_ID").val(data.std_ID); $("#card_ID").val(data.card_ID); var class_level_data=data.class_level; $("#calss_"+class_level_data).attr("selected","selected"); var room_data=data.room; $("#room_"+room_data).attr("selected","selected"); var name_title_data=data.name_title; $("#name_title_"+name_title_data).attr("selected","selected"); $("#fname").val(data.fname); $("#lname").val(data.lname); var blood_group_data=data.blood_group; $("#blood_group_"+blood_group_data).attr("selected","selected"); $("#address").val(data.address); $("#status_alive").val(data.status_alive); var parent_name_title_data=data.parent_name_title; $("#parent_name_title_"+parent_name_title_data).attr("selected","selected"); $("#parent_fname").val(data.parent_fname); $("#parent_lname").val(data.parent_lname); $("#tell").val(data.tell); $("#parent_address").val(data.parent_address); }); } function years_set() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_years" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#years_set").html(data.set_years); }); } function get_day(mouth) { //var formData = $( "#frm_data" ).serializeArray(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_day" }); formData.push({ "name": "mouth", "value": mouth }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { console.log(data.day_set) $("#day_set").html(data.day_set); }); }<file_sep>/modules/regis_course/process.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## if(isset($_GET['acc_action']) and $_GET['acc_action'] == "set_term_year"){ $term_set=$_GET['term_set']; $year_set=$_GET['year_set']; echo $class_data->set_term_year($term_set,$year_set); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_term_year_now"){ echo $class_data->get_term_year_now(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_year_search"){ echo $class_data->get_data_year_search(); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_registered"){ $data_term_search=$_GET['data_term_search']; $data_year_search=$_GET['data_year_search']; $chk_edit_after=$_GET['chk_edit_after']; $chk_teacher_icon=$_GET['chk_teacher_icon']; $show_delete=$_GET['show_delete']; echo $class_data->get_data_registered($data_term_search,$data_year_search,$chk_edit_after); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data_registered_edit"){ $data_term_search=$_GET['data_term_search_3']; $data_year_search=$_GET['data_year_search_3']; $chk_edit_after=$_GET['chk_edit_after']; $chk_teacher_icon=$_GET['chk_teacher_icon']; $show_delete=$_GET['show_delete']; echo $class_data->get_data_registered_edit($data_term_search,$data_year_search,$chk_edit_after); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "chk_regiseted_course"){ $data_val = $_GET['data_val']; $term = $_GET['term']; $year = $_GET['year']; echo $class_data->chk_regiseted_course($data_val,$term,$year); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_regis_course"){ $data_val = $_POST['data_val']; //$term=$_POST['term']; //$year=$_POST['year']; $cdate="now()"; $class_data->insert_data_regis_course($data_val,$cdate); } if(isset($_POST['acc_action']) and $_POST['acc_action'] == "save_data"){ $user_add=$_SESSION['ss_user_id']; $data_id_course=$_POST['data_id_course']; $arr_sql[]="courseID='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['courseID'])))."'"; $arr_sql[]="user_add='".chkhtmlspecialchars($InputFilter->clean_script(trim($user_add)))."'"; $arr_sql[]="name='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['name'])))."'"; $arr_sql[]="class_level='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['class_level'])))."'"; $arr_sql[]="unit='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['unit'])))."'"; $arr_sql[]="department='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['department'])))."'"; $arr_sql[]="hr_learn='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['hr_learn'])))."'"; $arr_sql[]="status='".chkhtmlspecialchars($InputFilter->clean_script(trim($_POST['course_status'])))."'"; $class_data->update_data($arr_sql,$data_id_course); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "remove_registed"){ $data_id = $_GET['data_id']; $data_term = $_GET['data_term']; $data_year = $_GET['data_year']; echo $class_data->remove_registed($data_id,$data_term,$data_year); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_teacher_to_course_registed"){ $registered_id = $_GET['registered_id']; echo $class_data->get_teacher_to_course_registed($registered_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "set_room_teacher"){ $course_teacher_id = $_GET['course_teacher_id']; $room_val = $_GET['room_val']; echo $class_data->set_room_teacher($course_teacher_id,$room_val); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_room_detail"){ $data_id_registered_room = $_GET['data_id_registered_room']; echo $class_data->get_room_detail($data_id_registered_room); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "insert_teacher_to_course"){ $teacher_id = $_GET['teacher_id']; $registered_id = $_GET['registered_id']; echo $class_data->insert_teacher_to_course($teacher_id,$registered_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_teacher_list"){ $data_id_registered = $_GET['data_id_registered']; $teacher_search_data = $_GET['teacher_search_data']; echo $class_data->get_teacher_list($data_id_registered,$teacher_search_data); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "getdata_edit"){ $data_id = $_GET['data_id']; echo $class_data->getdata_edit($data_id); } if(isset($_GET['acc_action']) and $_GET['acc_action'] == "get_data"){ $arr_search_val['courseID_search'] = $_GET['courseID_search']; $arr_search_val['department_search'] = $_GET['department_search']; $arr_search_val['class_level_search'] = $_GET['class_level_search']; $arr_search_val['status'] = $_GET['status']; echo $class_data->get_data($arr_search_val); }<file_sep>/modules/profile/upload_one.php <?php @ob_start(); @session_start(); require_once('../../init.php'); include('../../src/class.pagination.php'); include('../../src/class.inputfilter.php'); $InputFilter = new InputFilter(); ##CLASS_DB_CONNECT## include('class_modules.php'); $class_data = new ClassData(); ##CLASS_DB_CONNECT## $file_path="../../file_managers/profile/"; $user_id=$_SESSION['ss_user_id']; $ext=pathinfo(basename($_FILES['file_up']['name']),PATHINFO_EXTENSION); $new_file='file_'.uniqid().".".$ext; $up_path=$file_path.$new_file; $oldFileName=$_FILES['file_up']['name']; $upload=move_uploaded_file($_FILES['file_up']['tmp_name'], $up_path); if ($upload==false) { echo "no"; exit(); } $class_data->sql="SELECT * FROM tbl_regis_teacher_gallery WHERE regis_teacher_id=$user_id"; $class_data->select(); $class_data->setRows(); $FileName=$class_data->rows[0]['FileName']; @unlink($file_path.$FileName); $class_data->sql="DELETE FROM tbl_regis_teacher_gallery WHERE regis_teacher_id = $user_id"; $class_data->query(); $class_data->sql="INSERT INTO tbl_regis_teacher_gallery (regis_teacher_id,FileName) VALUES($user_id,'$new_file')"; $class_data->query(); echo json_encode("ok"); ?><file_sep>/modules/save_score/index.php <?php session_start(); ?> <div class="container set-content-pad-20" > <div class="bg-whte" style="position: relative;padding-bottom: 60px"> <div class="circle-bg-violet"> <img class="head-img-circle" src="assets/images/8.png"> </div> <div class="text-head-title"> <p>บันทึกคะแนน</p> </div> <div class="text-head-desc"> <p>ใช้สำหรับการบันทึกคะแนนของนักเรียนในแต่ละรายวิชา</p> </div> <div class="row pd-40 pt-80 stage-set" > <?php if($_SESSION['ss_status']==2){ ?> <div class="col-sm-12 col-xs-12 mt-30"> <div class="set-line"> <form id="frm_data_room_admin"> <p class="text-bold text-inline fs-16">เลือกภาคเรียน</p> <select id="term_data" name="term_data" class="form-control search-drop-sub-class mr-20"> <option value="1">1</option> <option value="2">2</option> <option selected="selected" value="1,2">1,2</option> </select> <p class="text-inline fs-14">ปีการศึกษา</p> <select id="year_data" name="year_data" class="form-control search-drop-sub-years mr-20"> </select> <div id="btn_search_course_detail_admin" class="btn-search-save-score"> <div class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </form> </div> </div> <?php } ?> <div class="col-sm-12 col-xs-12"> <div class="set-line"> <form id="frm_data_room"> <p class="text-bold text-inline fs-16">เลือกรายวิชา</p> <select onchange="get_class_level()" id="coures_id_list" name="coures_id_list" class="form-control search-drop-sub-id mr-20"> </select> <p class="text-inline fs-14">ชั้น</p> <p id="place_class_level" class="text-inline mr-20"></p> <span class="slash-class" style="display: none;">/</span> <select id="room_search" style="display: none;" name="room_search" class="form-control search-drop-sub-class mr-20"> </select> <div id="btn_search_course_detail" class="btn-search-save-score"> <div class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </form> </div> </div> </div> <div class="row"> <div class="hr-co-text-depart mt-nega-30"></div> </div> <div id="course_detal_box" style="display: none;" class="ml-50 mr-50 mt-nega-10" > <div class="row"> <div class="box-search-depart"> <div class="set-line"> <div id="rate_score_box" class="col-sm-12 col-xs-12" style="display: block;"> <div class="row"> <table> <tbody style="border: none;"> <tr > <td > <p class="text-before-box3 text-bold" style="float: right;">รหัสวิชา</p> </td> <td> <p id="place_detail_courseID" class=" text-before-box2 " ></p> </td> <td > <p class="text-before-box3 text-bold">รายวิชา</p> </td> <td width="300px"> <p id="place_detail_name" class=" text-before-box2 "></p> </td> <td > <p class="text-before-box3 text-bold">นก./น.น.</p> </td> <td width="40px"> <p id="place_detail_unit" class=" text-before-box2 "></p> </td> <td > <p class="text-before-box3 text-bold">ชม./สัปดาห์</p> </td> <td > <p id="place_detail_hr_learn" class=" text-before-box2 "></p> </td> </tr> <tr > <td class="text-before-box3 text-bold" style="float: right;"> ชั้น </td> <td> <p id="place_detail_class_level" class=" text-before-box2 "> </p> </td> </tr> <tr > <td class="text-before-box3 text-bold" style="float: right;"> ช่วงคะแนน </td> <td width="200px"> <form id="frm_data_legth_score"> <select id="legth_score" name="legth_score" class="form-control search-drop-ob-length mt-5"> </select> </form> </td> <td style="padding-left: 20px;"> <div class="btn-search-save-score "> <div id="btn_get_config" class="btn-search"> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </div> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <input id="data_registed_courseID" type="text" hidden="hidden" name=""> <input id="data_objectiveID_of_title" type="text" hidden="hidden" name=""> <input id="std_id_all" type="text" hidden="hidden" name=""> <div id="place_config"> </div> </div> </div><file_sep>/modules/regis_course/class_modules.php <?php class ClassData extends Databases { public function get_term_year_now(){ $data_response = array(); $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $data_response['term']=$this->rows[0]['term']; $data_response['year']=$this->rows[0]['year']; $data_response['year_now']=date("Y")+543; $data_response['status_rang']=$_SESSION['ss_status_rang']; echo json_encode($data_response); } public function set_term_year($term_set,$year_set){ if($_SESSION['ss_status_rang']==1 || $_SESSION['ss_status_rang']==2){ $this->sql ="UPDATE tbl_set_term_year SET year='$year_set' WHERE DataID=1" ; $this->query(); }else{ $this->sql ="UPDATE tbl_set_term_year SET term='$term_set',year='$year_set' WHERE DataID=1" ; $this->query(); } return 1; } public function get_data_year_search(){ $this->sql ="SELECT distinct(year) FROM tbl_registed_course "; $this->select(); $this->setRows(); $data_response['year_list']=' <option value="">ทั้งหมด</option> '; foreach($this->rows as $key => $value) { $year= $value['year']; $data_response['year_list'].=' <option value="'.$year.'">'.$year.'</option> '; } return json_encode($data_response); } public function get_term($unit_data,$status_data,$term){ if ($unit_data==0) { if ($status_data==1) { $term="1,2"; }else{ $term=$term; } }else{ $term=$term; } return $term; } public function get_name_course($courseID_send,$term,$year,$cdate,$chk_edit_after,$registed_courseID){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$courseID_send"; $this->select(); $this->setRows(); $name= $this->rows[0]['name']; $courseID=$this->rows[0]['courseID']; $name=$this->rows[0]['name']; $class_level_data=$this->rows[0]['class_level']; $class_level= $this->get_class_level($class_level_data); $unit_data=$this->rows[0]['unit']; $unit=$this->get_unit_data($unit_data); $department=$this->rows[0]['department']; $hr_learn=$this->rows[0]['hr_learn']; $status_data=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; $status_form_text=$this->get_status_form($status_form); $term_new=$this->get_term($unit_data,$status_data,$term); $data_response=' <tr> <td style="padding-left: 30px;">'.$courseID.'</td> <td>'.$name.'</td> <td>'.$status_form_text.'</td> <td style="text-align: center;">'.$unit.'</td> <td style="text-align: center;">'.$hr_learn.'</td> <td style="text-align: center;">'.$class_level.'</td> '.$data_teacher_icon.' <td class="chk_delete_btn" style="display:block;text-align:center;"> <div class="btn_remove_registed" data-term="'.$term_new.'" data-year="'.$year.'" data-id="'.$registed_courseID.'" aria-hidden="true" data-toggle="modal" data-target="#modalCancelRegister"> <span class="glyphicon glyphicon-trash edit-icon-table"></span> </div> </td> </tr> '; return $data_response; } public function get_name_course_edit($courseID_send,$term,$year,$cdate,$chk_edit_after,$registed_courseID){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$courseID_send"; $this->select(); $this->setRows(); $name= $this->rows[0]['name']; $courseID=$this->rows[0]['courseID']; $name=$this->rows[0]['name']; $class_level_data=$this->rows[0]['class_level']; $class_level= $this->get_class_level($class_level_data); $unit_data=$this->rows[0]['unit']; $unit=$this->get_unit_data($unit_data); $department=$this->rows[0]['department']; $hr_learn=$this->rows[0]['hr_learn']; $status_data=$this->rows[0]['status']; $status_form=$this->rows[0]['status_form']; $status_form_text=$this->get_status_form($status_form); $term_new=$this->get_term($unit_data,$status_data,$term); $sql = "SELECT COUNT(*) as num_row FROM tbl_regis_teacher WHERE DataID in( SELECT teacher_id FROM tbl_course_teacher WHERE regis_course_id=$registed_courseID ) "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if($num_row>0){ $data_teacher_icon=' <td style="text-align: center;"> <img data-id-registered="'.$registed_courseID.'" style="width:20px;margin-top: -8px;margin-left: 5px;" class="edit-icon-table btn_teacher_list" aria-hidden="true" data-toggle="modal" data-target="#modalMenageTeacher" src="assets/images/check_person.png"> </td> '; $sql = "SELECT COUNT(*) as num_row_room FROM tbl_room_teacher WHERE course_teacherID in( SELECT DataID FROM tbl_course_teacher WHERE regis_course_id=$registed_courseID ) "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row_room=$this->rows[0]['num_row_room']; if ($num_row_room>0) { $data_room_icon=' <td style="text-align: center;"> <img data-id-registered-room="'.$registed_courseID.'" style="width:26px;margin-top: -8px;margin-left: 5px;" class="edit-icon-table btn_room_detail" aria-hidden="true" data-toggle="modal" data-target="#modalMenageRoom" src="assets/images/glyphicons-200-ban-circle.png"> </td> '; }else{ $data_room_icon=' <td style="text-align: center;"> <img data-id-registered-room="'.$registed_courseID.'" style="width:20px;margin-top: -8px;" class="edit-icon-table btn_room_detail" aria-hidden="true" data-toggle="modal" data-target="#modalMenageRoom" src="assets/images/glyphicons-44-group.png"> </td> '; } }else{ $data_teacher_icon=' <td style="text-align: center;"> <span data-id-registered="'.$registed_courseID.'" class="glyphicon glyphicon glyphicon-user edit-icon-table btn_teacher_list" aria-hidden="true" data-toggle="modal" data-target="#modalMenageTeacher"></span> </td> '; $data_room_icon=' <td style="text-align: center;"> <img style="width:20px;margin-top: -8px;" src="assets/images/glyphicons-44-group.png"> </td> '; } $data_response=' <tr> <td style="padding-left: 30px;">'.$courseID.'</td> <td>'.$name.'</td> <td>'.$status_form_text.'</td> <td style="text-align: center;">'.$unit.'</td> <td style="text-align: center;">'.$hr_learn.'</td> <td style="text-align: center;">'.$class_level.'</td> '.$data_teacher_icon.' '.$data_room_icon.' </tr> '; return $data_response; } public function get_data_registered($data_term_search,$data_year_search,$chk_edit_after,$chk_teacher_icon,$show_delete){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term=$this->rows[0]['term']; $year=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_registed_course WHERE term='$term' AND year='$year' OR term='1,2' AND year='$year' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $registed_courseID= $value['DataID']; $courseID= $value['courseID']; $term= $value['term']; $year= $value['year']; $cdate= $value['cdate']; $data_response['course'].=$this->get_name_course($courseID,$term,$year,$cdate,$chk_edit_after,$registed_courseID,$chk_teacher_icon,$show_delete); } if ($data_response['course']=='') { $data_response['course']=''; } echo json_encode($data_response); } public function get_data_registered_edit($data_term_search,$data_year_search,$chk_edit_after,$chk_teacher_icon,$show_delete){ $this->sql ="SELECT * FROM tbl_set_term_year "; $this->select(); $this->setRows(); $term=$this->rows[0]['term']; $year=$this->rows[0]['year']; $this->sql ="SELECT * FROM tbl_registed_course WHERE term='$term' AND year='$year' OR term='1,2' AND year='$year' "; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $registed_courseID= $value['DataID']; $courseID= $value['courseID']; $term= $value['term']; $year= $value['year']; $cdate= $value['cdate']; $data_response['course'].=$this->get_name_course_edit($courseID,$term,$year,$cdate,$chk_edit_after,$registed_courseID,$chk_teacher_icon,$show_delete); } if ($data_response['course']=='') { $data_response['course']=''; } echo json_encode($data_response); } public function get_course_name($courseID){ $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID=$courseID"; $this->select(); $this->setRows(); $name= $this->rows[0]['name']; $courseID=$this->rows[0]['courseID']; $data_response.='<p>'.$courseID.' : '.$name.'</p>'; return $data_response; } public function chk_regiseted_course($data_val){ $this->sql ="SELECT * FROM tbl_set_term_year"; $this->select(); $this->setRows(); $term= $this->rows[0]['term']; $year= $this->rows[0]['year']; $course_name=""; $arr_id = explode(",", $data_val); for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID={$arr_id[$i]} "; $this->select(); $this->setRows(); $class_level=$this->rows[0]['class_level']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term="1,2"; } $this->sql ="SELECT * FROM tbl_registed_course WHERE courseID={$arr_id[$i]} AND term='$term' AND year='$year'"; $this->select(); $this->setRows(); $courseID=$this->rows[0]['courseID']; if ($courseID!="") { $course_name.=$this->get_course_name($courseID); } } echo json_encode($course_name); } public function insert_data_regis_course($data_val,$cdate){ $this->sql ="SELECT * FROM tbl_set_term_year"; $this->select(); $this->setRows(); $term= $this->rows[0]['term']; $year= $this->rows[0]['year']; $arr_id = explode(",", $data_val); $num=0; for ($i=0; $i < count($arr_id) ; $i++) { $this->sql ="SELECT * FROM tbl_add_delete_course WHERE DataID={$arr_id[$i]}"; $this->select(); $this->setRows(); $class_level= $this->rows[0]['class_level']; $status= $this->rows[0]['status']; if ($class_level=='p1' || $class_level=='p2' || $class_level=='p3' || $class_level=='p4' || $class_level=='p5' || $class_level=='p6') { $term="1,2"; } $this->sql ="INSERT INTO tbl_registed_course(courseID,term,year,cdate) VALUES({$arr_id[$i]},'$term','$year',$cdate)"; $this->query(); $new_id = $this->insertID(); $this->sql ="INSERT INTO tbl_set_count_adttend_class(registed_courseID,week_name) VALUES($new_id,20)"; $this->query(); $num=$num+$i; } return $num; } public function update_data($update,$data_id_course){ $this->sql = "UPDATE tbl_add_delete_course SET ".implode(",",$update)." WHERE DataID='".$data_id_course."'"; $this->query(); } public function get_department($department_data){ if ($department_data=="1") { $department='dep_1'; }elseif($department_data=="2"){ $department='dep_2'; }elseif($department_data=="3"){ $department='dep_3'; }elseif($department_data=="4"){ $department='dep_4'; }elseif($department_data=="5"){ $department='dep_5'; }elseif($department_data=="6"){ $department='dep_6'; }elseif($department_data=="7"){ $department='dep_7'; }elseif($department_data=="8"){ $department='dep_8'; } return $department; } public function remove_registed($data_id,$data_term,$data_year){ $data_response = array(); $sql = "DELETE FROM tbl_registed_course WHERE DataID=$data_id "; $this->sql = $sql; $this->query(); return 0; } public function get_unit($unit_data){ if ($unit_data=="0.5") { $unit='05'; }elseif($unit_data=="1.0"){ $unit='10'; }elseif($unit_data=="1.5"){ $unit='15'; }elseif($unit_data=="2.0"){ $unit='20'; }elseif($unit_data=="2.5"){ $unit='25'; }elseif($unit_data=="3.0"){ $unit='30'; } return $unit; } public function set_room_teacher($course_teacher_id,$room_val){ $sql = "SELECT COUNT(*) AS num_row FROM tbl_room_teacher WHERE course_teacherID=$course_teacher_id AND room=$room_val "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $this->sql =" DELETE FROM tbl_room_teacher WHERE course_teacherID=$course_teacher_id AND room=$room_val "; $this->query(); $new_id = $this->insertID(); }else{ $this->sql ="INSERT INTO tbl_room_teacher(course_teacherID,room) VALUES($course_teacher_id,$room_val)"; $this->query(); $new_id = $this->insertID(); } return $new_id; } public function get_room_detail($registered_id){ $sql = "SELECT tbl_add_delete_course.courseID,tbl_add_delete_course.name ,tbl_add_delete_course.class_level,tbl_registed_course.term,tbl_registed_course.year FROM tbl_add_delete_course,tbl_registed_course WHERE tbl_add_delete_course.DataID=tbl_registed_course.courseID AND tbl_registed_course.DataID=$registered_id "; $this->sql = $sql; $this->select(); $this->setRows(); $courseID=$this->rows[0]['courseID']; $name=$this->rows[0]['name']; $term=$this->rows[0]['term']; $year=$this->rows[0]['year']; $class_level_data=$this->rows[0]['class_level']; $class_level=$this->get_class_level($class_level_data); $data_response['course_detail_header']=' <p style="color: black;text-align: left;"> <span class="ml-20">รหัสวิชา : </span><span>'.$courseID.'</span> <span class="ml-20">รายวิชา : </span><span>'.$name.'</span> <span class="ml-20">ระดับชั้น : </span><span>'.$class_level.'</span> </p> <p style="color: black;text-align: left;"> <span class="ml-20">ภาคเรียนที่ : </span><span>'.$term.'</span> <span class="ml-20">ปีการศึกษา : </span><span>'.$year.'</span> </p> '; $sql = "SELECT * FROM tbl_course_teacher WHERE regis_course_id=$registered_id "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $teacher_id=$value['teacher_id']; $teacher_detail=$this->get_teacher_detail($teacher_id); $room_list=$this->get_room_list($DataID); $data_response['teacher_list_box'].=' <div class="panel panel-violet"> <div class="panel-heading"> <h3 class="panel-title text-left">'.$teacher_detail.' : รับผิดชอบสอนห้อง</h3> </div> <div class="panel-body"> <form> <div style="text-align: left;padding-left: 12%;"> '.$room_list.' </div> </form> </div> </div> '; } echo json_encode($data_response); } public function get_room_list($course_teacherID){ $data_response.='<p >'; for ($i=1; $i <=5 ; $i++) { $sql = "SELECT COUNT(*) AS num_row FROM tbl_room_teacher WHERE course_teacherID=$course_teacherID AND room=$i "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $chk_status='checked'; }else{ $chk_status=''; } $data_response.=' <label class="checkbox-inline mr-30"> <input '.$chk_status.' class="room_btn_chk" type="checkbox" course-teacher-id="'.$course_teacherID.'" value="'.$i.'"> '.$i.' </label> '; } $data_response.='</p>'; $data_response.='<p>'; for ($i=6; $i <=10 ; $i++) { $sql = "SELECT COUNT(*) AS num_row FROM tbl_room_teacher WHERE course_teacherID=$course_teacherID AND room=$i "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $chk_status='checked'; }else{ $chk_status=''; } $data_response.=' <label class="checkbox-inline mr-30"> <input '.$chk_status.' class="room_btn_chk" type="checkbox" course-teacher-id="'.$course_teacherID.'" value="'.$i.'"> '.$i.' </label> '; } $data_response.='</p>'; return $data_response; } public function get_teacher_detail($teacher_id){ $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID=$teacher_id "; $this->sql = $sql; $this->select(); $this->setRows(); $fname_th=$this->rows[0]['fname_th']; $lname_th=$this->rows[0]['lname_th']; return $fname_th.' '.$lname_th; } public function get_teacher_to_course_registed($registered_id){ $sql = "SELECT COUNT(*) as num_row FROM tbl_regis_teacher WHERE DataID in( SELECT teacher_id FROM tbl_course_teacher WHERE regis_course_id=$registered_id ) "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if ($num_row>0) { $number=1; $sql = "SELECT * FROM tbl_regis_teacher WHERE DataID in( SELECT teacher_id FROM tbl_course_teacher WHERE regis_course_id=$registered_id ) "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID=$value['DataID']; $fname_th= $value['fname_th']; $lname_th= $value['lname_th']; $data_response['teacher_listed'].='<p style="text-align:left;">'.$number.'. '.$fname_th.' '.$lname_th.'</p>'; if ($num_row==$number) { $data_response['teacher_id'].=$DataID; }else{ $data_response['teacher_id'].=$DataID.'-'; } $number++; } }else{ $data_response['teacher_listed'].='<p style="text-align:left;">ยังไม่เลือกครูผู้สอน</p>'; } $data_response['num']=$num_row; echo json_encode($data_response); } public function insert_teacher_to_course($teacher_id,$registered_id){ $sql = "SELECT COUNT(*) as num_row FROM tbl_course_teacher WHERE regis_course_id=$registered_id "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; $cdate=date("Y-m-d"); if ($num_row>0) { $sql = "SELECT COUNT(*) as num_row_teacher FROM tbl_course_teacher WHERE regis_course_id=$registered_id AND teacher_id=$teacher_id "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row_teacher=$this->rows[0]['num_row_teacher']; if ($num_row_teacher>0) { $this->sql = "DELETE FROM tbl_course_teacher WHERE teacher_id=$teacher_id AND regis_course_id=$registered_id"; $this->query(); $sql = "SELECT COUNT(*) as num_row FROM tbl_course_teacher WHERE regis_course_id=$registered_id "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row=$this->rows[0]['num_row']; if($num_row==0) { $this->sql = "DELETE FROM tbl_registed_course_teaching WHERE registed_courseID=$registered_id" ; $this->query(); } }else{ $this->sql = "INSERT INTO tbl_course_teacher(teacher_id,regis_course_id) VALUES($teacher_id,$registered_id)"; $this->query(); } }else{ $this->sql = "INSERT INTO tbl_course_teacher(teacher_id,regis_course_id) VALUES($teacher_id,$registered_id)"; $this->query(); $this->sql = "INSERT INTO tbl_registed_course_teaching(registed_courseID,cdate) VALUES($registered_id,'$cdate')"; $this->query(); } return '1'; } public function get_teacher_list($data_id_registered,$teacher_search_data){ $data_response = array(); if ($teacher_search_data!='') { $sql_condition="AND fname_th LIKE '%$teacher_search_data%' OR lname_th LIKE '%$teacher_search_data%'"; }else{ $sql_condition=""; } $sql = "SELECT * FROM tbl_regis_teacher WHERE status_alive=1 AND status=1 $sql_condition "; $this->sql = $sql; $this->select(); $this->setRows(); foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $fname_th= $value['fname_th']; $lname_th= $value['lname_th']; $data_list.=' <tr> <td><input class="checkbox_data_teacher_'.$DataID.'" onclick="insert_teacher_to_course('.$DataID.','.$data_id_registered.')" type="checkbox" value="'.$DataID.'" name="checkbox_regis_teacher_to_course[]" id="checkbox'.$DataID.'"></td> <td style="text-align:left;padding-left: 30px;">'.$fname_th.'</td> <td style="text-align:left;padding-left: 30px;">'.$lname_th.'</td> </tr> '; } if ($data_list=='') { $data_list=''; } return json_encode($data_list); } public function getdata_edit($data_id){ $data_response = array(); $sql = "SELECT * FROM tbl_add_delete_course WHERE DataID=$data_id "; $this->sql = $sql; $this->select(); $this->setRows(); $data_response['data_id_course']=$this->rows[0]['DataID']; $data_response['courseID']=$this->rows[0]['courseID']; $data_response['name']=$this->rows[0]['name']; $data_response['class_level']=$this->rows[0]['class_level']; $unit_data=$this->rows[0]['unit']; $data_response['unit']=$this->get_unit($unit_data); $department_data=$this->rows[0]['department']; $data_response['department']=$this->get_department($department_data); $data_response['hr_learn']=$this->rows[0]['hr_learn']; $data_response['status']=$this->rows[0]['status']; return json_encode($data_response); } public function get_class_level($class_level_data){ if ($class_level_data=="p1") { $class_level="ป.1"; }elseif($class_level_data=="p2"){ $class_level="ป.2"; }elseif($class_level_data=="p3"){ $class_level="ป.3"; }elseif($class_level_data=="p4"){ $class_level="ป.4"; }elseif($class_level_data=="p5"){ $class_level="ป.5"; }elseif($class_level_data=="p6"){ $class_level="ป.6"; }elseif($class_level_data=="m1"){ $class_level="ม.1"; }elseif($class_level_data=="m2"){ $class_level="ม.2"; }elseif($class_level_data=="m3"){ $class_level="ม.3"; }elseif($class_level_data=="m4"){ $class_level="ม.4"; }elseif($class_level_data=="m5"){ $class_level="ม.5"; }elseif($class_level_data=="m6"){ $class_level="ม.6"; } return $class_level; } function get_unit_data($unit_data){ if ($unit_data==0.0 || $unit_data==9.9) { $unit="-"; }else{ $unit=$unit_data; } return $unit; } public function get_data($arr_search_val){ $data_response = array(); $sql_condition = " DataID > 0 "; $status = $arr_search_val['status']; $courseID_search = $arr_search_val['courseID_search']; $department_search = $arr_search_val['department_search']; $class_level_search = $arr_search_val['class_level_search']; if ($status!=1) { if (isset($courseID_search) && $courseID_search != "") { $sql_condition .= " AND ( courseID LIKE '%{$courseID_search}%') "; } if (isset($department_search) && $department_search != "") { if ($department_search=="dev_mode") { $sql_condition .= " AND ( status=2 ) "; }else{ $sql_condition .= " AND ( department = '$department_search') "; } } if (isset($class_level_search) && $class_level_search != "") { $sql_condition .= " AND ( class_level = '$class_level_search') "; } }else{ if (isset($courseID_search) && $courseID_search != "") { $sql_condition .= " AND ( courseID LIKE '%{$courseID_search}%') "; } } $sql = "SELECT count(*) as num_row_count FROM tbl_add_delete_course WHERE $sql_condition ORDER BY DataID DESC "; $this->sql = $sql; $this->select(); $this->setRows(); $num_row_count=$this->rows[0]['num_row_count']; $sql = "SELECT * FROM tbl_add_delete_course WHERE $sql_condition ORDER BY DataID DESC "; $this->sql = $sql; $this->select(); $this->setRows(); if ($num_row_count!=0) { foreach($this->rows as $key => $value) { $DataID= $value['DataID']; $courseID= $value['courseID']; $name= $value['name']; $class_level_data= $value['class_level']; $class_level=$this->get_class_level($class_level_data); $unit_data= $value['unit']; $status_form= $value['status_form']; $status_form_text=$this->get_status_form($status_form); $unit=$this->get_unit_data($unit_data); $hr_learn= $value['hr_learn']; $data_response['table_list'].=' <tr> <td> <input class="checkbox_data" type="checkbox" value="'.$DataID.'" name="checkbox_regis_course[]" id="checkbox'.$DataID.'"> </td> <td>'.$courseID.'</td> <td>'.$name.'</td> <td>'.$status_form_text.'</td> <td style="text-align: center;">'.$unit.'</td> <td style="text-align: center;">'.$hr_learn.'</td> <td style="text-align: center;">'.$class_level.'</td> </tr> '; } }else{ $data_response['table_list'].=''; } return json_encode($data_response); } public function get_status_form($status_form){ switch ($status_form) { case '11': $data_response='พื้นฐาน'; break; case '12': $data_response='เพิ่มเติม'; break; case '21': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; case '22': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; case '23': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; case '24': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; case '25': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; case '26': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; case '27': $data_response='กิจกรรมพัฒนาผู้เรียน'; break; default: $data_response=''; break; } return $data_response; } }<file_sep>/modules/report_std_personal/report_form_p.php <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/margin-padding.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/responsive.css" rel="stylesheet" type="text/css"> <link href="../../assets/css/print_std_personal.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" rel="stylesheet" type="text/css"> <script type="text/javascript" src="../../assets/js/jquery.js"></script> <style type="text/css"> <!-- table { border-collapse: collapse; } td, th { border: 1px solid black; padding: 2px; } --> </style> <?php @session_start(); require_once('../../init.php'); include('class_modules.php'); $class_data = new ClassData(); $std_ID=$_GET['std_ID']; $term=$_GET['term']; $year=$_GET['year']; ?> <div style="background-color: rgb(82, 86, 89);min-height: 100%"> <div class="container" style="font-size: 10%;background-color: white;min-height: 100%"> <?php $arr_id = explode(",", $std_ID); for ($i=0; $i < count($arr_id) ; $i++) { $pw6_p=$class_data->get_pw6_p($arr_id[$i],$term,$year); ?> <div style="page-break-after:always;"> <page> <p style="position: absolute;right: 30px;top: 30px;font-size: 20px;">ปพ.6</p> <div class="col-sm-12 " style="font-size: 18px;margin-top: 52px;line-height: 0.9;"> <p class="text-bold text-center" style="margin-top: -8px;">รายงานการพัฒนาคุณภาพผู้เรียนเป็นรายบุคคล</p> <p class="text-bold text-center" style="line-height: 0.3">โรงเรียนเทศบาลวัดสระทอง สังกัดเทศบาลเมืองร้อยเอ็ด อำเภอเมือง จังหวัดร้อยเอ็ด</p> <p style="margin-left: 40px;"> <span class="text-bold">ขื่อ-สกุล</span> <?php echo $pw6_p['std_name']; ?> <span style="position: absolute;left: 42%"><span class="text-bold" >เลขที่</span> 1 </span> <span style="position: absolute;left: 53.2%"><span class="text-bold" style="margin-left:80px;">เลขประจำตัวนักเรียน</span> <?php echo $pw6_p['std_ID']; ?></span> </p> <p style="line-height: 0.5;margin-left: 40px;"> <span class="text-bold">ประถมศึกษาปีที่</span> <?php echo $pw6_p['class_level_room']; ?> <span class="text-bold" style="margin-left:165px;">ปีการศึกษา</span> <?php echo $pw6_p['year']; ?> <span class="text-bold" style="margin-left:80px;">เลขประจำตัวประชาชน</span> <?php echo $pw6_p['card_ID']; ?> </p> </div> <div> <table style="width: 94%;margin-left: 20px;margin-top: 20px;font-size: 16px;"> <thead style="font-weight: bold;text-align: center;background-color: #ddddddb3;"> <tr> <th colspan="11" style="text-align: center;">การพัฒนาคุณภาพผู้เรียน</th> </tr> <tr> <th rowspan="2" style="width: 5%;text-align: center;">ที่</th> <th rowspan="2" style="text-align: center;">กลุ่มสาระการเรียนรู้</th> <th rowspan="2" style="width: 10%;text-align: center;">รหัสวิชา</th> <th rowspan="2" style="width: 5%;padding: 0;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> น้ำหนัก </div> </th> <th style="height: 70px;line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> คะแนน<br>ภาคเรียนที่ 1 </div> </th> <th style="line-height: 1;width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> คะแนน<br>ภาคเรียนที่ 2 </div> </th> <th style="width: 1%;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;"> คะแนนรวม </div> </th> <th rowspan="2" style="width: 14%;text-align: center;">ระดับ<br>ผลการเรียนเฉลี่ย<br>(GPA)</th> <th rowspan="2" style="width: 5%;padding: 0;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;margin-left: -10px;margin-right: -10px;"> คุณลักษณะฯ </div> </th> <th rowspan="2" style="width: 5%;padding: 0;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;margin-left: -10px;margin-right: -10px;"> อ่าน เขียนฯ </div> </th> <th rowspan="2" style="width: 5%;padding: 0;text-align: center;"> <div style="transform: rotate(-90deg);white-space: nowrap;margin-left: -10px;margin-right: -10px;"> หมายเหตุ </div> </th> </tr> <tr> <th style="text-align: center;">50</th> <th style="text-align: center;">50</th> <th style="text-align: center;">100</th> </tr> </thead> <tbody style="text-align: center;"> <tr > <td colspan="3" style="text-align: left;font-weight: bold;">รายวิชาพื้นฐาน</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <?php if ($pw6_p['sub_main_list']=='') {?> <tr style="height: 34px;"> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <?php }else{ ?> <?php echo $pw6_p['sub_main_list']; ?> <?php } ?> <tr> <td colspan="3" style="text-align: left;font-weight: bold;">รายวิชาเพิ่มเติม</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <?php if ($pw6_p['sub_add_list']=='') {?> <tr style="height: 34px;"> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <?php }else{ ?> <?php echo $pw6_p['sub_add_list']; ?> <?php } ?> <?php echo $pw6_p['sub_sum_list']; ?> <tr style="background-color: #ddddddb3;" > <th colspan="2">กิจกรรมพัฒนาผู้เรียน</th> <th style=";text-align: center;"></th> <th></th> <th></th> <th></th> <th></th> <th style=";text-align: center;">ผลการประเมิน</th> <th></th> <th></th> <th></th> </tr> <?php if ($pw6_p['sub_dev_list']=='') {?> <tr style="height: 34px;"> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <?php }else{ ?> <?php echo $pw6_p['sub_dev_list']; ?> <?php } ?> </tbody> </table> </div> <div style="margin-top: 30px;"> <table style="width: 40%;margin-left: 20px;margin-top: 20px;font-size: 16px;"> <?php echo $pw6_p['sub_conclution_list']; ?> </table> </div> <div class="printOnly" style=" margin-top: -240px;font-size:16px;margin-left: 450px;line-height: 0.7;"> <div> <p>......................................................... ครูประจำชั้น</p> <p><span style="margin-right: 145px;">(</span><span>)</span></p> <p style="margin-left: 16px;">................./.............../...............</p> </div> <div style="margin-top: 40px;"> <p>......................................................... ผู้อำนวยการสถานศึกษา</p> <p><span style="margin-right: 145px;">(</span><span>)</span></p> <p style="margin-left: 16px;">................./.............../...............</p> </div> <div style="margin-top: 40px;"> <p>......................................................... ผู้ปกครอง</p> <p><span style="margin-right: 145px;">(</span><span>)</span></p> <p style="margin-left: 16px;">................./.............../...............</p> </div> </div> <table id="footer" class="printOnly" width="100%" style="border: none;"> <tbody style="border: none;"> <tr > <td width="100%" style="border: none;"> <div style="line-height: 0.5;margin-left: 50px;"> <p>หมายเหตุ : การประเมินผลคุณลักษณะอันพึงประสงค์ 3 หมายถึง ดีเยี่ยม, 2 หมายถึง ดี, 1 หมายถึง ผ่าน</p> <p style="margin-left:50px; ">การประเมินผลการอ่าน เขียน คิด วิเคราะห์ 3 หมายถึง ดีเยี่ยม, 2 หมายถึง ดี, 1 หมายถึง ผ่าน</p> </div> </td> </tr> </tbody> </table> </page> </div> <?php } ?> </div> </div> <script> $(document).ready(function() { get_print(); setTimeout(window.close, 0); }); function get_print() { window.print(); } </script><file_sep>/src/class_role.php <?php class ClassRole extends Databases { /*************************************** PROCESS DB ****************************************/ public function ath_chk_role($user_id){ $this->sql = "SELECT * FROM tbl_regis_teacher WHERE DataID={$user_id}"; $this->select(); $this->setRows(); return $this->rows[0]['status']; } /*************************************** PROCESS DB ****************************************/ } ?><file_sep>/modules/news/edit.js var opPage = 'news'; $(document).ready(function() { get_news_detail(); $('#data_id').val(_get.id); }); function get_news_detail() { var news_id=_get.id; var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_news_detail" }); formData.push({ "name": "news_id", "value": news_id }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $('#title').val(data.title); $('#detail_box').val(data.detail); $('#img_list').html(data.img_list); }) } $(document).delegate('.delete_img_set', 'click', function(event) { var data_id = $(this).attr('data-id'); var set_type = $(this).attr('set-type'); $(document).delegate('#btn_delete_img', 'click', function(event) { var formData = new Array(); formData.push({ "name": "acc_action", "value": "delete_img_file" }); formData.push({ "name": "data_id", "value": data_id }); formData.push({ "name": "set_type", "value": set_type }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_news_detail(); $('.modal').modal('hide'); }); }); }); $(document).delegate('#btn_edit_news', 'click', function(event) { $("#btn_submit").click(); }); function loadFile1() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output1'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile2() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output2'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile3() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output3'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile4() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output4'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; function loadFile5() { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output5'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; <file_sep>/modules/attend_class/backup/index.js var opPage = 'attend_class'; $(document).ready(function() { get_coures_id_list(); //$(".course_detal_box").hide(); }); function remove_selected_count_adttend_class() { for (var i = 1; i <= 20; i++) { $("#set_count_adttend_class_"+i).removeAttr('selected'); } } function get_count_adttend_class_val() { var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_count_adttend_class_val" }); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { remove_selected_count_adttend_class(); $("#set_count_adttend_class_"+data).attr('selected','selected'); }) } $(document).delegate('#btn_save_attend_score_std', 'click', function(event) { var inputs = document.getElementsByClassName( 'select-table-form ' ), value_attend_week = [].map.call(inputs, function( input ) { return input.value; }).join( ',' ); var std_id_all=$("#std_id_all").val(); var all_attendID= $("#all_attendID").val(); var length_list_val= $("#length_list_val").val(); //var set_count_adttend_class_val= $("#set_count_adttend_class_val").val(); var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "save_attend_score_std" }); formData.push({ "name": "value_attend_week", "value": value_attend_week }); formData.push({ "name": "std_id_all", "value": std_id_all }); formData.push({ "name": "all_attendID", "value": all_attendID }); formData.push({ "name": "length_list_val", "value": length_list_val }); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val }); //formData.push({ "name": "set_count_adttend_class_val", "value": set_count_adttend_class_val }); $.post('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { get_week_list(); get_count_adttend_class_val(); $(".modal").modal('hide'); }) }) $(document).delegate('#btn_set_data_seem', 'click', function(event) { var legth_week=$("#legth_week").val(); var attend_seem_value_main=$("#attend_seem_value_main").val(); $(".class_col_"+legth_week).val(attend_seem_value_main); }) function open_edit_attend() { $(".class_col_set_new").attr('disabled','disabled'); var legth_week=$("#legth_week").val(); $(".class_col_"+legth_week).removeAttr('disabled'); } function get_week_list_data() { var room_search=$("#room_search").val(); var length_list_val=$("#length_list_val").val(); var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_week_list_data" }); formData.push({ "name": "room_search", "value": room_search}); formData.push({ "name": "length_list_val", "value": length_list_val}); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { /*$("#objective_list").html(data.objective_list); $("#ob_title_table_col").html(data.ob_title_table_col); $("#detail_std").html(data.detail_std); $("#data_objectiveID_of_title").val(data.data_objectiveID_of_title); $("#std_id_all").val(data.std_id_all); set_col_header(length_list_val); open_edit_score();*/ $("#all_attendID").val(data.all_attendID); $("#std_id_all").val(data.std_id_all); $("#detail_std").html(data.detail_std); open_edit_attend(); }) } function get_week_between() { var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_week_between" }); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#length_list_val").html(data); }) } function get_week_list() { var length_list_val=$("#length_list_val").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_week_list" }); formData.push({ "name": "length_list_val", "value": length_list_val}); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { //alert(data) $("#legth_week").html(data.week_list); $("#week_header").html(data.week_header); get_week_list_data(); }) } $(document).delegate('#btn_search_course_detail', 'click', function(event) { var formData = $( "#frm_data_room" ).serializeArray(); formData.push({ "name": "acc_action", "value": "search_course_detail" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#place_detail_courseID").html(data.courseID); $("#place_detail_name").html(data.name); $("#place_detail_unit").html(data.unit); $("#place_detail_hr_learn").html(data.hr_learn); $("#place_detail_class_level").html(data.class_level_co); $("#hr-co-text-depart_course").show(); $(".course_detal_box").show(); get_week_between(); get_week_list(); get_count_adttend_class_val(); //get_config(); }) }) function get_class_level() { var coures_id_list_val =$("#coures_id_list").val(); var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_class_level" }); formData.push({ "name": "coures_id_list_val", "value": coures_id_list_val }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#place_class_level").html(data.class_level); $("#room_search").html(data.room); }) } function get_coures_id_list() { var formData = new Array(); formData.push({ "name": "acc_action", "value": "get_coures_id_list" }); $.getJSON('modules/' + opPage + '/process.php', formData, function(data, textStatus, xhr) { $("#coures_id_list").html(data.coures_id_list); get_class_level(); }) }
50e3fec5137777235f63f9330831975f05715b24
[ "JavaScript", "SQL", "PHP" ]
140
JavaScript
golfchanut/sratong
cd03c65350ffd53e8d48f9c34e28f9a22ab88c0a
8ce413fdf5a83c8f8e0b3d30beb26f4f262beca6
refs/heads/master
<repo_name>cjtorralba/PSU<file_sep>/Term_One/Prog_One/GPACalc.cpp #include <iostream> using namespace std; /* * code written by <NAME> for the 3rd time cause I keep deleting it accidentally * first PSU assignment for Comp Sci 162, job is to calculate avg GPA */ double charToDouble(char c, char plus_Or_Minus); // The job of this function is to convert grade such as b- to gradePoints int main() { int totalClasses; // Total number of classes the user is taking char letterGrade, plusOrMinus; // the users letter grade for specified class, and if they got a +/- double totalGradePoints; // total amount of grade points, ex: a = 4.0, b- = 2.67 double avgGpa; // calculated by dividing totalGradePoints by totalClasses char recalculate = 'y'; // setting recalculate to be 'y' at first // Beggining of while to ask user for grades and calculate gpa while(recalculate == 'y') { cout << "How many classes are you taking?" << endl; cin >> totalClasses; int loopCounter = totalClasses; // this is for the for() loop, in case we change the value of totalClasses for(int i = 1; i <= loopCounter; i++) { cin.ignore(100, '\n'); cout << "What was the letter grade for class number " << i << endl; cout << "Enter P if pass and F is failed for pass/fail classes" << endl; cin >> letterGrade; if(letterGrade == 'p' || letterGrade == 'f'){ --totalClasses; } // if pass or fail, wont effect gpa plusOrMinus = cin.peek(); totalGradePoints += charToDouble(letterGrade, plusOrMinus); } avgGpa = totalGradePoints / totalClasses; cout << "Average GPA is: "; cout.precision(3); cout << avgGpa << endl; cout << "Would you like to re-calculate? <y/n>" << endl; //got to make sure buffer is clear before asking if user wants to retry cin.ignore(100, '\n'); recalculate = cin.get(); //setting all my variables back to zero in case user wants to recalculate avgGpa = 0.0; totalClasses = 0; totalGradePoints = 0.0; cin.clear(); cin.ignore(100, '\n'); } return 0; } double charToDouble(char c, char plus_Or_Minus) { double returnVal; // value of the character tolower(c); switch(c) { case 'a': returnVal = 4.0; break; case 'b': returnVal = 3.0; break; case 'c': returnVal = 2.0; break; case 'd': returnVal = 1.0; break; case 'f': returnVal = 0.0; break; default: break; } switch(plus_Or_Minus) { case '+': returnVal += 0.33; break; case '-': returnVal -= 0.33; break; default: break; } return returnVal; } <file_sep>/Term_Three/prog3/derived.h #include "base.h" //header file with derived classes and their fucntions //webstie class class website : public base { public: //constructoprs and destructors website(); ~website(); website(char priority, char* subject, char* link); website(const website& toCopy); void display(); //displays infromation void writeToFile(); //writes to fiel private: char* link; //one data members which is the link to the website }; //zoom meeting class class zoom : public base { public: //constructors and destrcutctos zoom(); ~zoom(); zoom(char priority, char* subject, char* teacher, char* time, char* id); zoom(const zoom& toCopy); void display(); //displays information void writeToFile(); //writes information tot he file private: //data members which include the teacher leading the lecture, the time the meeting starts, and the meeting id char* teacher; char* time; char* id; }; //book class class book : public base { public: //constructors and destructos book(); ~book(); book(char priority, char* subject, char* pages, char* author, char* title); book(const book& toCopy); void display(); //displays information void writeToFile(); //writes to file private: //data members char* pages; char* author; char* title; }; <file_sep>/Term_Two/Prog3/main.cpp #include "header.h" /* * This code is by <NAME> in cs163 * main focus is to explore hash tables * this program allows you to enter meals you have eaten from certain establishments and they will be * stored into a hjash table * you may also remove meals and add more when you want * you may also display information about a certain meal if you wish * thanks! */ //These two functions are purely for ease and I made them cause i was running out of time on this project //please do not grade me down on them I could have implemented them elsewhere it would have just taken longer bool again() { char response; cout << "Would you like to enter another? <y,n>" << endl; cin >> response; cin.ignore(100, '\n'); if(response == 'y') return true; return false; } bool type() { char input; cout << "Is it a food cart or restaurant? <f,r>" << endl; cin >> input; cin.ignore(100, '\n'); if(input == 'c') return true; return false; } int main() { table myTable; char input[100]; char meals[50]; meal* pmeal; meal first; first.mealName = new char[100]; first.name = new char[100]; first.review = new char[100]; do{ cout << "Meal name: " << endl; cin.get(first.mealName, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Establishment name: " << endl; cin.get(first.name, 100, '\n'); cin.ignore(100, '\n'); cout << "Review: " << endl; cin.get(first.review, 100, '\n'); cin.ignore(100, '\n'); cout << "Approximate price: " << endl; cin >> first.price; cout << "Rating <1-10>: " << endl; cin >> first.rating; first.type = type(); myTable.add(first.mealName, &first); }while(again()); do { cout << "Enter r to remove a meal by the name" << endl <<"Enter ra to remove all meals by a certain establishment" << endl << "Enter d to display a meal and its information" << endl << "Enter a to add more meals" << endl; cin.get(input, 100, '\n'); cin.ignore(100, '\n'); if(strcmp(input, "r") == 0) { cout << "Please enter the meal name" << endl; cin.get(meals, 100, '\n'); cin.ignore(100, '\n'); pmeal = myTable.retrieve("meals"); if(pmeal != NULL) { cout << "Your removed: " << endl; (*pmeal).display(); pmeal = NULL; myTable.remove(meals); } } else if(strcmp(input, "d") == 0) { cout << "Enter meal you would like to see" << endl; cin.get(meals, 10, '\n'); cin.ignore(100, '\n'); if(!myTable.display(meals)) "Looks like the meal doesn't exist yet!" << endl; } else if(strcmp(input, "a") == 0) { do{ cout << "Meal name: " << endl; cin.get(first.mealName, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Establishment name: " << endl; cin.get(first.name, 100, '\n'); cin.ignore(100, '\n'); cout << "Review: " << endl; cin.get(first.review, 100, '\n'); cin.ignore(100, '\n'); cout << "Approximate price: " << endl; cin >> first.price; cout << "Rating <1-10>: " << endl; cin >> first.rating; first.type = type(); myTable.add(first.mealName, &first); cout << "You are still adding meals" << endl; }while(again()); } else if(strcmp(input, "ra") == 0) { cout << "Please enter the establishment name you would like to remove meals from" << endl; cin.get(meals, 100, '\n'); cin.ignore(100, '\n'); cout << "Removing all meals made from: " << meals << endl; myTable.removeAll(meals); } else cout << "Not valid" << endl; }while(again()); return 0; } <file_sep>/Term_Two/prog5_backup/class.cpp #include "header.h" void myClass::copy(myClass* toCopy) { name = new char[strlen(toCopy->name) + 1]; strcpy(name, toCopy->name); } graph::graph(int size) { int i; list_size = size; list = new vertex[list_size]; for(i = 0; i < list_size; ++i) { list[i].currentClass = NULL; list[i].head = NULL; list[i].tail = NULL; } } int graph::findLocation(char* key) { int position = -1; int count; bool found = false; for(count = 0; count < list_size; ++count) { if(list[count].currentClass && strcmp(key, list[count].currentClass->name) == 0) position = count; } return position; } bool graph::traverse(char* name) { int current = findLocation(name); node* cur; vertex* currentVert = &list[current]; if(list[current].head == NULL) cout << "Last class in this path is " << list[current].currentClass->name << endl; else { for(cur = list[current].head; cur != NULL; cur = cur->next) { cout << "You can take " << currentVert->currentClass->name << " after " << name << endl; traverse(currentVert->currentClass->name); } } /* for(i = 0; i < list_size; ++i) { if(list[i].currentClass && (strcmp(name, list[i].currentClass->name) == 0)) { cout << list[i].currentClass->name << "" << endl; cout << "After this you can take "; cur = list[i].head; while(cur->next != NULL) { connected = true; cout << "Calling traverse on " << cur->adjacent->currentClass->name << endl; if(cur->adjacent->currentClass) traverse(cur->adjacent->currentClass->name); cur = cur->next; } } } */ return true; } bool graph::insertVertex(myClass* to_insert) { bool inserted = false; int count = 0; while(!inserted && (count < list_size)) { if(!list[count].currentClass) { inserted = true; list[count].currentClass = new myClass; list[count].currentClass->copy(to_insert); list[count].head = NULL; } ++count; } return inserted; } int graph::test(int i) { /* node* cur; for(int j = 0; j < list_size; ++j) { cout << list[j].currentClass->name << " at position " << j << endl; cur = list[j].head; while(cur != NULL) { cout << cur->adjacent->currentClass->name << endl; cur = cur->next; } } node* cur; k for(cur = list[i].head; cur != NULL; cur = cur->next) cout << cur->adjacent->currentClass->name << endl; if(!cur) cout << "WHY is this happenening" << endl; return i; */ } bool graph::insertEdge(char* name, char* connect) { int current = findLocation(name); int attach = findLocation(connect); if(current == -1 || attach == -1) return false; else { if(!list[current].head) { cout << "head is NULL" << endl; list[current].head = new node; list[current].head->next = NULL; list[current].head->adjacent = attach; cout << "Attached " << list[current].currentClass->name << " to " << list[attach].currentClass->name << endl; return true; } else { list[current].tail = new node; list[current].tail->next = NULL; list[current].tail->adjacent = attach; // list[current].tail = list[current].tail->next; cout << "Attached " << list[current].currentClass->name << " to " << list[attach].currentClass->name << endl; return true; } } /* for(i = 0; i < list_size; ++i) { if(list[i].currentClass && strcmp(name, list[i].currentClass->name) == 0) { if(!list[i].head) { list[i].head = new node; list[i].head->next = NULL; cur = list[i].head; } else { cur = list[i].head; while(cur != NULL) cur = cur->next; cur = new node; cur->next = NULL; } for(j = 0; j < list_size; ++j) { if(list[j].currentClass && strcmp(connect, list[j].currentClass->name) == 0) { cout << "connecting to " << list[j].currentClass->name << endl; cur->adjacent = &list[j]; connected = true; } } } } return connected; */ } /* bool graph::display() { bool full = false; myClass* cur; int i; for(i = 0; i < list_size; ++i) { if(list[i].currentClass) { full = true; cout << "Class: " << list[i].currentClass->name << endl; cout << "Pre Reqs: " << endl; cur = list[i].currentClass->head; while(cur->next != NULL) { cout << "\tClass: " << cur->name << endl; cur = cur->next; } } } return full; } */ <file_sep>/Term_Three/prog3/base.h #include <iostream> #include <cstring> #include <cctype> #include <fstream> using namespace std; //base class holding information that is necessary for all the children class base { public: base(); ~base(); // constructors and destructors base(char* subject, char priority); base(const base& toCopy); void display(); //display function char getPriority(){ return priority; } //returns the priority which is a charaxcter void writeToFile(ofstream& out); //writes to file, taking a ofstream object as an argument, I dont know why but it works for some reason private: char* subject; //subjcet of the object char priority; //priority from 0-9 0 being most important }; <file_sep>/Term_Three/prog2/derived.h #include "base.h" //this is the header file for all the derived classes of the base class //swim class class swim : public base { public: //constructors and destructor swim(); ~swim(); swim(const swim & toCopy); swim(int length, int priority, bool group, char* name, char* location, char* swimsuit, bool member, bool hasHotTub); void display(); //display function void startExercise(); //user can se wether or not they want to work out on this trip private: char* swimSuit; //type of swimsuit or color of swim suit, upto the user bool member; //if they are a member of the pool club bool hasHotTub; //if the pool has a hot tub bool exercise; //true if they was to work out on this trip, false otherwise }; //hiking class class hike : public base { public: //constructor and destructor hike(); ~hike(); hike(const hike & toCopy); hike(int length, int priority, bool group, char* name, char* location, bool overNight, char* season, char* weather); void display(); //display function bool rockClimb(); //prompts the user if they was to pack rock climbining shoes private: bool overNight; //true if the hike is going to be overnight char* season; //season char* weather; //weather suny, rainy etc bool climbShoes;//true if they packed rock climbing shoes }; //work class class work : public base { public: //work class constructor and destructor work(); ~work(); work(const work& toCopy); work(int length, int priority, bool group, char* name, char* location, char* position, int pay, bool partTime); void display(); //display functions void planLunch(); //prompts the user as to which luinch they want to pack private: char* position; //position at work manager, floor staff etc double pay; //pay per hour bool partTime; //true if part time job, fals otherwise char* lunch; //their lunch tehy packed }; <file_sep>/Term_Three/prog1/node.cpp #include "node.h" //node constructors node::node() : myVideo(NULL), myStream(NULL), myEmail(NULL), myEssay(NULL), next(NULL), type(-1) { } //copy contrusctor for the node class node::node(const node & toAdd) { next = NULL; //have to set the type or else we will seg fault if(toAdd.myVideo) { myVideo = new video(*toAdd.myVideo); myStream = NULL; myEmail = NULL; myEssay = NULL; type = toAdd.type; } else if(toAdd.myStream) { myStream = new liveStream(*toAdd.myStream); myVideo = NULL; myEmail = NULL; myEssay = NULL; type = toAdd.type; } else if(toAdd.myEmail) { myEmail = new email(*toAdd.myEmail); myVideo = NULL; myStream = NULL; myEssay = NULL; type = toAdd.type; } else if(toAdd.myEssay) { myEssay = new essay(*toAdd.myEssay); myVideo = NULL; myEmail = NULL; myStream = NULL; type = toAdd.type; } } //recursive destructor node::~node() { delete next; if(myVideo) delete myVideo; else if(myStream) delete myStream; else if(myEmail) delete myEmail; else if(myEssay) delete myEssay; myVideo = NULL; myStream = NULL; myEmail = NULL; myEssay = NULL; next = NULL; } //recursive function to add to the end of void node::addToEnd(node* source, node*& head) { if(!head) { head = new node(*source); return; } addToEnd(source, head->goNext()); } //returns the node->next of current node node *& node::goNext() { return this->next; } //returns type, this is necessary for //adding nodes to the node array in the table class int node::getType() { return type; } //for traversing through the linear linked list node *& node::returnNext() { return next; } /* * =========Adding our learning method objects to the nodes======= * 0 = video * 1 = liveStream * 2 = email * 3 = essay */ //setting our class members to a new objects using the copy constructors of each class void node::addVideo(video& toAdd) { myVideo = new video(toAdd); type = 0; } void node::addStream(liveStream& toAdd) { myStream = new liveStream(toAdd); type = 1; } void node::addEmail(email& toAdd) { myEmail = new email(toAdd); type = 2; } void node::addEssay(essay& toAdd) { myEssay = new essay(toAdd); type = 3; } //our display function //this uses our type member of the node class to see if the array is NULL bool node::displayNode() { bool displayed = false; /* * using switch case on our type member * 0 = video * 1 = liveStream * 2 = email * 3 = essay */ switch(type) //using the type of object to call corresponding functions { case 0: myVideo->display(); displayed = true; break; case 1: myStream->display(); displayed = true; cout << "done " << endl; break; case 2: myEmail->display(); displayed = true; break; case 3: myEssay->display(); displayed = true; break; case -1: break; default: break; } return displayed; } //=====================Table constructor and functions ====================A //table constructor table::table() { int i; size = 4; //setting our table to size four since we only have four classes we're dealing with nodeTable = new node*[size]; //allocating new array of node of size N for(i = 0; i < size; ++i) nodeTable[i] = NULL; //setting them all to NULL } //table destructor calls node destructor on each element table::~table() { int i; for(i = 0; i < size; ++i) { if(nodeTable[i]) { delete nodeTable[i]; nodeTable[i] = NULL; } } delete [] nodeTable; nodeTable = NULL; } //adds a node to the nodeTable array //if the position is null we just set the first //if it is not null we call the recursive addToEnd() function for the node bool table::addNode(node* toAdd) { int position = toAdd->getType(); //position in array if(position == -1) return false; //this means the node has nothing in it so we are not going to add it else { //since the position is not -1, the node we want to add must exist if(nodeTable[position] == NULL) //our position in the node table is empty { nodeTable[position] = new node(*toAdd); return true; //our node has succefully been added } else //our position in the node table is not empty so we need to add to the linear linked list { nodeTable[position]->addToEnd(toAdd, nodeTable[position]); //calling recursive function to add to the end of our linear linked list return true; } } return false; //if it did not enter any of the blocks, it did not add the node succefully, therefore returning false } //These following display functions are for displaying all of any given //objects using their type // /* for reference * 0 = video * 1 = liveStream * 2 = email * 3 = essay */ void table::displayVid() { node* cur; if(nodeTable[0]) for(cur = nodeTable[0]; cur != NULL; cur = cur->returnNext()) { cout << endl; cur->displayNode(); } } void table::displayEmails() { node* cur; if(nodeTable[2]) for(cur = nodeTable[2]; cur != NULL; cur = cur->returnNext()) { cout << endl; cur->displayNode(); } } void table::displayEssays() { node* cur; if(nodeTable[3]) for(cur = nodeTable[3]; cur != NULL; cur = cur->returnNext()) { cout << endl; cur->displayNode(); } } void table::displayStreams() //displaying all streams(type id = 3); { node* cur; if(nodeTable[1]) for(cur = nodeTable[1]; cur != NULL; cur = cur->returnNext()) { cout << endl; cur->displayNode(); } } //displays all objects and in all elements of the array void table::displayAll() { int i; node* cur; //temp node for traversing throuh the list for(i = 0; i < size; ++i) { /* for reference * 0 = video * 1 = liveStream * 2 = email * 3 = essay */ if(nodeTable[i]) //if we have nodes in this element { switch(i) //our i counter corresponds to what type of object we are dealing with { case 0: cout << "Videos: " << endl; break; case 1: cout << "LiveStreams: " << endl; break; case 2: cout << "Emails: " << endl; break; case 3: cout << "Essays: " << endl; break; } for(cur = nodeTable[i]; cur != NULL; cur = cur->returnNext()) { cur->displayNode(); cout << endl; } } } } <file_sep>/Term_Three/prog3/derived.cpp #include "derived.h" //constructors and destructors website::website() : link(NULL) {} website::~website() { if(link) delete [] link; link = NULL; } website::website(char priority, char* subject, char* link) : base(subject, priority) { this->link = new char[strlen(link) + 1]; strcpy(this->link, link); } website::website(const website& toCopy) : base(toCopy) { if(toCopy.link) { this->link = new char[strlen(toCopy.link) + 1]; strcpy(this->link, toCopy.link); } } //display functions displays all the data members and calls base class display function void website::display() { base::display(); cout << "Link: " << link << endl; } //writes the information of the object to file then calls base class writeToFile() void website::writeToFile() { ofstream out; out.open("prog3.txt", ios::app); if(out) { out << "w|" << link; base::writeToFile(out); } } //zoom class constructors and destructors zoom::zoom() : teacher(NULL), time(NULL), id(NULL) {} zoom::~zoom() { if(teacher) delete [] teacher; if(time) delete [] time; teacher = time = NULL; } zoom::zoom(char priority, char* subject, char* teacher, char* time, char* id) : base(subject, priority) { this->teacher = new char[strlen(teacher) + 1]; this->time = new char[strlen(time) + 1]; this->id = new char[strlen(id) + 1]; strcpy(this->teacher, teacher); strcpy(this->time, time); strcpy(this->id, id); } zoom::zoom(const zoom& toCopy) : base(toCopy), id(toCopy.id) { if(toCopy.teacher) { this->teacher = new char[strlen(toCopy.teacher) + 1]; strcpy(this->teacher, toCopy.teacher); } if(toCopy.time) { this->time = new char[strlen(toCopy.time) + 1]; strcpy(this->time, toCopy.time); } } //writes the information of the object to file then calls base class writeToFile() void zoom::writeToFile() { ofstream out; out.open("prog3.txt", ios::app); if(out) { out << "z|" << teacher << "|" << time << "|" << id; base::writeToFile(out); } } //display functions displays all the data members and calls base class display function void zoom::display() { base::display(); if(teacher && time) cout << "Teacher: " << teacher << endl << "Time: " << time << endl; } //book class construectors and destructors book::book() : pages(NULL), author(NULL), title(NULL) {} book::~book() { if(author) delete [] author; if(title) delete [] title; if(pages) delete [] pages; title = author = pages = NULL; } book::book(const book& toCopy) : base(toCopy) { if(toCopy.title) { this->title = new char[strlen(toCopy.title) + 1]; strcpy(this->title, toCopy.title); } if(toCopy.author) { this->author = new char[strlen(toCopy.author) + 1]; strcpy(this->author, toCopy.author); } if(toCopy.pages) { this->pages = new char[strlen(pages) + 1]; strcpy(this->pages, toCopy.pages); } } book::book(char priority, char* subject, char* pages, char* author, char* title) : base(subject, priority) { this->author = new char[strlen(author) + 1]; this->title = new char[strlen(title) + 1]; this->pages = new char[strlen(pages) + 1]; strcpy(this->author, author); strcpy(this->title, title); strcpy(this->pages, pages); } //writes the information of the object to file then calls base class writeToFile() void book::writeToFile() { ofstream out; out.open("prog3.txt", ios::app); if(out) { out << "b|" << pages << "|" << author << "|" << title; base::writeToFile(out); } } //display functions displays all the data members and calls base class display function void book::display() { base::display(); if(author && title) cout << "Author: " << author << endl << "Title: " << title << endl << "Length: " << pages << " pages" << endl; } <file_sep>/Term_Two/prog5_backup/main.cpp #include "header.h" bool again() { char input; cout << "Would you like to enter again? <y,n> " << endl; cin >> input; cin.ignore(100, '\n'); return input == 'y'; } int main() { char input; graph myGraph; myClass first; first.name = "cs161"; myClass second; second.name = "cs162"; myClass third; third.name = "cs163"; myClass fourth; fourth.name = "cs202"; myGraph.insertVertex(&first); myGraph.insertVertex(&second); myGraph.insertVertex(&third); myGraph.insertVertex(&fourth); myGraph.insertEdge("cs161", "cs162"); myGraph.insertEdge("cs161", "cs202"); myGraph.insertEdge("cs161", "cs163"); myGraph.traverse("cs161"); myGraph.test(0); /* do { cout << "=======================" << endl; cout << "1: Add a class" << endl; cout << "2: Add a pre-req to this class" << endl; cout << "3: View what courses you can take after a current one" << endl; }while(again()); */ return 0; } <file_sep>/Term_Three/prog3/tree.h #include "derived.h" /* * this is oujr data structure, a tree of nodes, with each node holding an object * */ class node { public: //cosntrucotr and destructor node(); ~node(); node(const node& toCopy); //adding objects to the node usign copy constructor void addBook(book& toAdd); void addWeb(website& toAdd); void addZoom(zoom& toAdd); void addNode(node& toAdd, node* root); //add node to tree //to go left and rigtht in the tree node*& goLeft(){ return left; } node*& goRight(){ return right; } char getPriority(); //returns the priority of the specified object void display(); //displays node private: char id; //how we know which node holds what type of object 0 = book, 1 = website, 2 = zoom node* left; node* right; book* myBook; website* myWeb; zoom* myZoom; }; class tree { public: tree(); ~tree(); //constructor void addNode(node& toAdd); //add node to tree void display(); //display contents fo the tree void getFromFile(); //get information from the file private: node* root; //root node void addNode(node& toAdd, node*& root); //private recursive wrappers void display(node* root); void writeToFile(); }; <file_sep>/Term_One/prog_4/prog4.h #include <iostream> #include <fstream> using namespace std; class Question { public: Question(); // ~Question(); void initQuestion(); void write(); void display(); private: char* subject; char* body; char* date; }; class List { public: List(int length); //~List(); void read(); int lines; private: Question* fileList; Question* question; }; <file_sep>/Term_Three/prog1/title.h #include <iostream> #include <cstring> #include <cctype> using namespace std; class title { public: //copy constructor and defauly, as well as descturcot title(char* name, char* date); title(const title & title); title(); ~title(); //display function void display(); //get/setters void changeTitle(char* name, char* date); void changeTitle(const title & toChange); void setTitleName(char* name); void setTitleDate(char* date); protected: char* name; //name of title char* date; //date of title }; class video : public title //video is a title so it conatins its member functions { public: //constructors and destructor video(); ~video(); video(char* name, char* date, char* description, double length); video(const video & toCopy); //display function void display(); //functions to change members of the class void changeVideo(double length, char* description); void changeVideo(const video & toChange); protected: char* description; //description of video double length; //length of video }; class liveStream : public video { public: //construcotrs and desturcots liveStream(); ~liveStream(); liveStream(char* name, char* date, char* description, double length, char* instructor, char* topic); liveStream(const liveStream & toCopy); //change stream and display fucntions void changeStream(const liveStream & toChange); void display(); protected: char* instructor; //instructor teaching the liveStream char* topic; //topic of the liveStream }; <file_sep>/Term_Two/Prog2/header.h #include <iostream> #include <cctype> #include <cstring> using namespace std; struct trip_section { trip_section(); ~trip_section(); bool set_trip(char* name, char* traffic, char* notes, char* landmarks, int length); char* name; char* traffic; char* notes; char* landmarks; int length; trip_section* next; }; struct node { ~node(); node* next; trip_section* stack; }; class return_trip { private: int top_index; const int MAX = 5; node* head; public: return_trip(); ~return_trip(); bool push(trip_section* node); bool pop(); trip_section* peek(); bool display(); }; class travel { private: trip_section* rear; public: travel(); ~travel(); bool copy(trip_section* trip, trip_section* to_copy); bool enqueue(trip_section* trip_section); bool dequeue(); trip_section* peek(); bool display(); }; <file_sep>/Term_One/prog5/prog5.h #include <iostream> #include <cstring> #include <fstream> using namespace std; struct node { char* name; char* description; char* complete; int* priority; node* next; ~node(); }; class List { public: List(); ~List(); node* getHead(); //void initFile(); //bool writeToFile(); bool add(); bool remove(char search[]); void display(); void displayPriority(int priority, node* search); int length(); //bool test(); private: node* head; }; <file_sep>/Term_Three/prog1/email.cpp #include "email.h" //============================Email constructos and functions ======================= // //defualt constructor email::email() : title(), subject(NULL), body(NULL), recipiant(NULL) {} //copy constructor, calls title copy constructor as well email::email(const email & toCopy) : title(toCopy), timeSent(toCopy.timeSent) { this->subject = new char[strlen(toCopy.subject) + 1]; this->body = new char[strlen(toCopy.body) + 1]; this->recipiant = new char[strlen(toCopy.recipiant) + 1]; strcpy(this->subject, toCopy.subject); strcpy(this->body, toCopy.body); strcpy(this->recipiant, toCopy.recipiant); } //constructor when given information email::email(char* name, char* date, char* subject, char* body, char* recipiant, double timeSent) : title(name, date), timeSent(timeSent) { this->subject = new char[strlen(subject) + 1]; this->body = new char[strlen(body) + 1]; this->recipiant = new char[strlen(recipiant) + 1]; strcpy(this->subject, subject); strcpy(this->body, body); strcpy(this->recipiant, recipiant); } //email destructor email::~email() { delete [] subject; delete [] body; delete [] recipiant; subject = body = recipiant = NULL; } //diaply function to cout all the information void email::display() { title::display(); cout << "Recipiant: " << recipiant << endl << "Time sent: " << timeSent << endl << "Subject: " << subject << endl << "Body: " << body << endl; } //===============Essay constructors and functions================= //default constructor for the essay class essay::essay() : title(), body(NULL), dueDate(NULL), wordLength(0) { } //constructor when given information essay::essay(char* name, char* date, char* body, char* dueDate, int wordLength) : title(name, date), wordLength(wordLength) { this->body = new char[strlen(body) + 1]; this->dueDate = new char[strlen(dueDate) + 1]; strcpy(this->body, body); strcpy(this->dueDate, dueDate); } //copy constructor essay::essay(const essay & toCopy) : title(toCopy.name, toCopy.date), wordLength(toCopy.wordLength) { body = new char[strlen(toCopy.body) + 1]; dueDate = new char[strlen(toCopy.dueDate) + 1]; strcpy(body, toCopy.body); strcpy(dueDate, toCopy.dueDate); } //essay class destructor essay::~essay() { delete [] body; delete [] dueDate; body = dueDate = NULL; } //essay display fucntion void essay::display() { title::display(); cout << "Due date: " << dueDate << endl << "Length: " << wordLength << " words" << endl << "Body: " << body << endl; } <file_sep>/Term_Two/Prog4_Backup/main.cpp #include "header.h" bool again() { char input; cout << "Again? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') return true; return false; } int main() { tree BST; meal myMeal; char name[100]; char review[100]; char storeName[100]; int rating; int price; bool type; while(again()) { cout << "Name: " << endl; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << "Store: " << endl; cin.get(review, 100, '\n'); cin.ignore(100, '\n'); cout << "Review: " << endl; cin.get(storeName, 100, '\n'); cin.ignore(100, '\n'); cout << "Rating: " << endl; cin >> rating; cin.ignore(100, '\n'); cout << "Price: " << endl; cin >> price; cin.ignore(100, '\n'); bool type = true; myMeal.name = name; myMeal.review = review; myMeal.storeName = storeName; myMeal.rating = rating; myMeal.price = price; myMeal.type = type; BST.add(&myMeal); } BST.display(); BST.displayMatch("meal"); return 0; } <file_sep>/Term_Two/Prog2/class.cpp #include "header.h" //=======================struct stuff=============================== node::~node() { delete [] stack; next = NULL; } trip_section::trip_section() { next = NULL; name = NULL; traffic = NULL; notes = NULL; landmarks = NULL; length = 0; } trip_section::~trip_section() { delete [] name; delete [] traffic; delete [] notes; delete [] landmarks; next = NULL; } bool trip_section::set_trip(char* nameAdd, char* trafficAdd, char* notesAdd, char* landmarksAdd, int lengthAdd) { if(this->name != NULL) { delete [] name; delete [] traffic; delete [] notes; delete [] landmarks; name = NULL; traffic = NULL; notes = NULL; landmarks = NULL; } name = new char[strlen(nameAdd) + 1]; traffic = new char[strlen(trafficAdd) + 1]; notes = new char[strlen(notesAdd) + 1]; landmarks = new char[strlen(landmarksAdd) + 1]; strcpy(name, nameAdd); strcpy(traffic, trafficAdd); strcpy(notes, notesAdd); strcpy(landmarks, landmarksAdd); length = lengthAdd; return true; } //===========================End of struct stuff========================= //===================================circular linked list stuff========================== travel::travel() { rear = NULL; } travel::~travel() { trip_section* cur; trip_section* prev; if(rear) { if(rear->next == rear) { rear->next = NULL; delete rear; } else { cur = rear->next; rear->next = NULL; while(cur->next != NULL) { prev = cur; cur = cur->next; prev->next = NULL; delete prev; } rear->next = NULL; delete rear; } } } bool travel::display() { trip_section* temp; if(!rear) return NULL; else { temp = rear; do { temp = temp->next; cout << "Name: " << temp->name << endl; }while(temp != rear); return true; } return false; } trip_section* travel::peek() { if(!rear) return NULL; else return rear->next; return NULL; } bool travel::dequeue() { trip_section* cur; if(!rear) return false; else { if(rear->next == rear) { delete rear; rear = NULL; return true; } else { for(cur = rear->next; cur->next != rear; cur = cur->next); cur->next = rear->next; delete rear; rear = cur; return true; } } return false; } bool travel::enqueue(trip_section* trip) { trip_section* temp; if(rear == NULL) { rear = new trip_section; rear->next = rear; rear->name = new char[strlen(trip->name) + 1]; rear->traffic = new char[strlen(trip->traffic) + 1]; rear->notes = new char[strlen(trip->notes) + 1]; rear->landmarks = new char[strlen(trip->landmarks) + 1]; strcpy(rear->name, trip->name); strcpy(rear->traffic, trip->traffic); strcpy(rear->notes, trip->notes); strcpy(rear->landmarks, trip->landmarks); rear->length = trip->length; return true; } else { temp = rear->next; rear->next = new trip_section; rear = rear->next; rear->next = temp; rear->name = new char[strlen(trip->name) + 1]; rear->traffic = new char[strlen(trip->traffic) + 1]; rear->notes = new char[strlen(trip->notes) + 1]; rear->landmarks = new char[strlen(trip->landmarks) + 1]; strcpy(rear->name, trip->name); strcpy(rear->traffic, trip->traffic); strcpy(rear->notes, trip->notes); strcpy(rear->landmarks, trip->landmarks); rear->length = trip->length; return true; } return false; } //=========================================End of circular linked list stuff============================ //=======================================Start of stack stuff========================================= return_trip::return_trip() { top_index = 0; head = NULL; } return_trip::~return_trip() { node* temp; if(head) { if(head->next == NULL) { delete head; head = NULL; } else { while(head->next != NULL) { temp = head; head = head->next; delete [] temp->stack; temp->next = NULL; } } } } bool return_trip::display() { int temp_index = top_index; node* cur; if(!head) return false; else { for(cur = head; cur != NULL; cur = cur->next) { while(temp_index != 0) { --temp_index; cout << cur->stack[temp_index].name << endl; } temp_index = MAX; } return true; } return false; } trip_section* return_trip::peek() { if(!head) return NULL; else return &head->stack[top_index-1]; } bool return_trip::pop() { node* temp; if(!head) return false; else { if(head->next == NULL && top_index == 0) { top_index = 0; delete head; head = NULL; return true; } else if(top_index == 1) { top_index = MAX; temp = head; head = head->next; delete temp; return true; } else { --top_index; return true; } } return false; } bool return_trip::push(trip_section* trip) { node* temp; if(!head) { head = new node; head->next = NULL; head->stack = new trip_section[MAX]; head->stack[top_index].name = new char[strlen(trip->name) + 1]; head->stack[top_index].traffic = new char[strlen(trip->traffic) + 1]; head->stack[top_index].notes = new char[strlen(trip->notes) + 1]; head->stack[top_index].landmarks = new char[strlen(trip->landmarks) + 1]; strcpy(head->stack[top_index].name, trip->name); strcpy(head->stack[top_index].traffic, trip->traffic); strcpy(head->stack[top_index].notes, trip->notes); strcpy(head->stack[top_index].landmarks, trip->landmarks); head->stack[top_index].length = trip->length; ++top_index; return true; } else { if(top_index >= MAX) { top_index = 0; temp = head; head = new node; head->next = temp; head->stack = new trip_section[MAX]; head->stack[top_index].name = new char[strlen(trip->name) + 1]; head->stack[top_index].traffic = new char[strlen(trip->traffic) + 1]; head->stack[top_index].notes = new char[strlen(trip->notes) + 1]; head->stack[top_index].landmarks = new char[strlen(trip->landmarks) + 1]; strcpy(head->stack[top_index].name, trip->name); strcpy(head->stack[top_index].traffic, trip->traffic); strcpy(head->stack[top_index].notes, trip->notes); strcpy(head->stack[top_index].landmarks, trip->landmarks); head->stack[top_index].length = trip->length; delete temp; ++top_index; return true; } else { head->stack[top_index].name = new char[strlen(trip->name) + 1]; head->stack[top_index].traffic = new char[strlen(trip->traffic) + 1]; head->stack[top_index].notes = new char[strlen(trip->notes) + 1]; head->stack[top_index].landmarks = new char[strlen(trip->landmarks) + 1]; strcpy(head->stack[top_index].name, trip->name); strcpy(head->stack[top_index].traffic, trip->traffic); strcpy(head->stack[top_index].notes, trip->notes); strcpy(head->stack[top_index].landmarks, trip->landmarks); head->stack[top_index].length = trip->length; delete temp; ++top_index; return true; } } return false; } //===============================================End of stack stuff===================================== <file_sep>/Term_One/prog4_backup/prog4/prog4.cpp #include "prog4.h" //Question contructor, initializes all arrays to \0 Question::Question() { subject[0] = '\0'; questionBody[0] = '\0'; date[0] = '\0'; } //Compares and displays question if the date, or subject is equal to input void Question::compare(char word[]) { if(strcmp(word,date) == 0 || strcmp(word, subject) == 0 || strcmp(word, "all") == 0) display(); } //-----------This method uses user input to initilaize a question------------ void Question::initQuestion() { cout << "Enter date please dd/mm/yyyy: "; cin.get(date, 11, '\n'); cin.ignore(1000, '\n'); cout << "Subject: "; cin.get(subject, 21, '\n'); cin.ignore(1000, '\n'); cout << "Please enter the question itself:\n"; cin.get(questionBody, 140, '\n'); cin.ignore(1000, '\n'); } //----------------This method is specifically for when we are getting questions from the file----------- void Question::initQuestion(char Date[], char Subject[], char Body[]) { strcpy(date, Date); strcpy(subject, Subject); strcpy(questionBody, Body); } //--------Displays date, subject, and quesion------------ void Question::display() { cout << "\nDate: " << date << "\nSubject: " << subject << "\nQuestion: " << questionBody << endl; } //--------Writes question to file in order date | subject | questionBody |\n void Question::writeToFile() { ofstream out; out.open("question.txt", ios::app); if(out) { out << date << "|" << subject << "|" << questionBody << "|\n"; } else cerr << "Could not open or write to file..." << endl; } //---------Accesses question at sepcific index in the lis and runs the writeToFile method on it-------- void List::write(int index) { list[index].writeToFile(); } //Compares questions in both the regular list and fileList void List::compare(char word[]) { for(int i = 0; i < arrayLength; ++i) list[i].compare(word); for(int i = 0; i < fileLength; ++i) fileList[i].compare(word); } //---------Initializes the list, with a set length for how many questions the user wants to input--- List::List(int length) { list = new Question[length]; fileList = NULL; arrayLength = length; fileLength = 0; } //List destructor List::~List() { delete [] list; delete [] fileList; arrayLength = 0; fileLength = 0; } //--------This initializes the list of questions to be put in by the user------------ void List::initList() { int length; cout << "How many questions would you like to enter?" << endl; cin >> length; cin.ignore(100, '\n'); list = new Question[length]; } //------------This initiliazes the list of the questions from the file, should they choose to--------- void List::initFileList() { ifstream in; in.open("question.txt"); if(in) in.peek(); else cerr << "Couldn't open file..." << endl; while(!in.eof()) { char line[300]; in.get(line, 300, '\n'); in.ignore(300, '\n'); if(line[0] != '\0') ++fileLength; } // cout << fileLength << " lines in the file..." << endl; fileList = new Question[fileLength]; in.close(); in.open("question.txt"); for(int i = 0; i < fileLength; ++i) { char date[11]; char subject[21]; char body[140]; in.get(date, 11, '|'); in.ignore(100, '|'); in.get(subject, 21, '|'); in.ignore(100, '|'); in.get(body, 140, '|'); in.ignore(200, '\n'); fileList[i].initQuestion(date, subject, body); } } //-----Initializes the question at whatever index you want, runs initQuestion on the question object.... void List::initQuestion(int index) { list[index].initQuestion(); } <file_sep>/Term_Three/prog1/node.h #include "email.h" class node { public: //node constructors and destrucot node(); ~node(); node(const node & toAdd); //copy constructos //functions to add learning classes to our memebers void addVideo(video& toAdd); void addStream(liveStream& toAdd); void addEmail(email& toAdd); void addEssay(essay& toAdd); //display the contents of a node bool displayNode(); //these are used to recursivly add to the end a linked list of nodes //returns the next pointer node *& returnNext(); node *& goNext(); //recursivly adds to the end of a linear linked list of nodes void addToEnd(node* source, node *& head); int getType(); //returns the type in integer // this is going to be used for our table in order to add // nodes correctly to the array protected: //our members //each node will only contain one of these, and when we are //done using said node //in main, we will destroy the node video* myVideo; liveStream* myStream; email* myEmail; essay* myEssay; //next pointer for the linear linked list node* next; //each node has a type, the type tells us which one of the objects above it //contains int type; //for types: //0 = video //1 = livestream //2 = email //3 = essay }; class table { public: //constructor and destructor table(); ~table(); //addd a node to the array of nodes bool addNode(node* toAdd); //displays the contents of the entire array void displayAll(); //displays all of a certain type of object //making use of the getType() function in the node class void displayVid(); void displayEmails(); void displayEssays(); void displayStreams(); protected: node** nodeTable; //array of node pointers, this is //what contains the linear linked list; // int size; //size of the array, I set mine to 4 since we are only using //four different objects }; <file_sep>/Term_Three/prog2/base.h #include <iostream> #include <cctype> #include <cstring> using namespace std; class base { public: base(); ~base(); //constructors and destructors base(int actLength, int priority, bool group, char* name, char* location); base(const base& toCopy); virtual void display() = 0; //virtual functions virtual char* getName() { return name; } //returns the name for easier strcmp int getPriority(); //returns the priority private: int activityLength; //lenght of the activity in hours` int priority; //priority of the activity from one to ten, one being you want to do it immediatly bool group; //true = is a group activity false = not a group activity char* name; //name of the activity char* location; //location of the acticity }; <file_sep>/Term_Two/Prog4_Backup/header.h #include <iostream> #include <cstring> #include <cctype> using namespace std; struct meal { char* name; char* storeName; char* review; int price; int rating; bool type; void display(void); void copy(meal* to_add); }; struct node { meal myMeal; node* left; node* right; }; class tree { public: tree(); //~tree(); int display(node* root); int display(); int displayMatch(char* mealName); int displayMatch(char*mealName, node* root); bool add(meal* toAdd); bool add(meal* toAdd, node*& root); bool remove(node* toRemove); bool remove(node* toRemove, node*& root); bool search(char* name); private: node* root; }; <file_sep>/Term_Three/prog2/derived.cpp #include "derived.h" //Swim class constructors and destructor swim::swim() : swimSuit(NULL), member(false), hasHotTub(NULL), exercise(false) {} //copy constructor swim::swim(const swim& toCopy) : base(toCopy), member(toCopy.member), hasHotTub(toCopy.hasHotTub), exercise(toCopy.exercise) { if(toCopy.swimSuit) { cout << "Copying swimsuit string: " << toCopy.swimSuit << endl; swimSuit = new char[strlen(toCopy.swimSuit) + 1]; strcpy(this->swimSuit, toCopy.swimSuit); } } //constructor when given all the members as arguments swim::swim(int length, int priority, bool group, char* name, char* location, char* swimSuit, bool member, bool hasHotTub) : base(length, priority, group, name, location), member(member), hasHotTub(hasHotTub), exercise(false) { this->swimSuit = new char[strlen(swimSuit) + 1]; strcpy(this->swimSuit, swimSuit); } //swim class destructor deleting only dynamically allocated array swim::~swim() { delete [] this->swimSuit; this->swimSuit = NULL; } //swim class functions void swim::display() { base::display(); cout << "Swimsuit: " << swimSuit << endl; if(hasHotTub) cout << "Has a hot tub" << endl; else cout << "Does not have a hot tub" << endl; if(member) cout << "Requires membership" << endl; else cout << "Does not require membership" << endl; if(exercise) cout << "You plan to exercise on this trip" << endl; else cout << "You do not plan to exercise on this trip" << endl; } //prompts the user if the want to plan an exercise on this trip void swim::startExercise() { char input; cout << "Would you like to exercise on this trip? <y,n>: " << endl; cin >> input; cin.ignore(100, '\n'); if(input == 'y') exercise = true; else exercise = false; cout << "You can change this at any time" << endl; } //hike class constructors and destructor hike::hike() : overNight(false), season(NULL), weather(NULL), climbShoes(false) {} //hike copy constructor hike::hike(const hike & toCopy) : base(toCopy), overNight(toCopy.overNight), climbShoes(toCopy.climbShoes) { if(toCopy.season && toCopy.weather) { this->season = new char[strlen(toCopy.season) + 1]; this->weather = new char[strlen(toCopy.weather) + 1]; strcpy(this->season, toCopy.season); strcpy(this->weather, toCopy.weather); } } //hike constructor when given all members as, arguments hike::hike(int length, int priority, bool group, char* name, char* location, bool overNight, char* season, char* weather) : base(length, priority, group, name, location), overNight(overNight), climbShoes(false) { this->season = new char[strlen(season) + 1]; this->weather = new char[strlen(weather) + 1]; strcpy(this->season, season); strcpy(this->weather, weather); } //hike destrucotr deleting all dynamically allocated memory hike::~hike() { delete [] this->season; delete [] this->weather; this->season = NULL; this->weather = NULL; } //hike class functions //displayu funtiuons void hike::display() { base::display(); if(overNight) cout << "Overnight" << endl; else cout << "Day hike" << endl; cout << "Season: " << season << endl << "Weather: " << weather << endl; } //prompts the user if they want to pack rock climbing shoes bool hike::rockClimb() { char input; if(climbShoes) cout << "You have packed climbing shoes" << endl; else { cout << "YOu have not packed climbing shoes, would you like to? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') climbShoes = true; } } //work class constructors and destructor work::work() : position(NULL), pay(-1), partTime(false), lunch(NULL) {} //work class constructor when given the information as arguments work::work(int length, int priority, bool group, char* name, char* location, char* position, int pay, bool partTime) : base(length, priority, group, name, location), pay(pay), partTime(partTime), lunch(NULL) { this->position = new char[strlen(position) + 1]; strcpy(this->position, position); } //work class copy constructor work::work(const work& toCopy) : base(toCopy), pay(toCopy.pay), partTime(toCopy.partTime) { if(toCopy.position) { this->position = new char[strlen(toCopy.position) + 1]; strcpy(this->position, toCopy.position); } if(toCopy.lunch) { this->lunch = new char[strlen(toCopy.lunch) + 1]; strcpy(this->lunch, toCopy.lunch); } } //work class destructor work::~work() { delete [] this->position; this->position = NULL; } //work class functions //usual display fucntion void work::display() { base::display(); cout << "Position: " << position << endl << "Pay: " << pay << endl; if(partTime) cout << "Part time job" << endl; else cout << "Full time job" << endl; if(lunch == NULL) cout << "No lunch planned" << endl; else cout << "Lunch: " << lunch << endl; } //prompts the user for which type of lunch they would like to pack void work::planLunch() { char input; char lunch[30]; cout << endl << "Would you like to pack a lunch? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') { cout << "What would you like to pack: "; cin.get(lunch, 100, '\n'); cin.ignore(100, '\n'); cout << endl; if(this->lunch) { delete this->lunch; this->lunch = new char[strlen(lunch) + 1]; strcpy(this->lunch, lunch); } else { this->lunch = new char[strlen(lunch) + 1]; strcpy(this->lunch, lunch); } } } <file_sep>/Term_One/Prog_Two/CommonPhrase.cpp /* code by <NAME> * written for cs162 programming assignment number 2 * goal is to get common phrases from user and a signature * the user then can decide what order they want the phrases output in * ended with the users signature * started writing 10/21/2019 at psu library * my name a jeff */ #include <iostream> #include <cstring> #include <cctype> using namespace std; const int MAX_SIZE = 130; // ------------Functions-------------------- void phraseCondition(char phrase[]); // this checks and makes sure the phrases have the correct conditions void capSignature(char signature[]); // this makes sure the signature is capitalized int main() { // -----------Variables------------------- const int MAX_LENGTH = 130; // Max size of the arrays char phraseOne[MAX_LENGTH], phraseTwo[MAX_LENGTH], phraseThree[MAX_LENGTH], phraseFour[MAX_LENGTH], signature[MAX_LENGTH];// all of arr character arrays set to max length char exitInput;// when the user wants to stop entering phrases int numOfPhrases = 0; // total number of phrases the user has input int order[4]; // keeps the order of phrases bool exit = false, finalExit = false; // our exit conditions for bot while loops int phraseCount = 1; // number phrases for the switch statemenit cout << "Hi, the purpose of this program is to make life easier for you." << endl; cout << "Lets start by getting your signature please: " << endl; cin.get(signature, MAX_LENGTH, '\n'); cin.ignore(150, '\n'); //checking signature and making sure its lookin good capSignature(signature); cout << "Hello " << signature << " nice to meet you!" << endl; //iterating through each of the phrases while(!finalExit){ while(!exit) { cout << "Please enter phrase number " << phraseCount << endl; switch(phraseCount) { case 1: cin.get(phraseOne, MAX_LENGTH, '\n'); cin.ignore(100, '\n'); phraseCondition(phraseOne); ++numOfPhrases; break; case 2: cin.get(phraseTwo, MAX_LENGTH, '\n'); cin.ignore(1000, '\n'); phraseCondition(phraseTwo); ++numOfPhrases; break; case 3: cin.get(phraseThree, MAX_LENGTH, '\n'); cin.ignore(1000, '\n'); phraseCondition(phraseThree); ++numOfPhrases; break; case 4: cin.get(phraseFour, MAX_LENGTH, '\n'); cin.ignore(1000, '\n'); phraseCondition(phraseFour); ++numOfPhrases; break; } if(phraseCount < 4) { cout << "Would you like to enter another? <y/n>: " << endl; cin >> exitInput; cin.ignore(100, '\n'); } //our exit condition if(phraseCount == 4 || exitInput == 'n') { exit = true; phraseCount = 0; } ++phraseCount; } cout << "What order would you like your phrases in? " << endl << "Please enter numbers one at a time, followed by a return: " << endl; for(int i = 0; i < numOfPhrases; ++i) { cin >> order[i]; cin.ignore(100, '\n'); } for(int i = 0; i < numOfPhrases; ++i) switch(order[i]) { case 1: cout << phraseOne << " "; break; case 2: cout << phraseTwo << " "; break; case 3: cout << phraseThree << " "; break; case 4: cout << phraseFour << " "; break; default: break; } cout << "\n\nFrom " << signature << endl; // Adding signature to end of phrase combination. cout << "\n\nWould you like to run this program again? <y/n>:" << endl; cin >> exitInput; cin.ignore(100,'\n'); if(exitInput == 'n') { finalExit = true; } exit = false; // setting exit condition back so user can run program again numOfPhrases = 0; } // ------------End Program------------ cout << "\n\nThank you for using this program!"; return 0; } // function that checks the phrase and makes sure it's valid. Also capitalizes the first character void phraseCondition(char phrase[]) { int size = strlen(phrase); //checking that last character of phrase ends in . ! or ? while(phrase[size-1] != '.' && phrase[size-1] != '!' && phrase[size-1] != '\?') { cout << "Your phrase doesn't end in a valid character, please try again." << endl; cin.get(phrase, 130, '\n'); cin.ignore(100, '\n'); size = strlen(phrase); //resetting size of array to new string } //remove double spaces and capitalize first letter for(int i = 0; i < size; ++i) { phrase[0] = toupper(phrase[0]); if(isspace(phrase[i]) && isspace(phrase[i+1])) for(int j = i+1; j < MAX_SIZE; ++j) phrase[j] = phrase[j+1]; } } // this function just capitalizes our users signature void capSignature(char signature[]) { int size = strlen(signature); // remove any extra white space and capitalize letters after white space for(int i = 0; i < size; ++i) { if(isspace(signature[i]) && isspace(signature[i+1])) { for(int j = i+1; j < size; ++j) signature[j] = signature[j+1]; } if(isspace(signature[i]) && isalpha(signature[i+1])) signature[i+1] = toupper(signature[i+1]); } //capitalize first letter signature[0] = toupper(signature[0]); } <file_sep>/Term_One/prog5/prog5.cpp #include "prog5.h" //node destructor, recursive node::~node() { delete []name; delete []description; delete []complete; delete priority; delete next; name = NULL; description = NULL; complete = NULL; priority = NULL; } //List constructor, pretty straight forward List::List() { head = NULL; } //list destroctor, calls on head only since node //destrutor is recursive List::~List() { delete head; } //Counts how many nodes are in the LLL int List::length() { int length = 0; node* cur = head; node* prev; if(head == NULL) return 0; else if(head->next == NULL) return 1; else { while(cur->next != NULL) { prev = cur; cur = cur->next; ++length; } } return length+1; } //displays each node in the LLL void List::display() { node* cur; if(head == NULL) cerr << "No List..." << endl; for(cur = head; cur != NULL; cur = cur->next) { cout << "Name: " << cur->name <<"\nDecription: " << cur->description <<"\nDate to be completed by: " << cur->complete << "\nPriority: " << *(cur->priority) << endl; } } //Gets the head node, this is used for a recursive function of searching node* List::getHead() { if(head == NULL) { return NULL; cerr << "Empty List..." << endl; } return head; } //recursivley searches for node with specific priority //using the getHead() method void List::displayPriority(int intSearch, node* search) { if(search->next != NULL) displayPriority(intSearch, search->next); if(*(search->priority) == intSearch) { cout << "Name: " << search->name << "\nDescription: " << search->description << "\nPriority: " << search->priority << "\nDate to be completed: " << search->complete << endl; } } //removes node with desired name... //returns true if succesfully deleted a node //false otherwise bool List::remove(char search[]) { node* cur = head; node* prev; if(head == NULL) { cerr << "Empty List..." << endl; return false; } if(head->next == NULL && strcmp(head->name, search) == 0) { delete [] head->name; delete [] head->description; delete [] head->complete; delete head->priority; head = NULL; cout << "Your list is now empty..." << endl; return true; } else { while(cur->next != NULL) { prev = cur; cur = cur->next; if(strcmp(cur->name, search) == 0) { prev->next = cur->next; delete [] cur->name; delete [] cur->description; delete [] cur->complete; delete cur->priority; return true; } } } cout << "Nothing matches criteria for deletion..." << endl; return false; } //This adds a node, but it does it so that all the nodes are sorted in order based //off name, this was hell bool List::add() { char tempName[200]; char tempDescription[200]; char tempComplete[100]; int tempPriority; cout << "Name of item: "; cin.get(tempName, 200, '\n'); cin.ignore(200, '\n'); cout << "\nDescription of the task: "; cin.get(tempDescription, 200, '\n'); cin.ignore(200, '\n'); cout << "\nDate you want this task completed by: "; cin.get(tempComplete, 100, '\n'); cin.ignore(100, '\n'); cout << "\nPriority <0-10>: "; cin >> tempPriority; cin.ignore(100, '\n'); if(head == NULL) { head = new node; head->name = new char[strlen(tempName)+1]; head->description = new char[strlen(tempDescription)+1]; head->complete = new char[strlen(tempComplete)+1]; head->priority = new int; strcpy(head->name, tempName); strcpy(head->description, tempDescription); strcpy(head->complete, tempComplete); *(head->priority) = tempPriority; head->next = NULL; return true; } else { node* cur; node* prev; if(head != NULL && head->next == NULL) { if(strcmp(tempName, head->name) >= 0) { head->next = new node; cur = head->next; cur->next = NULL; cur->name = new char[strlen(tempName)+1]; cur->description = new char[strlen(tempDescription)+1]; cur->complete = new char[strlen(tempComplete)+1]; cur->priority = new int; strcpy(cur->name, tempName); strcpy(cur->description, tempDescription); strcpy(cur->complete, tempComplete); *(cur->priority) = tempPriority; return true; } else { head->next = new node; cur = head; head = head->next; head->next = cur; cur->next = NULL; head->name = new char[strlen(tempName)+1]; head->description = new char[strlen(tempDescription)+1]; head->complete = new char[strlen(tempComplete)+1]; head->priority = new int; strcpy(head->name, tempName); strcpy(head->description, tempDescription); strcpy(head->complete, tempComplete); *(head->priority) = tempPriority; return true; } } cur = head; while(cur->next != NULL) { prev = cur; cur = cur->next; if(strcmp(tempName, prev->name) >= 0 && strcmp(tempName, cur->name) <= 0) { prev->next = new node; prev = prev->next; prev->next = cur; prev->name = new char[strlen(tempName)+1]; prev->description = new char[strlen(tempDescription)+1]; prev->complete = new char[strlen(tempComplete)+1]; prev->priority = new int; strcpy(prev->name, tempName); strcpy(prev->description, tempDescription); strcpy(prev->complete, tempComplete); *(prev->priority) = tempPriority; return true; } else if(strcmp(tempName, prev->name) <= 0 && prev == head) { head = new node; head->next = prev; head->name = new char[strlen(tempName)+1]; head->description = new char[strlen(tempDescription)+1]; head->complete = new char[strlen(tempComplete)+1]; head->priority = new int; strcpy(head->name, tempName); strcpy(head->description, tempDescription); strcpy(head->complete, tempComplete); *(head->priority) = tempPriority; return true; } if(cur->next == NULL && strcmp(tempName, cur->name) >= 0) { cur->next = new node; cur = cur->next; cur->next = NULL; cur->name = new char[strlen(tempName)+1]; cur->description = new char[strlen(tempDescription)+1]; cur->complete = new char[strlen(tempComplete)+1]; cur->priority = new int; strcpy(cur->name, tempName); strcpy(cur->description, tempDescription); strcpy(cur->complete, tempComplete); *(cur->priority) = tempPriority; return true; } } } } /* * didnt have time to finish this bool List::writeToFile(node* node) { ostream out; out.open("ToDo.txt", ios::app); if(!out) cerr << "\n\nCould not write to file\n\n"; else { out << node->name << "|" << node->description << "|" << node->priority << "|" << node->complete << "|\n"; } } void List::initFile() { istream in; in.open("ToDo.txt"); if(!in.peek()) cerr << "\n\nCould not read from file... \n\n"; else { in } } */ <file_sep>/Term_Three/prog3/base.cpp #include "base.h" //constructors and destructors base::base() : subject(NULL) { } base::~base() { if(subject) delete [] subject; subject = NULL; } base::base(const base& toCopy) : priority(toCopy.priority) { this->subject = new char[strlen(toCopy.subject) + 1]; strcpy(this->subject, toCopy.subject); } base::base(char* subject, char priority) : priority(priority) { this->subject = new char[strlen(subject) + 1]; strcpy(this->subject, subject); } //displays information in the base class void base::display() { if(subject) cout << "Subject: " << subject << endl; cout << "Priority: " << priority << endl; } //writes to the given ofstream file void base::writeToFile(ofstream& out) { if(out) { out << "|" << subject << "|" << priority << "|\n"; } else cerr << "Couldnt write to file" << endl; } <file_sep>/Term_One/Prog_Three/prog3.cpp /* Code by <NAME>...assignment number 3 for CS162 * purpose of this program is toask the user to input questions they want to store later to practice * this mainly uses structures and functions to display the structures, creating them locally from the text file */ #include <iostream> #include <cctype> #include <cstring> #include <fstream> using namespace std; //------------Constants----------- const int SUBSIZE = 21; // size for array of characters thta holds subject, e.g., loops, arrays, structs const int QUESTSIZE = 140; // Constant for size of question //--------Structs------ struct Question{ char subject[SUBSIZE]; // this is the subject of our question, loops, stucts, files, etc... char questionText[QUESTSIZE];// this is the acutal question itself char date[11]; //dates are usually a set size already.. }; //------Prototypes-------- //functions explained where they are written //prototypes are pretty stright forward void writeToFile(Question & question); void createStruct(Question &list); void displayQuestion(char subject[]); void getQuestionStruct(char subject[]); void displayStruct(Question & question); void displayStructQuestion(Question & question);//for testing only... //--------Fuctions--------- int main() { int numOfQuestions;//numbers of questions the user wants to input, required for our for loop Question list[numOfQuestions];//our array of questions, bool endProg = true; //------Getting how many questions the user wants to enter------- cout << "How many questions would your like to input?" << endl; cin >> numOfQuestions; cin.ignore(100, '\n'); while(numOfQuestions > 10) { cout << "Please put in a number that is 10 or less..." << endl; cin >> numOfQuestions; cin.ignore(100, '\n'); } for(int i = 1; i <= numOfQuestions; ++i) { cout << "Creating problem " << i << endl; createStruct(list[i]); writeToFile(list[i]); } //--------------------------------------------------------------- //--------This is the loop where the user is asked what questions they want to see--- while(endProg) { cout << "Which questions do you want to see? \nEnter a date, subject, or \"all\"" << endl; char subject[30]; cin.get(subject, 30, '\n'); getQuestionStruct(subject); cout << "Do you want to see more questions? <y/n>" << endl; char input; cin >> input; cin.ignore(100, '\n'); if(input == 'n') endProg = false; } cout << "Thanks for using the program!" << endl; return 0; } //this function is called in our for loop and edits the desired struct at the current index void createStruct(Question & list) { cout << "What is the subject: "; cin.get(list.subject, SUBSIZE, '\n'); cin.ignore(100, '\n'); cout << "What is the date you are writing this: "; cin.get(list.date, 11, '\n'); cin.ignore(100,'\n'); cout << "Please enter the question now: " << endl; cin.get(list.questionText, QUESTSIZE, '\n'); cin.ignore(QUESTSIZE, '\n'); } //This displays the quetion by passing in the current struct that contains a question void displayStruct(Question & question) { if(question.date[0] != '\0') { //cout << strlen(question.date) << endl; cout << "\nDate: " << question.date << "\nSubject: " << question.subject << "\nQuestion: " << question.questionText << endl; } } //this just displays question text for testing purposes void displayStructQuestion(Question & question) { cout << question.questionText << endl << endl; } //Much more improved way of getting the question from text file, //done by creating a struct of the question on that line, then displaying it if //it matches a set criteria void getQuestionStruct(char subject[]) { Question question;// the local struct we will be using to display the questions ifstream infile; infile.open("question.txt"); if(infile) infile.peek(); else cerr << "Couldn't open file..." << endl; while(!infile.eof()) { infile.get(question.date, 11, '|'); infile.ignore(1000, '|'); infile.get(question.subject, 100, '|'); infile.ignore(1000, '|'); infile.get(question.questionText, QUESTSIZE, '|'); infile.ignore(1000, '\n'); if(strcmp(subject, question.subject) == 0 || strcmp(subject, question.date) == 0 || strcmp(subject, "all") == 0) displayStruct(question); } } //This is our function that writes our desired question to our test file //does it in the order of "| Date | Subject | Body of question | \n" void writeToFile(Question & question) { ofstream out; out.open("question.txt", ios::app); if(out) { //cout << "Connected to file... " << endl; //cout << "Order will be | Date | Subject | Body of question | " << endl; out << question.date << "|" << question.subject << "|" << question.questionText << "|\n"; } else cerr << "Error writing to file..." << endl; out.close(); out.clear(); } //Don't even look at this it's not worth your time... /* VERY LOW IQ VERSION OF GETTING SHIT FROM THE FILE...... works like 35% of the time * this was a horrible way and it should never be used -_- void displayQuestion(char subject[]) { char date[11]; char compare[30]; char question[QUESTSIZE]; ifstream infile; infile.open("question.txt"); if(infile) { infile.peek(); //cout << "Date:" << date << endl; //infile.ignore(100, '|'); } else cerr << "Trouble reading from file..." << endl; //int count = 0; while(!infile.eof()) { //cout << count << endl; infile.get(compare, 31, '|'); infile.ignore(100, '|'); cout << "Our compare string: " << compare << endl; //cout << "What we want our compare to be: " << subject << endl; if(strcmp(subject, compare) == 0) { cout << "Key: " << subject << endl << "Compare: " << compare << endl; //infile.ignore(100, '|'); infile.get(question, QUESTSIZE, '|'); infile.ignore(100, '|'); cout << "Our question: " << question << endl; } //++count; } } */ <file_sep>/Term_One/prog_4/main.cpp #include <iostream> #include "prog4.h" int main() { int questions; cout << "How many questions would you like to enter?" << endl; cin >> questions; cin.ignore(100, '\n'); List list(questions); for(int i = 0; i < questions; ++i) { list.question[i].initQuestion(); list.question[i].display(); } return 0; } <file_sep>/Term_Two/prog5_backup/header.h #include <iostream> #include <cstring> #include <cctype> using namespace std; struct vertex { struct myClass* currentClass; struct node* head; struct node* tail; }; struct node { int adjacent; node* next; }; struct myClass { char* name; // myClass* next; // this is the list of required classes for any given class void copy(myClass* to_copy); }; class graph { public: graph(int size = 10); //~graph(); bool insertVertex(myClass* to_insert); bool insertEdge(char* name, char* connect); // bool display(void); int test(int i); bool traverse(char* name); int findLocation(char* key); private: vertex* list; int list_size; }; <file_sep>/Term_Three/prog2/list.cpp #include "list.h" //node class constructor taking the arrsize as an argument node::node(int arrSize) : next(NULL), arrSize(arrSize) { data = new base*[arrSize]; for(int i = 0; i < arrSize; ++i) data[i] = NULL; } //noed class desturctos node::~node() { delete next; int i; for(i = 0; i < arrSize; ++i) { if(data[i]) { delete data[i]; data[i] = NULL; } } } //function for deleting a base class pointer using a name to match bool node::deleteBase(char* match) { int i; bool removed = false; for(i = 0; !removed && i < arrSize; ++i) { if(data[i] && strcmp(match, data[i]->getName()) == 0) { delete data[i]; data[i] = NULL; removed = true; } } return removed; } //returns first matching base class pointer of the matching name base* node::getNodeByName(char* name) { bool found = false; base* temp = NULL; int i; for(i = 0; !found && i < arrSize; ++i) { if(data[i] && strcmp(name, data[i]->getName()) == 0) { found = true; temp = data[i]; } } return temp; } //displays all elements in the array void node::displayAll() { for(int i = 0; i < arrSize; ++i) if(data[i] != NULL) { data[i]->display(); cout << endl; } } //returns the priority of the element in given position int node::getPriority(int position) { return data[position]->getPriority(); } //returns if the last element is null in the list bool node::isFull() { return !(data[arrSize-1] == NULL); //if the last element in the array is not NULL then the array is full } //returns next pointer node*& node::goNext() { return next; } //adds a swim class void node::addSwim(swim* toAdd) { int i; bool inserted = false; for(i = 0; !inserted && i < arrSize; ++i) { if(data[i] == NULL) { data[i] = new swim(*toAdd); inserted = true; } } } //adds a work class void node::addWork(work* toAdd) { int i; bool inserted = false; for(i = 0; !inserted && i < arrSize; ++i) { if(data[i] == NULL) { data[i] = new work(*toAdd); inserted = true; } } } //adds a hiking class1 void node::addHike(hike* toAdd) { int i; bool inserted = false; for(i = 0; !inserted && i < arrSize; ++i) { if(data[i] == NULL) { data[i] = new hike(*toAdd); inserted = true; } } } //returns the poitners at n position in the array base*& node::getPosition(int position) { return this->data[position]; } //chose 5 as size of our arrays just because list::list() : arrSize(5), head(NULL), tail(NULL) {} //list detructor list::~list() { if(head) delete head; head = NULL; tail = NULL; } //function to delete a base class pointer form the LLL bool list::deleteBase(char* match) { node* cur; bool removed = false; if(head) for(cur = head; !removed && cur != NULL; cur = cur->goNext()) removed = cur->deleteBase(match); } //returns first matching base pointer with name base* list::getNodeByName(char* name) { bool found = false; node* cur; base* toReturn = NULL; if(!head) return NULL; else { for(cur = head; !found && cur != NULL; cur = cur->goNext()) { toReturn = cur->getNodeByName(name); if(toReturn != NULL) found = true; } } return toReturn; } //displays all nodes void list::display() { if(head) { for(node* cur = head; cur != NULL; cur = cur->goNext()) cur->displayAll(); } } //adds a swim object void list::addSwim(swim* toAdd) { if(!head) //head is null so there is no data anywhere { head = new node(arrSize); head->addSwim(toAdd); } else if(head->isFull()) { node* temp = head; head = new node(arrSize); head->goNext() = temp; head->addSwim(toAdd); } else head->addSwim(toAdd); } //adds a hike object void list::addHike(hike* toAdd) { if(!head) //head is null so there is no data anywhere { head = new node(arrSize); head->addHike(toAdd); } else if(head->isFull()) { node* temp = head; head = new node(arrSize); head->goNext() = temp; head->addHike(toAdd); } else head->addHike(toAdd); } //adds a work object void list::addWork(work* toAdd) { if(!head) //head is null so there is no data anywhere { head = new node(arrSize); head->addWork(toAdd); } else if(head->isFull()) { node* temp = head; head = new node(arrSize); head->goNext() = temp; head->addWork(toAdd); } else head->addWork(toAdd); } <file_sep>/Term_One/prog4/main4.cpp /* Code by <NAME> * program assignment number 4 for cs162 * this program is an object oriented version of program number 3 * purpose is to get practice questions you may want to use in the future * and store them into a file, then you may request specific questions */ #include "prog4.h" using namespace std; int main() { char input[21]; //our inputfor questions the user wants to get int count; //what we will be initializing the array of questions to char viewFile, exitVal; //if they want to view questions in the file or not, and an exit statement for main loop bool exit; //our exit boolean for main loop List list; // our list object cout << "How many questions do you want to enter: " << endl; cin >> count; cin.ignore(100, '\n'); list.init(count); //Initializing list to count size for(int i = 0; i < count; ++i) { list.initQuestion(i); list.write(i); } cout << "Would you like to access the questions in the file too? <y/n>" << endl; cin >> viewFile; cin.ignore(100, '\n'); if(viewFile == 'y') list.initFileList(); exit = list.hasQuestions();//checking to see if either list even has questions if(!list.hasQuestions()) cout << "No quetions to display! Please run again and enter some..." << endl; while(exit) { cout << "What question do you want to see, enter a date, subject, or \"all\" to display all questions. " << endl; cin.get(input, 21, '\n'); cin.ignore(1000, '\n'); list.compare(input); cout << "\nWould you like to see more questions? <y/n>" << endl; cin >> exitVal; cin.ignore(100, '\n'); if(exitVal == 'n') exit = false; } // delete list; cout << "\nThank you for running the program..." << endl; return 0; } <file_sep>/Term_Three/prog1/title.cpp #include "title.h" //====================Title functions and contructors================================ title::title() : name(NULL), date(NULL) {} //constructor with no data given to us so we will set it to NUL //constructor when we are given the information via arguments title::title(char* name, char* date) { this->name = new char[strlen(name) + 1]; this->date = new char[strlen(date) + 1]; strcpy(this->name, name); strcpy(this->date, date); } //constructor when we are given the data we need to work with title::title(const title & toCopy) //copy constructor { if(toCopy.name) { name = new char[strlen(toCopy.name) + 1]; strcpy(name, toCopy.name); } if(toCopy.date) { date = new char[strlen(toCopy.date) + 1]; strcpy(date, toCopy.date); } } //title destructor destroys dynamic memebersj title::~title() { delete [] name; delete [] date; name = NULL; date = NULL; } //display functions displays the name and date void title::display() { if(name) cout << "Name: " << name << endl; if(date) cout << "Date: " << date << endl; } //a change title function //I will probably not include this in main void title::changeTitle(char* name, char* date) { if(this->name) //checking to see if the name has already been set first { delete [] this->name; this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } else { this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } if(this->date) //checking to see if the date has been set already { delete [] this->date; this->date = new char[strlen(date) + 1]; strcpy(this->date, date); } else { this->date = new char[strlen(date) + 1]; strcpy(this->date, date); } } void title::changeTitle(const title & toChange) { if(this->name) //checking to see if the name has already been set first { delete [] this->name; this->name = new char[strlen(toChange.name) + 1]; strcpy(this->name, toChange.name); } else { this->name = new char[strlen(toChange.name) + 1]; strcpy(this->name, toChange.name); } if(this->date) //checking to see if the date has been set already { delete [] this->date; this->date = new char[strlen(toChange.date) + 1]; strcpy(this->date, toChange.date); } else { this->date = new char[strlen(toChange.date) + 1]; strcpy(this->date, toChange.date); } } void title::setTitleName(char* name) { if(this->name && name) //checking to see if the name has already been set first { delete [] this->name; this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } else if(!this->name && name) { this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } } void title::setTitleDate(char* date) { if(this->date) //checking to see if the date has been set already { delete [] this->date; this->date = new char[strlen(date) + 1]; strcpy(this->date, date); } else { this->date = new char[strlen(date) + 1]; strcpy(this->date, date); } } //=================================Video function and constructors================================== //default constructor video::video() : description(NULL) {} //constructor when we are given the information via arguments video::video(char* name, char* date, char* description, double length) : title(name, date), length(length) { this->description = new char[strlen(description) + 1]; strcpy(this->description, description); } //copy constructor calls title copy contructor as well using //initialization list video::video(const video & toCopy) : title(toCopy) { description = new char[strlen(toCopy.description) + 1]; strcpy(description, toCopy.description); length = toCopy.length; } //video destructor video::~video() { delete [] description; description = NULL; } //display function calls title display function and //also displays description and length void video::display() { title::display(); cout << "Description: " << this->description << endl << "Length: " << this->length << endl; } //====================Live stream functions and constructors============================== //default constructor liveStream::liveStream() : video(), instructor(NULL), topic(NULL) { } //copy contructor calls parent copy constructor for parent members liveStream::liveStream(const liveStream& toCopy) : video(toCopy) { this->instructor = new char[strlen(toCopy.instructor) + 1]; this->topic = new char[strlen(toCopy.topic) + 1]; strcpy(this->instructor, toCopy.instructor); strcpy(this->topic, toCopy.topic); } //constructor when we are given the information liveStream::liveStream(char* name, char* date, char* description, double length, char* instructor, char* topic) : video(name, date, description, length) { this->instructor = new char[strlen(instructor) + 1]; this->topic = new char[strlen(topic) + 1]; strcpy(this->instructor, instructor); strcpy(this->topic, topic); } //destructor liveStream::~liveStream() { delete [] instructor; delete [] topic; instructor = NULL; topic = NULL; } //display function where we call parents display which in turn calls //the title display function as well void liveStream::display() { video::display(); cout << "Instructor: " << this->instructor << endl << "Topic: " << this->topic << endl; cout << "Done displaying stream" << endl; } <file_sep>/Term_Three/prog1/main.cpp #include "node.h" /* * program one by <NAME> for cs202 at PSU * this program is to experiment with the use of classes and inheritance, * we have developed classes to represent different types of learning, whether it be a video, livestream, or essay * * to store these classes we have made use of an array of linear linked lists to try to make it more efficent, each * element in the array contains a pointer to a list of like objects */ //just a simple function to check if the user want to continue bool again() { char input; cout << "Again? <y,n>:"; cin >> input; cout << endl; return input == 'y'; } int main() { table LLL; //our data structure; //variables for adding specific objects to nodes video* vid; email* myEmail; liveStream* stream; essay* myEssay; node* toAdd; //node we will be using to add to the table; int input; //user input //variable for the title class char name[50]; char date[50]; //variables for the video class char desc[100]; double length; //variables for the liveStream class char instructor[50]; char topic[100]; //variables for the email class char subject[100]; char body[800]; char sender[50]; char recipiant[50]; double timeSent; //variables for the essay class char paper[1200]; char dueDate[20]; int wordLength; do { cout << "Please enter corresponding to below: " << endl << "1: Add a new video" << endl << "2: Add a new livestream" << endl << "3: Add a new Email" << endl << "4: Add a new essay" << endl << "5: Display all videos" << endl << "6: Display all livestreams" << endl << "7: Display all emails" << endl << "8: Display all essays" << endl << "9: Display everything" << endl cin >> input; cin.ignore(100, '\n'); switch(input) { /* * when adding to our table, we allocated a new object of requested type and call the copy constructor on it to copy its contents into * the array * * when the contents have been copied, we de allocate it and set it to null so we can re use the pointer */ case 1: cout << "Name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Date: "; cin.get(date, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Description of the video: "; cin.get(desc, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Length (minutes): "; cin >> length; cin.ignore(100, '\n'); vid = new video(name , date, desc, length); toAdd = new node(); toAdd->addVideo(*vid); LLL.addNode(toAdd); delete vid; delete toAdd; vid = NULL; toAdd = NULL; break; case 2: cout << "Name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Date: "; cin.get(date, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Description of the video: "; cin.get(desc, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Length (minutes): "; cin >> length; cin.ignore(100, '\n'); cout << endl << "Instructor: "; cin.get(instructor, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Topic: "; cin.get(topic, 100, '\n'); cin.ignore(100, '\n'); stream = new liveStream(name, date, desc, length, instructor, topic); toAdd = new node(); toAdd->addStream(*stream); LLL.addNode(toAdd); delete stream; delete toAdd; stream = NULL; toAdd = NULL; break; case 3: cout << "Name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Date: "; cin.get(date, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Recipiant: "; cin.get(recipiant, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Subject: "; cin.get(subject, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Body: "; cin.get(body, 800, '\n'); cin.ignore(800, '\n'); cout << endl << "Time sent: "; cin >> timeSent; cin.ignore(100, '\n'); toAdd = new node(); myEmail = new email(name, date, recipiant, subject, body, timeSent); toAdd->addEmail(*myEmail); LLL.addNode(toAdd); delete myEmail; delete toAdd; myEmail = NULL; toAdd = NULL; break; case 4: cout << endl << "Name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Date: "; cin.get(date, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Due Date: "; cin.get(dueDate, 100, '\n'); cin.ignore(100, '\n'); cout << endl << "Body: "; cin.get(paper, 1200, '\n'); cin.ignore(1200, '\n'); cout << endl << "Word Length: "; cin >> wordLength; cin.ignore(100, '\n'); myEssay = new essay(name, date, paper, dueDate, wordLength); toAdd = new node(); toAdd->addEssay(*myEssay); LLL.addNode(toAdd); delete toAdd; delete myEmail; toAdd = NULL; myEmail = NULL; break; // switch cases for displaying certain sets of objects case 5: LLL.displayVid(); break; case 6: LLL.displayStreams(); break; case 7: LLL.displayEmails(); break; case 8: LLL.displayEssays(); break; //9 displays the entire list with all its contents case 9: LLL.displayAll(); default: break; } }while(again()); return 0; } <file_sep>/Term_Three/prog1/email.h #include "title.h" class email : public title { public: //contructors and destructor email(); ~email(); email(const email & toCopy); email(char* name, char* date, char* subject, char* body, char* recipiant, double timeSent); //display function void display(); protected: char* subject; //subject of an email char* body; //actual message the email will hold char* recipiant; //who is recieving this email double timeSent; //the time the email was sent }; class essay : public title { public: //constructors and destructor essay(); ~essay(); essay(char* name, char* date, char* body, char* dueDate, int wordLength); essay(const essay & toCopy); //display functions void display(); protected: char* body; //actual paper char* dueDate; //due date int wordLength; //length of paper }; <file_sep>/Term_Two/Prog5/header.h #include <iostream> #include <cstring> #include <cctype> /* code by <NAME> for cs163 * this is supposed to be a lay out of classes and pre requisites * uses the graph ADT */ using namespace std; struct vertex { struct myClass* currentClass; //pointer to class object struct node* head; //head of adjacency list struct node* tail; //tail of adjacency list }; struct node { int adjacent; //position in the index of the adjacent class node* next; //next pointer for LLL ~node(); //node desturcotor }; struct myClass { char* name; //name of class void copy(myClass* to_copy); //copies classes }; class graph { public: graph(int size = 10); ~graph(); //constructor and destructor bool insertVertex(myClass* to_insert); //inserts a vertex bool insertEdge(char* name, char* connect); //inserts an edge with the name and the naem of the class you wish to connect to // bool display(void); int test(int i); bool traverse(char* name); //traverses based off name you give it int findLocation(char* key); //finds location of given class private: vertex* list; //list of verticies int list_size; }; <file_sep>/Term_Two/Prog2/main.cpp #include "header.h" int main() { travel circ1; travel circ2; return_trip stack1; return_trip stack2; trip_section trip; char name[100]; char traffic[100]; char notes[100]; char landmarks[100]; int length; bool exit = false; char input; int route; cout << "Welcome to the trip planner..." << endl << "Please enter your first route, to do so, you will enter the name, \n" << "traffic status, any notes about the road, any landmarks, and the length (miles)" << endl; do{ cout << "Enter the road name: " << endl; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter traffic condition: " << endl; cin.get(traffic, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter notes: " << endl; cin.get(notes, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter any landmarks: " << endl; cin.get(landmarks, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter length: " << endl; cin >> length; cin.ignore(100, '\n'); trip.set_trip(name, traffic, notes, landmarks, length); circ1.enqueue(&trip); // stack1.push(&trip); cout << "Would you like to add another? <y,n>: "; cin >> input; cin.ignore(100, '\n'); if(input == 'n') exit = true; }while(!exit); stack1.push(&trip); circ1.display(); cout << "Please enter the information for the second trip" << endl; exit = false; input = '\0'; do{ cout << "Enter the road name: " << endl; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter traffic condition: " << endl; cin.get(traffic, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter notes: " << endl; cin.get(notes, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter any landmarks: " << endl; cin.get(landmarks, 100, '\n'); cin.ignore(100, '\n'); cout << "Enter length: " << endl; cin >> length; cin.ignore(100, '\n'); trip.set_trip(name, traffic, notes, landmarks, length); circ2.enqueue(&trip); // stack2.push(&trip); cout << "Would you like to add another? <y,n>: "; cin >> input; cin.ignore(100, '\n'); if(input == 'n') exit = true; }while(!exit); stack2.push(&trip); circ2.display(); cout << "This is the trip to your destination via route 1:" << endl; circ1.display(); cout << "Hit enter to see the trip via route 2:" << endl; cin; cin.ignore(100, '\n'); circ2.display(); cout << "Hit enter to see the trip back home via route 1:" << endl; cin; cin.ignore(100, '\n'); // stack1.display(); cout << "Hit enter to see the trip back home via route 2:" << endl; cin; cin.ignore(100, '\n'); // stack2.display(); cout << "Please choose a route <1,2>: "; cin >> route; cin.ignore(100, '\n'); if(route == 1) { } else if(route == 2) { // circ1.~travel(); // stack1.~return_trip(); } cout << "At end of program" << endl; return 0; } <file_sep>/Term_Three/prog3/main.cpp #include "tree.h" bool again() { char input; cout << "Would you like to go again? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; return input == 'y'; } void help() { cout << "Here are your options" << endl << "1: Add a book" << endl << "2: Add a zoom meeting" << endl << "3: Add a website" << endl << "4: Display all" << endl << "5: See these options again" << endl; } int main() { char input; tree BST; node* toAdd; book* myBook; website* myWeb; zoom* myZoom; char subject[100]; char priority; char link[100]; // all the members for the website class //all the members for the book class char pages[100]; char author[100]; char title[100]; //all the members for the zoom class char teacher[100]; char time[100]; char id[100]; //start by populating the tree with information from the external file if there is one BST.getFromFile(); help(); do { cin >> input; cin.ignore(100, '\n'); switch(input) { case '1': cout << "Please enter the title of the book: "; cin.get(title, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter the author of the book: "; cin.get(author, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter the length in pages: "; cin.get(pages, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter the priority from <0-9> 0 being most important: "; cin >> priority; cin.ignore(100, '\n'); cout << endl; cout << "Please enter the subject of this book: "; cin.get(subject, 100, '\n'); cin.ignore(100, '\n'); cout << endl; myBook = new book(priority, subject, pages, author, title); toAdd = new node(); toAdd->addBook(*myBook); myBook->writeToFile(); BST.addNode(*toAdd); delete myBook; delete toAdd; myBook = NULL; toAdd = NULL; break; case '2': cout << "Please enter the teacher for this zoom meeting: "; cin.get(teacher, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter the time: "; cin.get(time, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "please enter the zoom meeting id: "; cin.get(id, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter the priority from <0-9> 0 being most important: "; cin >> priority; cin.ignore(100, '\n'); cout << endl; cout << "Please enter the subject of this book: "; cin.get(subject, 100, '\n'); cin.ignore(100, '\n'); cout << endl; myZoom = new zoom(priority, subject, teacher, time, id); toAdd = new node(); toAdd->addZoom(*myZoom); myZoom->writeToFile(); BST.addNode(*toAdd); delete myZoom; delete toAdd; myZoom = NULL; toAdd = NULL; break; case '3': cout << "Please enter the link to this website: "; cin.get(link, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter the priority from <0-9> 0 being most important: "; cin >> priority; cin.ignore(100, '\n'); cout << endl; cout << "Please enter the subject of this book: "; cin.get(subject, 100, '\n'); cin.ignore(100, '\n'); cout << endl; myWeb = new website(priority, subject, link); toAdd = new node(); toAdd->addWeb(*myWeb); myWeb->writeToFile(); BST.addNode(*toAdd); delete myWeb; delete toAdd; toAdd = NULL; myWeb = NULL; break; case '4': BST.display(); break; case '5': help(); break; } }while(again()); BST.getFromFile(); BST.display(); /* base* myBase; myWeb = new website('3', "bubject", "www.google.com"); myWeb->writeToFile(); // myWeb->writeToFile(); // myBook = new book('1', "first book", 200, "<NAME>", "like a bitch"); // myBook->writeToFile(); BST.getFromFile(); BST.display(); //book(int priority, char* subject, int pages, char* author, char* title) // toAdd.addBook(*myBook); // toAdd.display(); BST.addNode(toAdd); BST.display(); */ return 0; } <file_sep>/Term_Two/Prog3/header.h #include <iostream> #include <cstring> #include <cctype> #include <fstream> using namespace std; struct meal { char* mealName; //name of meal char* name; //name of venue int price; //approximate price int rating; //rating 1-10 char* review; //review bool type; //true = cart false = resturant bool copy(meal* to_add); //copys meals so its easier to add them void display(); //displays a meal ~meal(); //meal destructor }; struct node { meal* my_meal; //each node has a meal pointer node* next; //each node also has a next pointer ~node(); //node destructor }; class table { public: table(int size = 101); ~table(); //constructor and destructor bool add(char* key_value, meal* to_add); //function for adding meals int remove(char* meal_name); //function for removing meals by mealname int removeAll(char* name); //function that removes all meals of certain establishment meal* retrieve(char* key_word); //retrieves meal of desired meal name bool display(char* meal_name); //displays and returns number of nodes; int displayAll(); //displays all meals in the whole table int hash_function(char* key) const; //hash function for creating hash key private: node** hash_table; //hash table itself, array of pointers to pointers int hash_table_size; //size of hash table (101) }; <file_sep>/Term_One/prog4_backup/prog4/prog4.h #include <iostream> #include <cstring> #include <cctype> #include <fstream> using namespace std; class Question { public: Question(); //Contructor void writeToFile(); // writes question to file... void initQuestion(char Date[], char Subject[], char Body[]); // initilaizes question without user input void initQuestion(); // initiliazes question WITH user input void display();// Displays question date, subject, and body void compare(char word[]);// compares question to input, either a date, subject, or "all" private: char subject[21]; // Our subject, ex: loops, files, linked lists... char questionBody[140];// question itself.. char date[11];//the date of the question }; class List { public: List(int length); //Constructor, taking in an int as an argument to create dynamic array ~List();//destructor void initQuestion(int index);//initiliazes question at x index, using the Question initQuestion(); void initList(); //initiliazes list that the user will enter questions to void initFileList(); //initializes list of questions from external file should they want to view them void write(int index); // writes question at index x to external file void compare(char word[]);//compares using, the compare in the Question class private: Question* list; // pointer to list for questions the user will enter Question* fileList;// pointer to list for the questions from the external file int arrayLength; // length of list for input from user int fileLength;// amount of lines in the file, necessary for making the fileList of questions from file }; <file_sep>/Term_One/prog_4/prog4.cpp #include "prog4.h" Question::Question() { subject[0] = '\0'; date[0] = '\0'; body[0] = '\0'; } void Question::display() { cout << "Date: " << date << "\nSubject: " << subject << "\nQuestion: " << body << endl; } void Question::write() { ofstream out; out.open("question.txt", ios::app); if(out) { out << date << "|" << subject << "|" << body << "|\n"; } } void Question::initQuestion() { cout << "Date: "; cin.get(date, 11, '\n'); cin.ignore(100, '\n'); cout << "\nSubject: "; cin.get(subject, 21, '\n'); cin.ignore(100, '\n'); cout << "\nQuestion: "; cin.get(body, 140, '\n'); cin.ignore(1000, '\n'); } List::List(int length) { question = new Question[length]; fileList = NULL; lines = 0; char temp[300]; ifstream in; in.open("question.txt"); if(in) in.peek(); else cerr << "Couldn't open file..." << endl; while(getline(in, temp)) ++lines; fileList = new question[lines]; for(int i = 0; !in.eof(); ++i) { in.get(fileList[i].date, 11, '|'); in.ignore(100, '|'); in.get(fileList[i].subject, 21, '|'); in.ignore(100, '|'); in.get(fileList[i].body, 140, '|'); in.ignore(140, '\n'); } fileList[0].display(); } <file_sep>/Term_Two/Prog5/main.cpp #include "header.h" bool again() { char input; cout << "Would you like to enter again? <y,n> " << endl; cin >> input; cin.ignore(100, '\n'); return input == 'y'; } int main() { graph myGraph; //graph object myClass toEnter; //class object for entering things char name[100]; //user input char connect[100]; //user input char input; //for the switch case do { cout << "=======================" << endl; cout << "1: Add a class" << endl; cout << "2: Add a pre-req to this class" << endl; cout << "3: View what courses you can take after a current one" << endl; cin >> input; cin.ignore(100, '\n'); switch(input) { case '1': cout << "Please enter the name of the class: " << endl; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); toEnter.name = name; myGraph.insertVertex(&toEnter); break; case '2': cout << "Please enter the class before the pre req" << endl; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << "Now please enter the pre req" << endl; cin.get(connect, 100, '\n'); cin.ignore(100, '\n'); myGraph.insertEdge(name, connect); break; case '3': cout << "Please enter the class you wish to see" << endl; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); myGraph.traverse(name); break; default: break; } }while(again()); return 0; } <file_sep>/Term_Three/prog2/list.h #include "derived.h" class node { public: //constructor and copy constructor node(int arrSize); ~node(); node(const node& toCopy); int getPriority(int position); //returns the priority of the position at a certain index base*& getPosition(int position); //return the address of a base class pointer at a certain index bool isFull(); //returns true if the array is full node*& goNext(); //returns the next pointer void displayAll(); //displays all nodes in a array base* getNodeByName(char* name); //retrurns the first matching base class pointer by matching the name //functions for adding the children void addSwim(swim* toAdd); void addWork(work* toAdd); void addHike(hike* toAdd); //function to delete a base bool deleteBase(char* match); private: int arrSize; //size of eadch array base** data; //the array of base class pointers in all its glory node* next; //next pointer }; //list class class list { public: //constructor an destructor list(); ~list(); //returns th array size int getArrSize(); //displayus all contents in all nodes void display(); //functions to add children to the nodes void addSwim(swim* toAdd); void addWork(work* toAdd); void addHike(hike* toAdd); //returns the first matching base class by strmp name base* getNodeByName(char* name); //calls the node::deleteBase fucntions and deltes the first base with a matching name bool deleteBase(char* match); private: int arrSize; //size of the array in each node node* head; //head and tail pointers node* tail; }; <file_sep>/Term_Three/prog2/base.cpp #include "base.h" //default constructor with no arguments using initialization list base::base() : activityLength(-1), priority(-1), group(false), name(NULL), location(NULL) {} //copy constructor, copying any dynamically allocated memoery base::base(const base & toCopy) : activityLength(toCopy.activityLength), priority(toCopy.priority), group(toCopy.group) { this->name = new char[strlen(toCopy.name) + 1]; strcpy(this->name, toCopy.name); this->location = new char[strlen(toCopy.location) + 1]; strcpy(this->location, toCopy.location); } //constructor when given the data members as arguments base::base(int length, int priority, bool group, char* name, char* location) : activityLength(length), priority(priority), group(group) { this->name = new char[strlen(name) + 1]; strcpy(this->name, name); this->location = new char[strlen(location) + 1]; strcpy(this->location, location); } //destructor deleteing any dynamic memoery base::~base() { if(this->location && this->name) { delete [] this->location; delete [] this->name; } this->name = NULL; this->location = NULL; } //display function void base::display() { cout << "Name: " << name << endl << "Location: " << location << endl << "Length: " << activityLength << " hours" << endl << "Priority: " << priority << endl; if(group) cout << "Group Activity" << endl; else cout << "Not a group activity" << endl; } //returns prioprity int base::getPriority() { return priority; } <file_sep>/Term_One/prog5/main.cpp //Written by <NAME> cs162 <NAME> class //this program is meant to be a to-do list for winter break //you can add remove and search for things to do // //This program makes use of linear linked lists and recursive functions. //it also sorts each node that is added into the lit based off name. #include "prog5.h" #include "stdlib.h" void commands() { cout << "\n The way you use this program is like this: " <<"\nTo add somehting you want to do, simply type \"add\"" << endl << "To remove a something on the list type, \"remove\" followed " << "by the name of the item you wish to remove, like this, \"remove sledding\"" << endl << "To see all the things you want to do, type \"display\", you can also do " << "\"display 6\" to see all the items with a priority of 6, this can be any number 1-10" << endl << "Finally, if you wish to exit, just type \"exit\"" << endl << "If you want to see these again type \"help\" " << endl; } void seperate(char* word, char* first, int* second) { cout << "in seperator" << endl; char tempFirst[40], tempLast[40]; int space = -1; int size = strlen(word); int count = 0; for(int i = 0; i < size; ++i) { if(isspace(word[i])) { space = i; ++i; } if(space > 0) { tempLast[count] = word[i]; ++count; } if(space == -1) { tempFirst[i] = word[i]; } } char* secondTemp; first = new char[strlen(tempFirst)+1]; secondTemp = new char[strlen(tempLast)+1]; strcpy(first, tempFirst); strcpy(secondTemp, tempLast); int num = atoi(secondTemp); second = new int(num); // cout << "First: " << first << endl; // cout << "Last: " << second << endl; } int main() { bool exit = false; char input[40]; char* first; int* second; List list; cout << "Welcome to the TO-DO list!" << endl; cout << "\n Winter break is long and there is plenty to do " << "\nso why not write it down!" << endl; commands(); while(!exit) { cin.get(input, 40, '\n'); cin.ignore(100, '\n'); cout << input << endl; if(strcmp(input, "help") == 0) commands(); else if(strcmp(input, "exit") == 0) exit = true; else if(strcmp(input, "add") == 0) list.add(); else if(strcmp(input, "display")) { seperate(input, first, second); } cout << first << endl; cout << second << endl; } return 0; } <file_sep>/Term_Two/Prog3/class.cpp #include "header.h" /* * little messy but it works and with no memory leaks * code by <NAME> */ //function for copying a new node preferably from main to make it a little easier bool meal::copy(meal* to_add) { this->mealName = new char[strlen(to_add->mealName) + 1]; this->name = new char[strlen(to_add->name) + 1]; this->review = new char[strlen(to_add->review) + 1]; //Copying everything into new node, this is used //to make inserting into the hash table easier strcpy(mealName, to_add->mealName); strcpy(name, to_add->name); strcpy(review, to_add->review); rating = to_add->rating; price = to_add->price; type = to_add->type; return true; } //display function part of meal struct to make it easier to display meals from main and in other //display functions void meal::display() { cout << "Meal name: " << mealName << endl; cout << "Name: " << name << endl << "Review: " << review << endl << "Rating <1-10>: " << rating << endl << "Approximate Price Per Meal: " << price << "$" << endl; if(type) cout << "Type: Food Cart" << endl; else cout << "Type: Restuarant" << endl; } //Meal deconstructor meal::~meal() { delete [] mealName; delete [] name; delete [] review; mealName = NULL; name = NULL; review = NULL; } //Node deconstructor, recursivly calls destructor on itself node::~node() { delete next; delete my_meal; } //----------------------------------------------HashTable functions-------------------------------- //Hashtable contructor, i chose size of 101, initializes all element node* to NULL table::table(int size) { int i; hash_table_size = size; hash_table = new node*[hash_table_size]; for(i = 0; i < hash_table_size; ++i) hash_table[i] = NULL; } //hashtable deconstructor, calls the node destructor on each element then deletes array of pointers table::~table() { int i; for(i = 0; i < hash_table_size; ++i) delete hash_table[i]; delete [] hash_table; } //hash function, takes an array of characters and adds up all their ascii values, then mods it by table size (101) int table::hash_function(char* key) const { int i; int total; for(i = 0; i < strlen(key); ++i) total += key[i]; if((total % hash_table_size) < 0) return (total % hash_table_size) * -1; return total % hash_table_size; } //adds a meal to the hash table, in case of collision it creates a linear linked list of the meals with same hashfunction values bool table::add(char* key_value, meal * to_add) { int key = hash_function(key_value); //position in hash_table node* temp; //temp pointer if(hash_table[key]) //checking to see the the element already has a node (collision) { temp = hash_table[key]; hash_table[key] = new node; hash_table[key]->my_meal = new meal; (*hash_table[key]->my_meal).copy(to_add); hash_table[key]->next = temp; return true; } else //in the case of no collision we just create a new node { hash_table[key] = new node; hash_table[key]->my_meal = new meal; (*hash_table[key]->my_meal).copy(to_add); hash_table[key]->next = NULL; return true; } return false; } //displays the first meal with a matching name, this does not adjust for collision, did not have time //also returns the position in the hashtable, idk why bool table::display(char* meal_name) { int key = hash_function(meal_name); if(hash_table[key] != NULL) { (*hash_table[key]->my_meal).display(); return true; } return false; } //this function was just for me so I could see everything in the table, returns the total number of nodes in the table int table::displayAll() { int numNode = 0; node* temp; int i; for(i = 0; i < hash_table_size; ++i) { if(hash_table[i] != NULL) { cout << "Chain #" << i << ":" << endl; temp = hash_table[i]; do { ++numNode; (*temp->my_meal).display(); cout << endl << endl; temp = temp->next; }while(temp != NULL); } } return numNode; } //this function removes a meal by the meal name //returns the position that was deleted int table::remove(char* meal_name) { node* cur; node* prev; int i; int removed; for(i = 0; i < hash_table_size; ++i) { if(hash_table[i] != NULL) { cur = hash_table[i]; prev = cur; //this is a very sketch way of going about the table while(cur != NULL) { if(cur == hash_table[i] && strcmp(meal_name, cur->my_meal->mealName) == 0) //special case for if there is only one { hash_table[i] = cur->next; removed = hash_function(cur->my_meal->mealName); delete cur; cur = NULL; } else { cur = cur->next; if(strcmp(meal_name, cur->my_meal->mealName) == 0) { prev->next = cur->next; removed = hash_function(cur->my_meal->mealName); delete cur; cur = NULL; } else prev = cur; } } } } return removed; } //removes all meals by establishment name //returning number of establishments deleted int table::removeAll(char* name) { node* cur; node* prev; int i; int deleted = 0; for(i = 0; i < hash_table_size; ++i) { if(hash_table[i] != NULL) { cur = hash_table[i]; prev = cur; while(cur != NULL) { //special case if its the first node in the list if(cur == hash_table[i] && strcmp(hash_table[i]->my_meal->name, name) == 0) { if(cur->next == NULL) hash_table[i] = NULL; else hash_table[i] = cur->next; delete cur; cur = hash_table[i]; ++deleted; } else { cur = cur->next; if(cur && strcmp(cur->my_meal->name, name) == 0) { if(cur->next = NULL) prev->next = NULL; else prev->next = cur->next; delete cur; ++deleted; cur = hash_table[i]; } else prev = cur; } } } } return deleted; } //returns the address of the desired meal based off meal name //checks to see if its null first //if it doesnt exist it returns null meal* table::retrieve(char* meal_name) { int key = hash_function(meal_name); if(hash_table[key] != NULL) return hash_table[key]->my_meal; else return NULL; } <file_sep>/Term_Three/prog3/tree.cpp #include "tree.h" //constructors node::node() : id(-1), left(NULL), right(NULL), myBook(NULL), myWeb(NULL), myZoom(NULL) {} node::node(const node& toCopy) : id(toCopy.id), left(NULL), right(NULL) { switch(toCopy.id) { case '0': myBook = new book(*toCopy.myBook); break; case '1': myWeb = new website(*toCopy.myWeb); break; case '2': myZoom = new zoom(*toCopy.myZoom); break; default: break; } } node::~node() { delete left; delete right; switch(id) { case 0: delete myBook; myBook = NULL; break; case 1: delete myWeb; myWeb = NULL; break; case 2: delete myZoom; myZoom = NULL; break; default: break; } left = NULL; right = NULL; } //displays the content of the node void node::display() { switch(id) { case '0': myBook->display(); break; case '1': myWeb->display(); break; case '2': myZoom->display(); break; default: break; } } //returns the priority of the contents of the node char node::getPriority() { char priority = '\0'; switch(id) { case '0': priority = myBook->getPriority(); break; case '1': priority = myWeb->getPriority(); break; case '2': priority = myZoom->getPriority(); break; default: break; } return priority; } //how we know which node holds what type of object 0 = book, 1 = website, 2 = zoom void node::addBook(book& toAdd) { myBook = new book(toAdd); id = '0'; } void node::addWeb(website& toAdd) { myWeb = new website(toAdd); id = '1'; } void node::addZoom(zoom& toAdd) { myZoom = new zoom(toAdd); id = '2'; } //constructor tree::tree() : root(NULL) {} tree::~tree() { delete root; root = NULL; } //add a node to the tree void tree::addNode(node& toAdd, node*& root) { if(!root) { root = new node(toAdd); return; } else { if(toAdd.getPriority() < root->getPriority()) addNode(toAdd, root->goRight()); else addNode(toAdd, root->goLeft()); } } //wrapper function void tree::addNode(node& toAdd) { addNode(toAdd, root); } //wrapper fucntion void tree::display() { display(root); } //recursivea display function void tree::display(node* root) { if(!root) return; else { root->display(); display(root->goLeft()); display(root->goRight()); } } //populating the tree with information from the external file void tree::getFromFile() { ifstream in; in.open("prog3.txt"); char type; // either w, b, z, how we find out which object we are going to be adding //members for our base class char subject[100]; char priority; char link[100]; // all the members for the website class //all the members for the book class char pages[100]; char author[100]; char title[100]; //all the members for the zoom class char teacher[100]; char time[100]; char id[100]; website* myWeb; zoom* myZoom; book* myBook; node* toAdd; if(in) in.peek(); else cerr << "Couldn't open file" << endl; while(!in.eof()) { in.get(type); in.ignore(100, '|'); switch(type) { case 'w': in.get(link, 100, '|'); in.ignore(100, '|'); in.get(subject, 100, '|'); in.ignore(100, '|'); in.get(priority); in.ignore(100, '\n'); myWeb = new website(priority, subject, link); toAdd = new node(); toAdd->addWeb(*myWeb); addNode(*toAdd); delete toAdd; delete myWeb; toAdd = NULL; myWeb = NULL; break; case 'b': in.get(pages, 100, '|'); in.ignore(100, '|'); in.get(author, 100, '|'); in.ignore(100, '|'); in.get(title, 100, '|'); in.ignore(100, '|'); in.get(subject, 100, '|'); in.ignore(100, '|'); in.get(priority); in.ignore(100, '\n'); myBook = new book(priority, subject, pages, author, title); toAdd = new node(); toAdd->addBook(*myBook); addNode(*toAdd); delete toAdd; delete myBook; toAdd = NULL; myBook = NULL; break; case 'z': in.get(teacher, 100, '|'); in.ignore(100, '|'); in.get(time, 100, '|'); in.ignore(100, '|'); in.get(id, 100, '|'); in.ignore(100, '\n'); in.get(subject, 100, '|'); in.ignore(100, '|'); in.get(priority); in.ignore(100, '\n'); myZoom = new zoom(priority, subject, teacher, time, id); toAdd = new node(); toAdd->addZoom(*myZoom); addNode(*toAdd); delete toAdd; delete myZoom; toAdd = NULL; myZoom = NULL; break; default: break; } } } <file_sep>/Term_Three/prog2/main.cpp #include "list.h" void help() { cout << "You have three activities to add, " << "working, hiking, and swiming" << endl; cout << "Please see the following for adding: " << endl << "1: Add a new working activity" << endl << "2: Add a new hiking activity" << endl << "3: Add a new swimming activity" << endl << "4: Remove an activity by name" << endl << "5: Add a lunch to a work activity by name" << endl << "6: Plan a work out for a swim activity by name" << endl << "7: Pack climbing shoes for a hike by name" << endl << "D: Display all activities" << endl << "0: To exit program" << endl << "H: To see this prompt again" << endl; } char getInput() { char commandInput; cout << "Please enter a command: "; cin >> commandInput; cin.ignore(100, '\n'); cout << endl; return commandInput; } int main() { list myList; //our data structur base* toFind; //for dynamic casting char commandInput; //input commands char input; //members inputs char locateActivity[50]; //name to match and find base pointers //base class memebers char name[40]; char location[50]; int priority; int activityLength; bool isGroupActivity; //swim pointer and all it's needed members swim* mySwim; char swimSuit[40]; bool member; bool hasHotTub; //hike pointer and all it's needed members hike* myHike; bool overNight; char season[20];; char weather[20]; //work pointer and all it's needed members work* myWork; char position[40];; double pay; bool partTime; //how we will be deciding what to do based on user commandInput help(); do { commandInput = getInput(); switch(commandInput) { case '1': cout << "Please enter name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Enter location: "; cin.get(location, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Enter priority <1-10> 1 being you want to do it immediatly: "; cin >> priority; cin.ignore(100, '\n'); cout << endl; cout << "Enter activity length, in hours, round to the nearest hour: "; cin >> activityLength; cin.ignore(100, '\n'); cout << endl; cout << "Is this a group activity? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') isGroupActivity = true; else isGroupActivity = false; cout << "Please enter your position in the work place: "; cin.get(position, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Please enter your pay per hour: "; cin >> pay; cin.ignore(100, '\n'); cout << endl; cout << "Is this a part time or full time job <p,f>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'p') partTime = true; else partTime = false; myWork = new work(activityLength, priority, isGroupActivity, name, location, position, pay, partTime); cout << "Adding work object" << endl; myList.addWork(myWork); cout << "Added work object" << endl; delete myWork; myWork = NULL; break; case '2': cout << "Please enter name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Enter location: "; cin.get(location, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Enter priority <1-10> 1 being you want to do it immediatly: "; cin >> priority; cin.ignore(100, '\n'); cout << endl; cout << "Enter activity length, in hours, round to the nearest hour: "; cin >> activityLength; cin.ignore(100, '\n'); cout << endl; cout << "Is this a group activity? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') isGroupActivity = true; else isGroupActivity = false; cout << "Will this hike be overnight? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') overNight = true; else overNight = false; cout << "Current Season: "; cin.get(season, 20, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Predicted weather?: "; cin.get(weather, 20, '\n'); cin.ignore(100, '\n'); cout << endl; myHike = new hike(activityLength, priority, isGroupActivity, name, location, overNight, season, weather); myList.addHike(myHike); delete myHike; myHike = NULL; break; case '3': cout << "Please enter name: "; cin.get(name, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Enter location: "; cin.get(location, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Enter priority <1-10> 1 being you want to do it immediatly: "; cin >> priority; cin.ignore(100, '\n'); cout << endl; cout << "Enter activity length, in hours, round to the nearest hour: "; cin >> activityLength; cin.ignore(100, '\n'); cout << endl; cout << "Is this a group activity? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') isGroupActivity = true; else isGroupActivity = false; cout << "What kind of swimsuit will you wear: "; cin.get(swimSuit, 100, '\n'); cin.ignore(100, '\n'); cout << endl; cout << "Are you a member? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') member = true; else member = false; cout << "Does this pool have a hot tub? <y,n>: "; cin >> input; cin.ignore(100, '\n'); cout << endl; if(input == 'y') hasHotTub = true; else hasHotTub = false; mySwim = new swim(activityLength, priority, isGroupActivity, name, location, swimSuit, member, hasHotTub); myList.addSwim(mySwim); cout << "swimSuit: " << swimSuit << endl; delete mySwim; mySwim = NULL; break; case '4': cout << "Please enter the name of the activity you would like to delete: "; cin.get(locateActivity, 40, '\n'); cin.ignore(100, '\n'); cout << endl; toFind = myList.getNodeByName(locateActivity); if(!toFind) cout << "There was no match" << endl; else { cout << "Located and deleted this activity" << endl << endl; toFind->display(); } myList.deleteBase(locateActivity); toFind = NULL; break; case '5': cout << "Enter the work activity you would like to plan a lunch for: "; cin.get(locateActivity, 40, '\n'); cin.ignore(100, '\n'); cout << endl; toFind = myList.getNodeByName(locateActivity); if(toFind) { myWork = dynamic_cast<work*>(toFind); myWork->display(); if(myWork) { try { myWork->planLunch(); }catch(int e) {} } else cout << "Sorry, couldn't add a lunch to this activity..." << endl; } myWork = NULL; toFind = NULL; break; case '6': cout << "Please enter the swimming activity you would like to work out on: "; cin.get(locateActivity, 40, '\n'); cin.ignore(100, '\n'); cout << endl; toFind = myList.getNodeByName(locateActivity); mySwim = dynamic_cast<swim*>(toFind); if(mySwim) { try { mySwim->startExercise(); } catch(int e) {} } else cout << "Sorry, couldn't plan a work out for this activity..." << endl; mySwim = NULL; toFind = NULL; break; case '7': cout << "Please enter the hike you would like to pack climbing shoes on: "; cin.get(locateActivity, 40, '\n'); cin.ignore(100, '\n'); cout << endl; toFind = myList.getNodeByName(locateActivity); myHike = dynamic_cast<hike*>(toFind); if(myHike) { try { myHike->rockClimb(); }catch(int e) {} } else cout << "Sorry, couldn't pack climbing shoes for this activity..." << endl; myHike = NULL; toFind = NULL; break; case 'D': myList.display(); break; case 'd': myList.display(); break; case '0': break; case 'H': help(); break; case 'h': help(); break; default: cout << "Please enter something valid..." << endl; break; } } while(commandInput != '0'); cout << "Exiting Program..." << endl; return 0; } <file_sep>/Term_Two/Prog4_Backup/class.cpp #include "header.h" //This is also for ease and displays any given meal void meal::display() { cout << "Meal name: " << name << endl << "Establishment name: " << storeName << endl << "Review: " << review << endl << "Rating <1-10>: " << rating << endl << "Approximate Price: " << price << "$" << endl << "Type: "; if(type) cout << "Food cart" << endl; else cout << "Retaurant" << endl; } //This is purely to make things look easier, copies a meal passed in to the current meal void meal::copy(meal* to_add) { this->name = new char[strlen(to_add->name) + 1]; this->storeName = new char[strlen(to_add->name) + 1]; this->review = new char[strlen(to_add->review) + 1]; strcpy(this->name, to_add->name); strcpy(this->storeName, to_add->storeName); strcpy(this->review, to_add->review); this->price = to_add->price; this->rating = to_add->rating; this->type = to_add->type; } //constructor for tree class, setting root to NULL as usual tree::tree() { root = NULL; } //Wrapper function for add function, returns boolean on if it was added or not bool tree::add(meal* toAdd) { return add(toAdd, root); } //Adds a node and returns whether it was succesfull or not bool tree::add(meal* toAdd, node*& root) { if(!root) { root = new node; root->myMeal.copy(toAdd); root->left = NULL; root->right = NULL; return true; } else { if(strcmp(root->myMeal.name, toAdd->name) < 0) add(toAdd, root->left); else add(toAdd, root->right); } return false; } int tree::displayMatch(char* mealName) { return displayMatch(mealName, root); } //Counts and displays the number of retaurants with matching meal names //returns the amount of matching meals int tree::displayMatch(char* mealName, node* root) { int sum = 0; if(!root) return 0; else { if(strcmp(mealName, root->myMeal.name) == 0) { root->myMeal.display(); ++sum; } } displayMatch(mealName, root->left); displayMatch(mealName, root->right); return sum; } //Wrapper function for our display fucntion returning the number of nodes in the tree int tree::display() { return display(root); } //displays entire tree and returns the number of nodes in the tree int tree::display(node* root) { int sum = 0; if(!root) return 0; else { root->myMeal.display(); cout << endl; } sum = display(root->left) + 1; sum = display(root->right) + 1; return sum; } <file_sep>/Term_One/prog4_backup/prog4/main4.cpp #include "prog4.h" using namespace std; int main() { int count; char viewFile, exitVal; bool exit = true; cout << "How many questions do you want to enter: " << endl; cin >> count; cin.ignore(100, '\n'); List list(count); for(int i = 0; i < count; ++i) { list.initQuestion(i); list.write(i); } cout << "Would you like to access the questions in the file? <y/n>" << endl; cin >> viewFile; cin.ignore(100, '\n'); if(viewFile == 'y') list.initFileList(); char input[21]; while(exit) { cout << "What question do you want to see, enter a date, subject, or \"all\" to display all questions. " << endl; cin.get(input, 21, '\n'); cin.ignore(1000, '\n'); list.compare(input); cout << "\nWould you like to see more questions? <y/n>" << endl; cin >> exitVal; cin.ignore(100, '\n'); if(exitVal == 'n') exit = false; } cout << "\nThank you for running the program..." << endl; return 0; }
ba2ffc66b5672c37d4202ccc0f3985f72699f8a2
[ "C++" ]
48
C++
cjtorralba/PSU
e0f33b1794177d6ff8c1759ec89baba0e37f90ed
8b048360393d4eac23b5bfd57430f793fadcc9fa
refs/heads/master
<repo_name>gdanj/email_mairie<file_sep>/README.md # email_mairie https://github.com/gdanj/email_mairie/blob/master/index.html <file_sep>/recupmail.rb def get_the_email_of_a_townhal_from_its_webpage(s) page = Nokogiri::HTML(open(s)) m = [] page.xpath('//p').each do |v| m << v.text end return m end
7686fbe479cec5f3c6d129230d5f31ae0a410ee7
[ "Markdown", "Ruby" ]
2
Markdown
gdanj/email_mairie
a7f90320e836ec1f0024401ad80a5c2cb755902b
2f97fd54225b2d138fa7f6a01adbd121a195cec5
refs/heads/master
<file_sep><?php include "conn.php"; $q="SELECT tentang FROM tentang"; $sql=mysql_query($q); $hasil=mysql_fetch_array($sql); $profil=htmlspecialchars_decode($hasil['tentang']); ?> <div class="box1"> <div class="inner"> <a href="#" class="close" data-type="close"><span></span></a> <h2>Biodataku</h2> <div class="wrapper"> <figure class="left marg_right1"><img src="images/page2_img1.jpg" alt=""></figure> <p class="color1 pad_bot2"><strong>Cerita Sedikit...</strong></p> <?php echo $profil;?> </div> </div> </div><file_sep><?php include "conn.php"; ?> <div class="box1"> <div class="inner"> <a href="#" class="close" data-type="close"><span></span></a> <div class="wrapper tabs"> <div class="col1"> <h2>Categories</h2> <ul class="nav"> <li class="selected"><a href="#Action"><span></span><strong>Action</strong></a></li> <li><a href="#Makanan"><span></span><strong>Makanan</strong></a></li> <li><a href="#Tidur"><span></span><strong>Tidur</strong></a></li> <li><a href="#Barang"><span></span><strong>Barang</strong></a></li> <li><a href="#Lainnya"><span></span><strong>Lainnya</strong></a></li> </ul> </div> <div class="col2 pad_left1"> <div class="tab-content" id="Action"> <h2>Action</h2> <?php $q="SELECT count(foto) from diary where id_kategori='1'"; $sql=mysql_query($q); $num_rows=mysql_result($sql,0); $q2="SELECT foto from diary where id_kategori='1'"; $sql2=mysql_query($q2); for ($i = 0; $i < $num_rows; $i+=2) { $gambar = mysql_result($sql2, $i, 'foto'); ?> <div class="wrapper"> <figure class="left marg_right1"><a href="img/<?php echo $gambar;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar;?>" height="130" width="202" alt=""></a></figure> <?php if($i+1 < $num_rows){ $gambar2 = mysql_result($sql2, $i+1, 'foto');?> <figure class="left"><a href="img/<?php echo $gambar2;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar2;?>" height="130" width="202" alt=""></a></figure> </div> <? }} ?> </div> <div class="tab-content" id="Makanan"> <h2>Makanan</h2> <?php $q="SELECT count(foto) from diary where id_kategori='2'"; $sql=mysql_query($q); $num_rows=mysql_result($sql,0); $q2="SELECT foto from diary where id_kategori='2'"; $sql2=mysql_query($q2); for ($i = 0; $i < $num_rows; $i+=2) { $gambar = mysql_result($sql2, $i); ?> <div class="wrapper"> <figure class="left marg_right1"><a href="img/<?php echo $gambar;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar;?>" height="130" width="202" alt=""></a></figure> <?php if($i+1 < $num_rows){ $gambar2 = mysql_result($sql2, $i+1);?> <figure class="left"><a href="img/<?php echo $gambar2;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar2;?>" height="130" width="202" alt=""></a></figure> </div> <? }} ?> </div> <div class="tab-content" id="Tidur"> <h2>Tidur</h2> <?php $q="SELECT count(foto) from diary where id_kategori='3'"; $sql=mysql_query($q); $num_rows=mysql_result($sql,0); $q2="SELECT foto from diary where id_kategori='3'"; $sql2=mysql_query($q2); for ($i = 0; $i < $num_rows; $i+=2) { $gambar = mysql_result($sql2, $i); ?> <div class="wrapper"> <figure class="left marg_right1"><a href="img/<?php echo $gambar;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar;?>" height="130" width="202" alt=""></a></figure> <?php if($i+1 < $num_rows){ $gambar2 = mysql_result($sql2, $i+1);?> <figure class="left"><a href="img/<?php echo $gambar2;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar2;?>" height="130" width="202" alt=""></a></figure> </div> <? }} ?> </div> <div class="tab-content" id="Barang"> <h2>Barang</h2> <?php $q="SELECT count(foto) from diary where id_kategori='4'"; $sql=mysql_query($q); $num_rows=mysql_result($sql,0); $q2="SELECT foto from diary where id_kategori='4'"; $sql2=mysql_query($q2); for ($i = 0; $i < $num_rows; $i+=2) { $gambar = mysql_result($sql2, $i); ?> <div class="wrapper"> <figure class="left marg_right1"><a href="img/<?php echo $gambar;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar;?>" height="130" width="202" alt=""></a></figure> <?php if($i+1 < $num_rows){ $gambar2 = mysql_result($sql2, $i+1);?> <figure class="left"><a href="img/<?php echo $gambar2;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar2;?>" height="130" width="202" alt=""></a></figure> </div> <? }} ?> </div> <div class="tab-content" id="Lainnya"> <h2>Lainnya</h2> <?php $q="SELECT count(foto) from diary where id_kategori='5'"; $sql=mysql_query($q); $num_rows=mysql_result($sql,0); $q2="SELECT foto from diary where id_kategori='5'"; $sql2=mysql_query($q2); for ($i = 0; $i < $num_rows; $i+=2) { $gambar = mysql_result($sql2, $i); ?> <div class="wrapper"> <figure class="left marg_right1"><a href="img/<?php echo $gambar;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar;?>" height="130" width="202" alt=""></a></figure> <?php if($i+1 < $num_rows){ $gambar2 = mysql_result($sql2, $i+1);?> <figure class="left"><a href="img/<?php echo $gambar2;?>" class="lightbox-image" data-type="prettyPhoto[group1]"><span></span><img src="img/<?php echo $gambar2;?>" height="130" width="202" alt=""></a></figure> </div> <? }} ?> </div> </div> </div> </div> </div><file_sep><!DOCTYPE html> <html lang="en"> <head> <title><NAME> the Cat</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/reset.css" type="text/css" media="all"> <link rel="stylesheet" href="css/layout.css" type="text/css" media="all"> <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="all"> <link rel="stylesheet" href="css/style.css" type="text/css" media="all"> <script type="text/javascript" src="js/jquery-1.6.js" ></script> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/cufon-replace.js"></script> <script type="text/javascript" src="js/Ubuntu_400.font.js"></script> <script type="text/javascript" src="js/Ubuntu_700.font.js"></script> <script type="text/javascript" src="js/bgSlider.js" ></script> <script type="text/javascript" src="js/script.js" ></script> <script type="text/javascript" src="js/pages.js"></script> <script type="text/javascript" src="js/jquery.easing.1.3.js"></script> <script type="text/javascript" src="js/bg.js" ></script> <script type="text/javascript" src="js/tabs.js"></script> <script type="text/javascript" src="js/jquery.prettyPhoto.js"></script> <!--[if lt IE 9]> <script type="text/javascript" src="js/html5.js"></script> <![endif]--> <!--[if lt IE 7]> <div style='clear:both;text-align:center;position:relative'> <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx?ocid=ie6_countdown_bannercode"><img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" alt="" /></a> </div> <![endif]--> </head> <body id="page1"> <div class="spinner"></div> <div id="bgSlider"></div> <div class="extra"> <div class="main"> <div class="box"> <!-- header --> <header> <h1><a href="index.php" id="logo">Catatan Nekoyanagi the Cat</a></h1> <nav> <ul id="menu"> <li><a href="#!/page_Home"><span></span><strong>Diary</strong></a></li> <li><a href="#!/page_About"><span></span><strong>Tentang</strong></a></li> <li><a href="#!/page_Portfolio"><span></span><strong>Galeri</strong></a></li> <li><a href="#!/page_Services"><span></span><strong>Rekomendasi</strong></a></li> <li><a href="#!/page_Contact"><span></span><strong>Kontak</strong></a></li> </ul> </nav> </header> <!--content --> <article id="content"> <div class="ic">More Website Templates @ TemplateMonster.com -September 19th, 2011!</div> <ul> <li id="page_Home"> <?php include "diary/index.php";?> </li> <li id="page_About"> <?php include "tentang/index.php";?> </li> <li id="page_Portfolio"> <?php include "galeri/index.php";?> </li> <li id="page_Services"> <?php include "rekomendasi/rekomendasi.php";?> </li> <li id="page_Contact"> <?php include "kontak/index.php";?> </li> <li id="page_More"> <div class="box1"> <div class="inner"> <a href="#" class="close" data-type="close"><span></span></a> <h2>Read more</h2> <div class="wrapper pad_bot3"> <figure class="left marg_right1"><img src="images/page4_img1.jpg" alt=""></figure> <p class="color1 pad_bot2"><strong>Et harum quidem rerum</strong></p> <p>Cupiditate noprovident similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas.</p> </div> <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p> <p>Occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p> <div class="wrapper pad_bot3"> <figure class="left marg_right1"><img src="images/page4_img2.jpg" alt=""></figure> <p class="color1 pad_bot2"><strong>Blanditiis praesentium voluptatum</strong></p> <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti iusto odio dignissimos ducimus qui atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p> </div> <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p> <p>Qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p> <p>Occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p> </div> </div> </li> </ul> </article> <!-- / content --> </div> </div> <div class="block"></div> </div> <div class="bg1"> <div class="main"> <!-- footer --> <footer> <div class="bg_spinner"></div> <ul class="pagination"> <li class="current"><a href="images/bg_img1.jpg">1</a></li> <li><a href="images/bg_img2.jpg">2</a></li> <li><a href="images/bg_img3.jpg">3</a></li> </ul> <div class="col_1"> <a href="index.php" id="footer_logo">Nekoyanagi the Cat</a> Copyright 2013 </div> <div class="col_2"> Designed by <a rel="nofollow" href="http://2ne1.kpop-indo.com/" target="_blank"><NAME></a> | <a rel="nofollow" href="http://www.nekoyanagi.net/" target="_blank">Nekoyanagi</a> <!-- {%FOOTER_LINK} --> </div> </footer> <!-- / footer--> </div> </div> <script type="text/javascript"> Cufon.now(); </script> <script> $(window).load(function() { $('.spinner').fadeOut(); $('body').css({overflow:'inherit'}) }) </script> </body> </html><file_sep><?php include "conn.php"; $batas = 4; if(!empty($_GET['page'])){ $hal=$_GET['page']-1; $start = $batas * $hal; }else if(!empty($_GET['page'])and $_GET['page']==1){ $start=0; }else if(empty($_GET['page'])){ $start=0; } ?> <div class="box1"> <div class="inner"> <a href="#" class="close" data-type="close"><span></span></a> <div class="wrapper pad_bot1"> <h2>Diary Nekoyanagi</h2> <?php $q="SELECT judul,foto,isi,tanggal FROM diary ORDER BY id_diary DESC limit $start , $batas"; $sql=mysql_query($q); while ($hasil=mysql_fetch_array($sql)){ $isi=htmlspecialchars_decode($hasil['isi']); $lokasi=$hasil['foto']; $tanggal=$hasil['tanggal']; $judul=$hasil['judul']; $date=explode("-",$tanggal); $bulan=$date[1]; $tgl=$date[2]; switch($bulan) { case"01"; $bulan="Jan"; break; case"02"; $bulan="Feb"; break; case"03"; $bulan="Mar"; break; case"04"; $bulan="Apr"; break; case"05"; $bulan="Mei"; break; case"06"; $bulan="Juni"; break; case"07"; $bulan="Juli"; break; case"08"; $bulan="Agst"; break; case"09"; $bulan="Sept"; break; case"10"; $bulan="Okt"; break; case"11"; $bulan="Nov"; break; case"12"; $bulan="Des"; break; } ?> <div class="wrapper" id="<?php echo $i;?>"> <span class="date"><strong><?php echo $tgl;?></strong><span><?php echo $bulan;?></span></span> <figure class="left marg_right1"><a href="img/<?php echo $lokasi;?>" data-type="prettyPhoto[group2]"><img src="img/<?php echo $lokasi;?>" height="138" width="220" alt=""></a></figure> <p class="color1 pad_bot2"><strong><?php echo $judul;?></strong></p> <p> <?php echo $isi;?></p> </div> <br> <?php } ?> <center> <?php $cekquery=mysql_query("SELECT * From diary"); $jumlah=mysql_num_rows($cekquery); if($jumlah > $batas){ echo '<br><div id="halaman">Halaman : '; $a=explode(".", $jumlah/$batas); $b=$a[0]; $c=$b+1; for($i=1;$i<=$c;$i++){ echo '<a style="text-decoration:none;'; if($_GET['page']==$i){ echo 'color:red'; } echo'"href="?page='. $i .'#!/page_Home" "class="close "data-type"=close > '. $i .' </a>'; } echo'</div>'; } ?> </center> </div> </div><file_sep><div class="box1"> <div class="inner"> <a href="#" class="close" data-type="close"><span></span></a> <h2>Barang-barang rekomended buat pus meongmu :3</h2><br><br> <?php include "conn.php"; $batas = 4; if(!empty($_GET['page'])){ $hal=$_GET['page']-1; $start = $batas * $hal; }else if(!empty($_GET['page'])and $_GET['page']==1){ $start=0; }else if(empty($_GET['page'])){ $start=0; } $q="SELECT id,namafoto,judul,isi FROM rekomendasi ORDER BY id DESC limit $start,$batas"; $sql=mysql_query($q); while ($hasil=mysql_fetch_array($sql)){ $judul=$hasil['judul']; $foto=$hasil['namafoto']; $isi=htmlspecialchars_decode($hasil['isi']); ?> <div class="wrapper pad_bot3"> <figure class="left marg_right1"><a href="img/<?php echo $foto;?>" data-type="prettyPhoto[group2]"><img src="img/<?php echo $foto;?>" height="134" width="220" alt=""></a></figure> <p class="color1 pad_bot2"><strong><?php echo $judul;?></strong></p> <?php echo $isi;?> </div> <?php } ?> <center> <?php $cekquery=mysql_query("SELECT * From diary"); $jumlah=mysql_num_rows($cekquery); if($jumlah > $batas){ echo '<br><div id="halaman">Halaman : '; $a=explode(".", $jumlah/$batas); $b=$a[0]; $c=$b+1; for($i=1;$i<=$c;$i++){ echo '<a style="text-decoration:none;'; if($_GET['page']==$i){ echo 'color:red'; } echo'"href="?page='. $i .'#!/page_Services" "class="close "data-type"=close > '. $i .' </a>'; } echo'</div>'; } ?> </center> </div> </div><file_sep>nekoyanagi ==========
dc74e958e7d0dd013f43b61c6469a6c4299cd381
[ "Markdown", "PHP" ]
6
PHP
faradina/yanagi
ea0897d79a081f38b12a898eeae2eecf8f5bbf53
7bb4b4497a03c0b46aa50336e0f6a1605262f296
refs/heads/master
<repo_name>tohanss/repobee-csvgrades<file_sep>/requirements.txt repobee_plug>=0.10.0 repobee>=2.1.0 <file_sep>/README.md # repobee-csvgrades [![Build Status](https://travis-ci.com/slarse/repobee-csvgrades.svg)](https://travis-ci.com/slarse/repobee-csvgrades) [![Code Coverage](https://codecov.io/gh/slarse/repobee-csvgrades/branch/master/graph/badge.svg)](https://codecov.io/gh/slarse/repobee-csvgrades) ![Supported Python Versions](https://img.shields.io/badge/python-3.6%2C%203.7%2C%203.8-blue) ![Supported Platforms](https://img.shields.io/badge/platforms-Linux%2C%20macOS-blue.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Code Style: Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) A plugin for reporting grades into a CSV file based on issue titles. `repobee-csvgrades` adds the `record-grades` command, which operates on the JSON file produced by running `repobee list-issues` with the `--hook-results-file` option. The idea is pretty simple: find issues in student repositories that match certain user-defined conditions (title + who opened it) and report the corresponding grades into a (preferably version controlled) CSV file. ## Example use case Say that you have three students, `slarse`, `glassey` and `glennol`, three tasks `task-1`, `task-2` and `task-3`, and that you (and any colleagues) open issues with titles `Pass` for pass and `Fail` for fail. `repobee-csvgrades` can then be configured to look for issues with those titles (using a regex), and write them into a grades sheet that looks something like this: ``` name,username,task-1,task-2,task-3 <NAME>, slarse, P, P, F Richard Glassey, glassey, P, P, P <NAME>, glennol, P, P, P ``` > **GitHub and CSV files:** GitHub > [renders CSV files really nicely](https://help.github.com/en/articles/rendering-csv-and-tsv-data), > they are even searchable! Only grades from issues that were opened by authorized teachers, as specified by you, are written to the file. Grades are mapped from issue title to a symbol, so the CSV file becomes more readable (here there's for example `P` for `Pass`). You also assign grades a priority, so if for example there's both a fail and a pass issue in a repo, it will pick the one that you've specified is most important. Additionally, each time new grades are reported, a summary message will be produced that looks something like this: ``` Record grades for task-3 @ta_a slarse task-3 F @ta_b glassey task-3 P ``` The `@ta_a` and `@ta_b` are mentions of the teachers/TAs (with usernames `ta_a` and `ta_b`) that opened the issues. The intention is that this message should be used as a commit message for the grades file, so that the people who reported grades get notified of which grades have been written to the grades sheet. That's just a quick introduction, see [Usage](#usage) for a more detailed description. ## Install Currently, the best way to install is directly from the Git repo. ``` $ python3 -m pip install git+https://github.com/slarse/repobee-csvgrades.git ``` Eventually, `repobee-csvgrades` will be moved to PyPi so you can just `pip install` it like any other package. ## Usage `repobee-csvgrades` is easy to use and highly customizable. First of all, you need to know how to use a plugin for RepoBee, see the [RepoBee plugin docs](https://repobee.readthedocs.io/en/stable/plugins.html). Then, there are a few key parts to familiarize yourself with before using it, however. The following sections explain the command line options in depth. Also don't miss the fact that you can configure all options in the [configuration file](#configuration-file-section). ### The grade specification (`--grade-specs` option) The grade specification (or _grade spec_) is the most important part of this plugin. Grade specs tell the `record-grades` command which issues to consider as grading issues, and which grading issues outweigh others if several are found. A typical grade spec looks like this: `1:P:[Pp]ass`. There are three parts to the grade spec, delimited by `:`. First is the priority. A lower priority outweighs a higher priority. Second is the symbol that is written to the CSV grades file. Third is a regex to match against issue titles. Any issue whos title matches the regex is considered a grading issues of that spec. > **Important:** Your grade spec regexes should _not_ overlap (i.e. be able to > match the same strings). If they do, behavior is undefined. Grade specs are specified by the `--grade-specs` option. Example: ``` --grade-specs '1:P:[Pp]ass' '2:F:[Ff]ail' '3:C:[Cc]orrection' ``` ### The hook results file (`--hook-results-file` option) `record-grades` operates on a file with a JSON database produced by the `list-issues` command (one of RepoBee's core commands). The file is produced by supplying the `--hook-results-file FILEPATH` option to `list-issues`. You should additionally supply `list-issues` with the `--all` flag, to get both open and closed issues (so as to avoid missing grading issues). If you try to use `record-grades` with a hook results file that's been produced without the `--all` flag, it will exit with an error. If you really want to run with that file, you can supply the `--allow-other-states` flag to `record-grades`, which disregards how the hook results were collected. The hook results file is specified by the `--hook-results-file` option. Example: ``` --hook-results-file ~/some_course/2019/hook_results_jan.json ``` ### The grades file (`--grades-file` option) `record-grades` writes grades to a CSV file that we refer to as the _grades file_. Each row represents one student, except for the first row which is a header row. The following requirements are placed on the CSV file format: * Commas must be used as the delimiter * The first line of the file must be a row of headers * One of the headers must be `username`, and the column must include the usernames of all students to be graded * There must be one column for each master repo, and the header for that column must exactly match the master repo's name Below is an example grades file that has been partially filled in by the `record-grades` command. As it is a CSV file, it is rendered very nicely on GitHub (see for example [this test file](/tests/expected_grades.csv)), and it is strongly recommended that you keep this file in version control. ``` name,username,task-1,task-2,task-3,task-4,task-5,task-6 <NAME>, slarse, P, P, F, , , <NAME>, glassey, P, P, P, , , <NAME>, glennol, P, P, P, , , ``` There are a few additional things to keep in mind with the grades file. * You should not manually edit the file with grade symbols for which there are no grade specifications, as this may cause `record-grades` to exit because it can't find a priority for the grade. * You can't have a task called `username`. * You can't have duplicate column headers. * You **can** have any additional columns that you want. `record-grades` will only look at the `username` column, and the columns corresponding to the master repo names that you specify when calling the command. Additional columns will simply not be inspected. * `record-grades` formats the diff file such that every cell of the same column has the same width, which makes diffs easy to inspect. - Because of this formatting, it is recommended to keep grade spec symbols shorter than the master repo names, to avoid resizing of columns when grades are entered. The grades file is specified by the `--grades-file` option. Example: ``` --grades-file ~/some_course/2019/grades.csv ``` ### The edit message file (`--edit-msg-file` option) Each time you run `record-grades`, a file is produced specifying what new grades were recorded, and tags the teachers who opened the grading issues. The intention is that this edit message should be used as a Git commit message. For example, if `slarse` has teacher `ta_a`, and `glassey` has teacher `ta_b`, and they both got new grades for `task-3`, the edit message might look like ths: ``` Record grades for task-3 @ta_a slarse task-3 F @ta_b glassey task-3 P ``` The reason this edit message file exists is that some of our TAs felt a bit nervous about not knowing when their reported grades were collected. If this edit message is posted as the commit message, every teacher/TA whos grades have been collected will be notified, and the extra thorough ones can even inspect the diff to make sure everything is OK. The destination for the edit message file is specified by the `--edit-msg-file` option. Example: ``` --edit-msg-file edit_msg.txt ``` ### Authorized teachers (`--teachers` option) The `record-grades` command requires you to specify a set of teachers that are authorized to open grading issues. This is to avoid having students trick the system. If an grading issue by an unauthorized user is found, a warning is emitted. This is both to alert the user about potential attempts at foul play, but also to help identify teachers that are actually authorized, but have not been included in the list. Teachers are specified with the `--teachers` option. Example: ``` --teachers ta_a ta_b ``` ## Configuration file section `repobee-csvgrades` can fetch information from the [RepoBee configuration file](https://repobee.readthedocs.io/en/stable/configuration.html#configuration-file), under the `csvgrades` section. All of the command line options can be configured. Here is an example of a complete configuration file that sets the same defaults as shown in the examples that end each subsection in the [Usage](#usage) section. ``` [DEFAULTS] plugins = csvgrades [csvgrades] hook_results_file = ~/some_course/2019/hook_results_jan.json grades_file = ~/some_course/2019/grades.csv edit_msg_file = edit_msg.txt teachers = ta_a,ta_b pass_gradespec = 1:P:[Pp]ass fail_gradespec = 2:F:[Ff]ail corr_gradespec = 3:C:[Cc]orrection ``` Note that you can have an arbitrary amount of grade spec options. Just end an option with `gradespec` and it will be parsed as a grade spec. # License `repobee-csvgrades` is released under the MIT license. See [LICENSE](LICENSE) for details. <file_sep>/.travis/run.sh #!/bin/bash function run_flake8() { pip install flake8 flake8 . if [[ ! $? == 0 ]]; then exit 1 fi } if [[ $TRAVIS_OS_NAME == 'osx' ]]; then eval "$(pyenv init -)" pyenv local 3.6.5 3.7.0 pyenv global 3.7.0 run_flake8 tox else run_flake8 pytest tests --cov=repobee_csvgrades --cov-branch fi <file_sep>/repobee_csvgrades/csvgrades.py """A plugin for reporting grades into a CSV file based on issue titles .. module:: csvgrades :synopsis: A plugin for reporting grades into a CSV file based on issue titles .. moduleauthor:: <NAME> """ import argparse import pathlib import configparser import itertools import daiquiri import repobee_plug as plug from repobee_csvgrades import _file from repobee_csvgrades import _grades from repobee_csvgrades import _marker from repobee_csvgrades import _containers from repobee_csvgrades import _exception PLUGIN_NAME = "csvgrades" LOGGER = daiquiri.getLogger(__file__) def callback(args: argparse.Namespace, api: None) -> None: results_file = pathlib.Path(args.hook_results_file) grades_file = pathlib.Path(args.grades_file) hook_results_mapping = _file.read_results_file(results_file) if "list-issues" not in hook_results_mapping: raise _exception.FileError( "can't locate list-issues metainfo in hook results" ) if ( not args.allow_other_states and plug.IssueState( hook_results_mapping["list-issues"][0].data["state"] ) != plug.IssueState.ALL ): raise _exception.FileError( "repobee list-issues was not run with the --all flag. This may " "cause grading issues to be missed. Re-run list-issues with the " "--all flag, or run this command with --allow-other-states to " "record grades anyway." ) grade_specs = list( map(_containers.GradeSpec.from_format, args.grade_specs) ) grades = _grades.Grades(grades_file, args.master_repo_names, grade_specs) grades.check_users( itertools.chain.from_iterable([t.members for t in args.students]) ) new_grades = _marker.mark_grades( grades, hook_results_mapping, args.students, args.master_repo_names, args.teachers, grade_specs, ) if new_grades: _file.write_edit_msg( sorted(new_grades.items()), args.master_repo_names, pathlib.Path(args.edit_msg_file), ) _file.write_grades_file(grades_file, grades) else: LOGGER.warning("No new grades reported") class CSVGradeCommand(plug.Plugin): def __init__(self): self._hook_results_file = None self._grades_file = None self._edit_msg_file = None self._grade_specs = None self._teachers = None def config_hook(self, config_parser: configparser.ConfigParser): self._hook_results_file = config_parser.get( PLUGIN_NAME, "hook_results_file", fallback=self._hook_results_file ) self._grades_file = config_parser.get( PLUGIN_NAME, "grades_file", fallback=self._grades_file ) self._edit_msg_file = config_parser.get( PLUGIN_NAME, "edit_msg_file", fallback=self._edit_msg_file ) self._grade_specs = self._parse_grade_specs(config_parser) self._teachers = self._parse_teachers(config_parser) @staticmethod def _parse_teachers(config_parser): return [ name.strip() for name in config_parser.get( PLUGIN_NAME, "teachers", fallback="" ).split(",") ] @staticmethod def _parse_grade_specs(config_parser): if not config_parser.has_section(PLUGIN_NAME): return [] sec = config_parser[PLUGIN_NAME] return [ value for key, value in sec.items() if key.endswith("gradespec") ] def create_extension_command(self): parser = plug.ExtensionParser() parser.add_argument( "--hf", "--hook-results-file", help="Path to an existing hook results file.", type=str, required=not self._hook_results_file, default=self._hook_results_file, dest="hook_results_file", ) parser.add_argument( "--gf", "--grades-file", help="Path to the CSV file with student grades.", type=str, required=not self._grades_file, default=self._grades_file, dest="grades_file", ) parser.add_argument( "--ef", "--edit-msg-file", help="Filepath specifying where to put the edit message. " "Defaults to 'edit_msg.txt'", type=str, required=not self._edit_msg_file, default=self._edit_msg_file, dest="edit_msg_file", ) parser.add_argument( "--gs", "--grade-specs", help=( "One or more grade specifications on the form " "<PRIORITY>:<SYMBOL>:<REGEX>. Example: 1:P:[Pp]ass" ), type=str, required=not self._grade_specs, default=self._grade_specs, nargs="+", dest="grade_specs", ) parser.add_argument( "-t", "--teachers", help=( "One or more space-separated usernames of teachers/TAs " "that are authorized to open grading issues. If a " "grading issue is found by a user not in this list, " "a warning is logged and the grade is not recorded." ), type=str, required=not self._teachers, default=self._teachers, nargs="+", ) parser.add_argument( "-a", "--allow-other-states", help="Allow other list-issues states than `all`. If this flag is " "not specified, the `list-issues` command must have been run " "with the `--all` flag.", action="store_true", default=False, ) return plug.ExtensionCommand( parser=parser, name="record-grades", help="Record grades from issues into a CSV file.", description="Record grades from issues into a CSV file. Grade " "specifications on the form <PRIORITY>:<SYMBOL>:<REGEX> " "specify which issues are grading issues (by matching the title " "against the spec regex), and the corresponding symbol is written " "into the grades CSV file. If multiple grading issues are found " "in the same repo, the one with the lowest priority is recorded. " "A grade in the CSV file can only be overwritten by a grade with " "lower priority. Only grading issues opened by teachers " "specified by the ``--teachers`` option are recorded. Read more " "at https://github.com/slarse/repobee-csvgrades", callback=callback, requires_base_parsers=[ plug.BaseParser.REPO_NAMES, plug.BaseParser.STUDENTS, ], )
483cb57ae7677217bffeb2fd10ea0c4f66380f52
[ "Markdown", "Python", "Text", "Shell" ]
4
Text
tohanss/repobee-csvgrades
b1b13c9a3f4282aed3946da5b25fe47ee3edd032
284b14b4153920be2c5a7a8d760073a6659fab86
refs/heads/master
<file_sep>package InvertedIndex; import java.io.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.StringUtils; public class InvertedIndexMapper extends Mapper<LongWritable,Text,Text,Text>{ private Text docID; private Text word=new Text(); protected void setup(Context context){ String filename=((FileSplit)context.getInputSplit()).getPath().getName(); docID=new Text(filename); } protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException{ String[] temp=value.toString().split(" "); for(String token:temp){ word.set(token); context.write(word,docID); } } } <file_sep>package MRUnitTest; import static org.junit.Assert.*; import org.junit.Test; public class JunitTestCountA { @Test public void test() { JunitTest test=new JunitTest(); int output=test.countA("AuthorA"); assertEquals(2,output); } } <file_sep>package Titanic; import java.io.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; //The Reducer will count all the values for each unique Reducer. //The Keys have been sorted by the gender column. public class TitanicReducer extends Reducer<TitanicCustomKey, IntWritable, TitanicCustomKey, IntWritable> { public void reduce(TitanicCustomKey key, Iterable<IntWritable> values, Context context)throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(key, new IntWritable(sum)); } }<file_sep>package practice; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WholeFileISDriver { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Two parameters are required for DriverNLineInputFormat- <input dir> <output dir>\n"); System.exit(-1); } Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "whole file IS"); job.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job.setJarByClass(practice.WholeFileISDriver.class); job.setMapperClass(practice.WholeFileMapper.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(Text.class); job.setNumReduceTasks(0); FileInputFormat.addInputPath(job, new Path(args[0])); job.setInputFormatClass(practice.WholeFileInputFormat.class); //if you dont use combinetext input format, then number of mappers is equal to number of input files // job.setInputFormatClass(CombineTextInputFormat.class); FileOutputFormat.setOutputPath(job,new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } <file_sep>package CustomKeyValue; import java.io.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; public class CustomDataTypeMapper extends Mapper<LongWritable,Text,CustomKey,IntWritable>{ private static final IntWritable one=new IntWritable(1); private CustomKey cKey=new CustomKey(); private IntWritable reqNo=new IntWritable(); private Text URL=new Text(); private Text reqDate=new Text(); private Text timestamp=new Text(); private Text IP=new Text(); public void map(LongWritable key, Text value, Context context)throws IOException, InterruptedException{ String str[]=value.toString().split("\t"); reqNo.set(Integer.parseInt(str[0])); URL.set(str[1]); reqDate.set(str[2]); timestamp.set(str[3]); IP.set(str[4]); //System.out.println(URL +"\t"+ reqDate+ "\t"+ timestamp+ "\t"+IP+ "\t"+ reqNo); //pass values to setter methods /*cKey.setRegNo(regNo); cKey.setURL(URL); cKey.setRegDate(regDate); cKey.setTime(time); cKey.setIP(IP); */ cKey.set(URL, reqDate, timestamp,IP, reqNo); // when you send CKey only IP is sent. because from getter only IP is taken rest all are commented context.write(cKey, one); } } <file_sep>package ChainingMRjobs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob; import org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; //method2: using job control for mapper1-->reducer1-->mapper2->redcuer2 //you can break this Driver into two and run manually one by one by giving job 1 output directory to input of job2 as given below. but, this is the simplest mehtod //hadoop jar chain.jar Job1 shakespeare output //hadoop jar chain.jar Job2 output output2 //however, very similar way you can to mapper1-->mapper2->mapper3--> reducer1-->mapper4-->reducer2 ... in any fashion public class JobChainDriverMethod2 { private static final String OUTPUT_PATH = "intermediate_output"; public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Enter valid number of arguments <Inputdirectory> <Outputlocation>"); System.exit(-1); } Job job = Job.getInstance(conf); job.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job.getConfiguration().set("mapreduce.output.textoutputformat.separator", "\t"); Configuration conf1 = new Configuration(); Configuration conf2 = new Configuration(); Job job1 = new Job(conf1, "WC"); job1.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job1.setJarByClass(ChainingMRjobs.JobChainDriverMethod2 .class); job1.setMapperClass(ChainingMRjobs.Mapper1.class); job1.setReducerClass(ChainingMRjobs.Reducer1.class); job1.setOutputKeyClass(Text.class); job1.setOutputValueClass(IntWritable.class); job1.setInputFormatClass(TextInputFormat.class); job1.setOutputFormatClass(TextOutputFormat.class); ControlledJob cJob1 = new ControlledJob(conf1); cJob1.setJob(job1); FileInputFormat.addInputPath(job1, new Path(args[0])); FileOutputFormat.setOutputPath(job1, new Path(OUTPUT_PATH)); Job job2 = new Job(conf2, "WC of WC"); job2.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job2.setJarByClass(ChainingMRjobs.JobChainDriverMethod2.class); job2.setMapperClass(ChainingMRjobs.Mapper2.class); job2.setReducerClass(ChainingMRjobs.Reducer2.class); //job2.setSortComparatorClass(ReverseOrder.class); job2.setOutputKeyClass(Text.class); job2.setOutputValueClass(IntWritable.class); job2.setInputFormatClass(TextInputFormat.class); job2.setOutputFormatClass(TextOutputFormat.class); ControlledJob cJob2 = new ControlledJob(conf2); cJob2.setJob(job2); FileInputFormat.addInputPath(job2, new Path(OUTPUT_PATH+"/part*")); FileOutputFormat.setOutputPath(job2, new Path(args[1])); JobControl jobctrl = new JobControl("jobctrl"); jobctrl.addJob(cJob1); jobctrl.addJob(cJob2); cJob2.addDependingJob(cJob1); jobctrl.run(); // delete jobctrl.run(); /* Thread t = new Thread(jobctrl); t.start(); String oldStatusJ1 = null; String oldStatusJ2 = null; while (!jobctrl.allFinished()) { String status =cJob1.toString(); String status2 =cJob2.toString(); if (!status.equals(oldStatusJ1)) { System.out.println(status); oldStatusJ1 = status; } if (!status2.equals(oldStatusJ2)) { System.out.println(status2); oldStatusJ2 = status2; } } System.exit(0);*/ } } <file_sep>package DistriCache; import java.io.IOException; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Reducer; public class NcdcMaxTempReducer extends Reducer<Text,IntWritable,Text,IntWritable>{ private NcdcStationMetadataParcer metadata; private Configuration conf; String fileName ; String stationName; protected void setup(Context context) throws IOException{ try{ URI[] patternsURIs = Job.getInstance(conf).getCacheFiles(); for (URI patternsURI : patternsURIs) { Path patternsPath = new Path(patternsURI.getPath()); fileName = patternsPath.getName().toString().trim(); if (fileName.equals("station.txt")){ metadata = new NcdcStationMetadataParcer(); metadata.initialize(patternsPath); break; } } System.out.println("File : "+ patternsURIs[0].toString()); } catch(NullPointerException e){ System.out.println("Exception : "+e); } System.out.println("Cache : "+context.getConfiguration().get("mapred.cache.files")); } protected void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException{ System.out.println("step1"); stationName = metadata.getStationName(key.toString()); System.out.println("step2"); int maxValue = Integer.MIN_VALUE; for (IntWritable val:values){ maxValue = Math.max(maxValue, val.get()); } context.write(new Text(stationName),new IntWritable(maxValue)); } } <file_sep>package FileSystemAPI; import java.io.IOException; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; //dont execute this program from eclispe on windows as permission error will be the result //execute this program in hadoop environment or eclipse on hadoop public class FileDelete { public static void main(String[] args)throws IOException { // TODO Auto-generated method stub Configuration conf=new Configuration(); String uri="hdfs://node2:10001/"; Path path = new Path(uri); FileSystem fs=FileSystem.get(URI.create(uri),conf); //display files and directories FileStatus[] status=fs.listStatus(path); // to show list of files in a directory Path[] paths=FileUtil.stat2Paths(status); for(Path p:paths){ System.out.println(p.toString()); } //delete input.txt Path path1 = new Path(uri+"/input.txt"); path.getFileSystem(conf).delete(path1); Path path2 = new Path(uri); FileStatus[] status1=fs.listStatus(path2); // to show list of files in a directory Path[] paths1=FileUtil.stat2Paths(status); //display files and directories for(Path p:paths1){ System.out.println(p.toString()); } } } <file_sep>package CustomKeyValue; import java.io.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; // output of mapper is key:/vfnlyvnx.html value: 172.16.31.10 and 1 public class MultiWritableReducer extends Reducer<Text,MultiWritableValue,Text,IntWritable>{ private Text result = new Text(); public void reduce(Text key,Iterable<MultiWritableValue> values, Context context) throws IOException, InterruptedException{ int sum = 0; StringBuilder output = new StringBuilder(); for (MultiWritableValue multi : values) { Writable writable = multi.get(); if (writable instanceof IntWritable){ sum += ((IntWritable)writable).get(); } /*else{ requests.append(((Text)writable).toString()); requests.append("\t"); }*/ } //result.set(key + "\t"+sum); context.write(key, new IntWritable(sum)); } } <file_sep>package DistriCache; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; /* in NcdcMaxTempReducer it shows NullPointer Exception. understand the program and debug it. input files are WeatherRecord.txt and station.txt add MRv2 jars. dont add MRv1 it will lead to exception. run in hadoop services. it doesnot run in Eclipse */ public class NCDCDriver{ public static void main(String[] arg) throws Exception { if(arg.length !=2) { System.err.println("Usage:<inputpath> <outputpath>"); System.exit(-1); } Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Distributed Cache"); job.setJarByClass(DistriCache.NCDCDriver.class); job.setMapperClass(DistriCache.NcdcMaxTempMapper.class); //job.setCombinerClass(DistriCache.NcdcMaxTempCombiner.class); job.setReducerClass(DistriCache.NcdcMaxTempReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(arg[0])); FileOutputFormat.setOutputPath(job, new Path(arg[1])); //for MRv1 with its libraries //DistributedCache.addCacheFile(new URI("hdfs://node1:10001/input/station.txt"), job.getConfiguration()); //for MRv2 with its libraries job.addCacheFile(new Path("hdfs://node1:10001/input/station.txt").toUri()); System.exit(job.waitForCompletion(true) ? 0 : 1); } } <file_sep>package RunTimeArguments; import java.io.IOException; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.Mapper.Context; public class WCMRv2Reducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); int lower; int upper; //set up method is called only once after JVM created public void setup(Context context)throws IOException, InterruptedException{ lower = Integer.parseInt(context.getConfiguration().get("LowerLimit")); upper = Integer.parseInt(context.getConfiguration().get("UpperLimit")); } public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } if(sum>=lower && sum<=upper){ result.set(sum); context.write(key, result); } } // cleanup method is called only once before JVM exit public void cleanup(Context context)throws IOException,InterruptedException{ } } <file_sep>package MRUnitTest; import static org.junit.Assert.*; import org.junit.Test; //https://www.youtube.com/watch?v=I8XXfgF9GSc public class JunitSquareTest { @Test public void test() { JunitTest test=new JunitTest(); int output=test.square(5); assertEquals(26,output); } } <file_sep>package practice; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.CombineTextInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class CombineFilesDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); //or Job job=Job.getInstance(getConf()); job.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job.setJarByClass(practice.CombineFilesDriver.class); job.setMapperClass(practice.WCMRv2Mapper.class); // check number of map output and it is not sorted //job.setReducerClass(practice.WCMRv2Reducer.class); job.setNumReduceTasks(0); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(CombineTextInputFormat.class); // just enable this if you have more number of small files to pack as one IS. It is in hadoop-mapreduce-client-core-2.7.0 CombineTextInputFormat.setMaxInputSplitSize(job, 64000000); // many files are put into 64 MB FileInputFormat.setInputPaths(job, new Path("D:/Eclipse Project/Practice/dataset/many files/*.txt")); FileOutputFormat.setOutputPath(job,new Path("D:/Eclipse Project/Practice/output")); System.exit( job.waitForCompletion(true) ? 0 : 1); } } <file_sep>package Titanic; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.LineRecordReader; public class TitanicRR extends RecordReader<TitanicCustomKey,IntWritable> { private TitanicCustomKey key; private IntWritable value; private LineRecordReader reader = new LineRecordReader(); @Override public TitanicCustomKey getCurrentKey() throws IOException, InterruptedException { // TODO Auto-generated method stub return key; } @Override public IntWritable getCurrentValue() throws IOException, InterruptedException { // TODO Auto-generated method stub return value; } @Override public float getProgress() throws IOException, InterruptedException { // TODO Auto-generated method stub return reader.getProgress(); } @Override public void initialize(InputSplit is, TaskAttemptContext tac)throws IOException, InterruptedException { reader.initialize(is, tac); } @Override //every key:value from dataset is passed to mapper public boolean nextKeyValue() throws IOException, InterruptedException { // TODO Auto-generated method stub boolean gotNextKeyValue = reader.nextKeyValue(); if(gotNextKeyValue){ if(key==null){ key = new TitanicCustomKey(); } if(value == null){ value = new IntWritable(); } Text line = reader.getCurrentValue(); String[] tokens = line.toString().split(","); //As discussed earlier, we need 2nd and 5th columns passed to our custom key. //The value is set as ‘1‘ since we need to count the number of people. so need not assign value 1 in mapper key.setX(new String(tokens[1])); key.setY(new String(tokens[4])); value.set(new Integer(1)); } else { key = null; value = null; } return gotNextKeyValue; } @Override public void close() throws IOException { // TODO Auto-generated method stub reader.close(); } } <file_sep>package cards; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer; public class CardRecordCount{ private static class RecordMapper extends Mapper <LongWritable,Text,Text,IntWritable>{ public void map(LongWritable lineoffset, Text record, Context output)throws IOException, InterruptedException{ output.write(new Text("count"), new IntWritable(1)); } } private static class RecordReducer extends Reducer<Text,IntWritable,Text,IntWritable>{ public void reduce(Text key,Iterable<IntWritable> values, Context output)throws IOException, InterruptedException{ int sum = 0; for (IntWritable val : values) { sum += val.get(); } output.write(new Text("total counte \t"), new IntWritable(sum)); } } public static void main(String args[]) throws Exception{ // TODO Auto-generated method stub if(args.length <2) { System.err.println("Usage:<inputpath> <outputpath>"); System.exit(-1); } Configuration conf = new Configuration(); Job job = Job.getInstance(conf); job.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job.setMapperClass(RecordMapper.class); job.setReducerClass(RecordReducer.class); // user defined class for counting //job.setReducerClass(LongSumReducer.class); //inbuilt class for counting. //job.setNumReduceTasks(0); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }<file_sep>package FileSystemAPI; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; public class ListFiles { public static void main(String args[])throws Exception{ //pass "src/cards/" as command line arguments. String uri="hdfs://node2:10001/"; //args[0]; Configuration conf=new Configuration(); //convert path string from URI so that can manipulate with many inbuilt functions FileSystem fs=FileSystem.get(URI.create(uri),conf); Path path=new Path(uri); FileStatus[] status=fs.listStatus(path); // to show list of files in a directory Path[] paths=FileUtil.stat2Paths(status); for(Path p:paths){ System.out.println(p.toString()); } } } <file_sep>package cards; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer; public class CardCountBySuite { public static class Map extends Mapper<LongWritable,Text,Text,LongWritable>{ public void map(LongWritable key, Text value, Context output) throws IOException, InterruptedException{ output.write(new Text(value.toString().split("\\|")[1]), new LongWritable(1)); } } public static void main(String args[]) throws Exception{ if(args.length <2) { System.err.println("Usage:<inputpath> <outputpath>"); System.exit(-1); } Configuration conf=new Configuration(); Job job=Job.getInstance(conf); job.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); job.setMapperClass(Map.class); job.setReducerClass(LongSumReducer.class); //job.setPartitionerClass(HashPartitioner.class); //job.setNumReduceTasks(0); //job.setMapOutputKeyClass(Text.class); //job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job,new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } <file_sep>package Filtering; import java.io.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.CombineTextInputFormat; // it is in hadoop-mapreduce-client-core-2.7.0 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import NYSE.CustomKeyValue.*; import NYSE.AvgStockVolPerMonth.*; public class AvgStockVolMonthDriver extends Configured implements Tool{ public int run(String args[]) throws IOException, InterruptedException, ClassNotFoundException { if (args.length < 2) { System.err.println("Usage: wordcount <in> [<in>...] <out>"); System.exit(2); } Configuration conf=getConf(); Job job=Job.getInstance(conf,"NYSE average stock volume per month"); //job.getConfiguration().set("fs.file.impl", "WinLocalFileSystem"); //job.setJarByClass(getClass()); job.setJarByClass(NYSE.AvgStockVolPerMonth.AvgStockVolMonthDriver.class); job.setMapperClass(AvgStockMapperWithSetUp.class); //average of average is not right. so we define new combiner class rather reusing reducer task job.setCombinerClass(AvgStockVolMonthCombiner.class); //now check combiner output job.setReducerClass(AvgStockVolMonthReducer.class); job.setNumReduceTasks(4); // to check mapper output job.setMapOutputKeyClass(TextPair.class); job.setMapOutputValueClass(LongPair.class); job.setOutputKeyClass(TextPair.class); job.setOutputValueClass(LongPair.class); job.setInputFormatClass(CombineTextInputFormat.class); // just enable this if you have more number of small files to pack as one IS. It is in hadoop-mapreduce-client-core-2.7.0 CombineTextInputFormat.setMaxInputSplitSize(job, 64000000); // many files are put into 64 MB //job.setInputFormatClass(TextInputFormat.class); //job.setOutputFormatClass(TextOutputFormat.class); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); for (int i = 0; i < otherArgs.length - 1; ++i) { FileInputFormat.addInputPath(job, new Path(otherArgs[i])); } FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1])); /* FileInputFormat.addInputPath(job, new Path("D:/Eclipse Project/Practice/dataset/nyse_data/*.csv")); FileOutputFormat.setOutputPath(job, new Path("D:/Eclipse Project/Practice/output"));*/ return job.waitForCompletion(true) ? 0 : 1; } public static void main(String args[])throws Exception{ int exitCode=ToolRunner.run(new AvgStockVolMonthDriver(), args); System.exit(exitCode); } }
79468dbc7b86e5fad5698d7a57e1af46387a88e5
[ "Java" ]
18
Java
yadevi/MapReduce
9c7db8c295c700297f72150339274f5c19dd217f
85a5ca30941ded9793fd43f48df8637b32e0d963
refs/heads/master
<file_sep>from django.apps import AppConfig class LoginformConfig(AppConfig): name = 'Loginform' def ready(self): import Loginform.signals<file_sep>from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import CreateUserForm,Userupdateform,Userupdateprofile from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout # Create your views here. def index(request): if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') print(username) form.save() messages.SUCCESS = (request, 'Acount Created') print('user created') return redirect('/login') else : error = form.errors print(error.as_data) messages.info(request, error) # return redirect('/') # return render(request,'index.html',{'form':form,'error':error}) form = CreateUserForm() return render(request,'index.html',{'form':form}) def loginpage(request): ''' this function is of about Login page ''' if request.method == 'POST': ''' this block will check the POST request ''' # path = request.path print(request.POST['username']) username = request.POST['username'] password = request.POST['psw'] user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect('home') else: messages.info(request,'Username or Password is incorrect') # return render(request,'login.html') else: print('No Post request') return render(request,'login.html') def logoutuser(request): logout(request) return redirect('/login') @login_required def home(request): # if not request.user.is_authenticated: # return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) return render(request,'home.html') @login_required def profile(request): userform = Userupdateform() userprofile = Userupdateprofile() context = { 'user': Userupdateform, "profile": Userupdateprofile } # if not request.user.is_authenticated: # return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) return render(request,'profile.html',context)<file_sep>from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('signup',views.index,name='register'), path('login',views.loginpage,name='login'), path('',views.home,name='home'), path('profile',views.profile,name='profile'), path('logout',views.logoutuser,name='logout') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
7145378df543b73278d817388c2b131ed3a20b46
[ "Python" ]
3
Python
ShahzaibMinhaz/Django_project
046d54f46242c8d7e0ed0330d81487b23af0adc1
3524f93f6c60cab58feb39c56f90c090bbaaab13
refs/heads/master
<repo_name>ktl1111/blockbreaker<file_sep>/Block.java package com.vany; import java.awt.*; class Block extends Rectangle { private Image pic; int dx = 3; int dy = -3; Rectangle left, right; boolean destroyed = false; boolean powerup = false; Block(int a, int b, int w, int h, String s) { this.x = a; this.y = b; this.width = w; this.height = h; this.left = new Rectangle(a-1, b, 1, h); this.right = new Rectangle(a+w+1, b, 1, h); this.pic = Tools.getImage(s); } void draw(Graphics g, Component c){ if(!destroyed){ g.drawImage(pic, x, y, width, height, c); } } }
890b95f9de7ed0b6c95017c35caa328c0cf7412c
[ "Java" ]
1
Java
ktl1111/blockbreaker
704fcb26c923ff49d687a849bed43bdae7cbe980
59173763654b494a2a3f31c4fc9c97f948d4d870
refs/heads/master
<repo_name>fernandajofili/SistemaFaculdade2.0<file_sep>/Turma.java package classes; import java.util.ArrayList; import java.util.List; public class Turma { int idTurma, capacidade; Disciplina disciplina; Professor professor; List<Aluno> alunoTurmaLista = new ArrayList<>(); public Turma() { } public Turma(Disciplina disciplina, Professor professor) { this.disciplina = disciplina; this.professor = professor; } public Turma(int idTurma, int capacidade) { super(); this.idTurma = idTurma; this.capacidade = capacidade; } public int getIdTurma() { return idTurma; } public void setIdTurma(int idTurma) { this.idTurma = idTurma; } public int getCapacidade() { return capacidade; } public void setCapacidade(int capacidade) { this.capacidade = capacidade; } public Disciplina getDisciplina() { return disciplina; } public void setDisciplina(Disciplina disciplina) { this.disciplina = disciplina; } public Professor getProfessor() { return professor; } public void setProfessor(Professor professor) { this.professor = professor; } public List<Aluno> getAlunoTurmaLista() { return alunoTurmaLista; } public void setAlunoTurmaLista(List<Aluno> alunoTurmaLista) { this.alunoTurmaLista = alunoTurmaLista; } // STRING public String disciplinaCadastrada() { return "Disciplina cadastrada com sucesso!\n"; } public String disciplinaNaoCadastrada() { return "Disciplina não cadastrada. Cadastre uma.\n"; } public String alunoCadastrado() { return "Aluno cadastrado com sucesso!\n"; } public String professorCadastrado() { return "Professor cadastrado com sucesso!\n"; } public String professorNaoCadastrado() { return "Professor não cadastrado. Cadastre um.\n"; } public String professorRemovido() { return "Professor removido com sucesso!\n"; } public String turmaCadastrada() { return "Turma cadastrada com sucesso!\n"; } public String turmaNaoCadastrada() { return "Turma não cadastrada. Cadastre uma.\n"; } public String turmaJaCadastrada() { return "Turma já cadastrada.\n"; } public String turmaLotadaMensagem() { return "Turma lotada. Não é possível adicionar um aluno.\n"; } public String consultarTurma() { return "Não é possível consultar a turma.\n"; } public String infoAluno(int i) { return "ID: " + getAlunoTurmaLista().get(i).getId() + "\tNOME: " + getAlunoTurmaLista().get(i).getNome() + "\tUSER: " + getAlunoTurmaLista().get(i).getUser() + "\tPERÍODO: " + getAlunoTurmaLista().get(i).getPeriodo() + "\n"; } public String infoProfessor() { return "PROFESSOR: " + getProfessor().getId() + " - " + getProfessor().getNome(); } public String infoDisciplina() { return "DISCIPLINA: " + getDisciplina().getIdDisciplina() + " - " + getDisciplina().getNomeDisciplina() + "\n"; } public String infoTurma() { return "TURMA " + getIdTurma() + "\nCapacidade: " + getCapacidade() + "\n"; } public String infoTurmaCompleta() { if (getDisciplina() != null && getProfessor() != null) { return infoTurma() + infoDisciplina() + infoProfessor(); } else { if (getDisciplina() == null && getProfessor() != null) { return infoTurma() + "\nDISCIPLINA: não cadastrada.\t" + infoProfessor(); } else { if (getDisciplina() != null && getProfessor() == null) { return infoTurma() + infoDisciplina() + "\nPROFESSOR: não cadastrado.\n"; } else { return infoTurma() + "\nDISCIPLINA: não cadastrada.\nPROFESSOR: não cadastrado.\n"; } } } } // TURMA public boolean existeTurma() { if (getCapacidade() != 0) { return true; } else { return false; } } public boolean turmaLotada() { if (getCapacidade() > getAlunoTurmaLista().size()) { return false; } else { return true; } } // ALUNO public void cadastrarAluno(Aluno aluno) { this.alunoTurmaLista.add(aluno); } public int buscarAluno(String nomeAluno) { boolean encontrou = false; int i; for (i = 0; i < getAlunoTurmaLista().size(); i++) { if (getAlunoTurmaLista().get(i).getNome().equals(nomeAluno)) { encontrou = true; break; } else { encontrou = false; } } if (encontrou == false) { System.out.println("Aluno não encontrado.\n"); return i = -1; } else { return i; } } public String listarAlunosTurma() { StringBuilder sb = new StringBuilder(); if (alunoTurmaLista.size() > 0) { for (Aluno aluno : alunoTurmaLista) { sb.append(aluno.getId() + " - " + aluno.getNome() + "\n"); } return sb.toString(); } else { return "Nenhum aluno cadastrado."; } } public boolean removerAluno(String nomeAluno) { boolean removeu = false; if (!nomeAluno.isBlank()) { if (getAlunoTurmaLista().size() > 0) { for (int i = 0; i < getAlunoTurmaLista().size(); i++) { if (getAlunoTurmaLista().get(i).getNome().equals(nomeAluno)) { getAlunoTurmaLista().remove(i); removeu = true; System.out.println("Aluno removido com sucesso!"); break; } else { removeu = false; } } } else { System.out.println("Turma vazia."); } } if (removeu == false) { System.out.println("Aluno não encontrado"); } return removeu; } public void consultarAluno(String nomeAluno) { int i = buscarAluno(nomeAluno); if (i != -1) { System.out.println(infoAluno(i)); } } public boolean professorJaCadastrado() { if (this.professor == null) { return false; } else { return true; } } public String consultarProfessor() { if (professorJaCadastrado()) { return infoProfessor(); } else { return professorNaoCadastrado(); } } public String removerProfessor(String confirma) { if (confirma.toUpperCase().equals("S")) { if (professorJaCadastrado()) { setProfessor(null); return professorRemovido(); } else { return professorNaoCadastrado(); } } else { return ""; } } public boolean disciplinaJaCadastrada() { if (this.disciplina == null) { return false; } else { return true; } } public String consultarDisciplina() { if (disciplinaJaCadastrada()) { return infoDisciplina(); } else { return disciplinaNaoCadastrada(); } } } <file_sep>/RendimentoEscolar.java package classes; public class RendimentoEscolar { Aluno aluno; Disciplina disciplina; float nota1, nota2, nota3, notaProjeto; float []notasTrabalho = new float[3]; String []trabalhos = new String[3]; String projeto = ""; public RendimentoEscolar() { super(); } public RendimentoEscolar(Aluno aluno, Disciplina disciplina, float nota1, float nota2, float nota3) { super(); this.aluno = aluno; this.disciplina = disciplina; this.nota1 = nota1; this.nota2 = nota2; this.nota3 = nota3; } public RendimentoEscolar(Aluno aluno, Disciplina disciplina, float[] notasTrabalho, String[] trabalhos) { super(); this.aluno = aluno; this.disciplina = disciplina; this.notasTrabalho = notasTrabalho; this.trabalhos = trabalhos; } public RendimentoEscolar(Aluno aluno, Disciplina disciplina, float notaProjeto, String projeto) { super(); this.aluno = aluno; this.disciplina = disciplina; this.notaProjeto = notaProjeto; this.projeto = projeto; } public RendimentoEscolar(Aluno aluno, Disciplina disciplina, float nota1, float nota2, float nota3, float notaProjeto, float[] notasTrabalho, String[] trabalhos, String projeto) { super(); this.aluno = aluno; this.disciplina = disciplina; this.nota1 = nota1; this.nota2 = nota2; this.nota3 = nota3; this.notaProjeto = notaProjeto; this.notasTrabalho = notasTrabalho; this.trabalhos = trabalhos; this.projeto = projeto; } public Aluno getAluno() { return aluno; } public void setAluno(Aluno aluno) { this.aluno = aluno; } public Disciplina getDisciplina() { return disciplina; } public void setDisciplina(Disciplina disciplina) { this.disciplina = disciplina; } public float getNota1() { return nota1; } public void setNota1(float nota1) { this.nota1 = nota1; } public float getNota2() { return nota2; } public void setNota2(float nota2) { this.nota2 = nota2; } public float getNota3() { return nota3; } public void setNota3(float nota3) { this.nota3 = nota3; } public float getNotaProjeto() { return notaProjeto; } public void setNotaProjeto(float notaProjeto) { this.notaProjeto = notaProjeto; } public float[] getNotasTrabalho() { return notasTrabalho; } public void setNotasTrabalho(float[] notasTrabalho) { this.notasTrabalho = notasTrabalho; } public String[] getTrabalhos() { return trabalhos; } public void setTrabalhos(String[] trabalhos) { this.trabalhos = trabalhos; } public String getProjeto() { return projeto; } public void setProjeto(String projeto) { this.projeto = projeto; } }
c7e5e14f5052811f73cf349a34422a217450dcae
[ "Java" ]
2
Java
fernandajofili/SistemaFaculdade2.0
92f27b1990789d28fe44e88b3790d196234877d5
f1a17dff98fff10c30bfad45ade4779831d8782e
refs/heads/main
<file_sep>const config = { blockSize: 10, blockBorderWidth: 1, divider: 1, columns: 10, rows: 20, };
96f5129b4d1fdaf27d9e69b2f914726f9d3f2da0
[ "JavaScript" ]
1
JavaScript
Lcsunm/tetris
c8bbf628c89b0be57ff87ce95f31d665ec4aaccc
1dfd9663f86b53614f00f65ff7995e853147a61c
refs/heads/master
<repo_name>jefersonla/LABII-Listas<file_sep>/Lista_VII/INTERMLG.cpp #include <iostream> #include <queue> #include <list> #include <limits> #include <set> #include <cmath> #include <cstdio> #define MAX_NUM_VERTICES 1001 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* better find */ #define not_found_in(var) var.end() /* Max value between two vars */ #define max_2(var1, var2) (var1 > var2 ? var1 : var2) #define min_2(var1, var2) (var1 < var2 ? var1 : var2) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE std::numeric_limits<int>::max() /* Indice nulo */ #define NULO -1 // APENAS PARA PROPOSITOS DE DEBUG //#define DEBUG using namespace std; /* Estrutura do grafo - arestas e vertices */ int grafo[MAX_NUM_VERTICES][MAX_NUM_VERTICES]; pair<long double, long double> vertices[MAX_NUM_VERTICES]; /* Matrizes do Floyd Warshall */ long double dist[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int parente[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int pai[MAX_NUM_VERTICES] = { 0 }; /* Variaveis do programa */ int N, M; struct compare { bool operator ()(const pair<pair<int, int>, int>&i, const pair<pair<int, int>, int>&j){ return i.second <= j.second; }; }; /* Distância de u a v */ #define w(u, v) (dist[u][v]) /* Define a união dos parentes */ #define union(u, v) pai[u] = pai[v] /* Retorna o valor máximo do set */ #define max_value_set(XX) XX.rbegin()->second /* Procura o parente de um dado vértice */ int find_set(int v){ if(v != pai[v]) pai[v] = find_set(pai[v]); return pai[v]; } /* Arvore geradora minima do Kruskal */ set<pair<pair<int,int>,long double>, compare> A; long double Kruskal(){ /* Pair de cordenadas e custo modelo: <<u,v>, custo>, e ordenamos o mesmo pelo custo */ set<pair<pair<int,int>,long double>, compare> Q; /* Insere no set a lista de pares e custo */ for(int u = 1; u <= N; u++){ for(int v = 1; v <= N; v++){ if(grafo[u][v] != 0){ Q.insert(make_pair(make_pair(u, v), w(u,v))); #ifdef DEBUG cout << "u -- " << u << " | v -- " << v << " | w -- " << w(u,v) << endl; #endif } } } #ifdef DEBUG /* Imprime todos os nós - deve estar ordenado pelo peso */ cout << "Todas arestas" << endl; for_each(it, Q){ int u = it->first.first; int v = it->first.second; int w = it->second; cout << "u " << u << " v " << v << " w " << w << endl; } #endif /* While n of nodes is different of 0 */ int n_nodes = 0; long double soma = 0; for_each(it, Q){ /* Pega os pares u e v da lista */ int u = it->first.first; int v = it->first.second; /* Executa o find_set para os nós u e v */ int find_set_u = find_set(u); int find_set_v = find_set(v); /* Se o pai de u for diferente do pai de v */ if(find_set_u != find_set_v){ A.insert(*it); soma += it->second; union(find_set_u, find_set_v); } /* Se já temos nossa arvore geradora minima paramos a execução */ if(A.size() == (N - 1)){ break; } } #ifdef DEBUG /* Imprime todos os nós da nossa arvore geradora minima */ cout << "Arvore geradora minima" << endl; for_each(it, A){ int u = it->first.first; int v = it->first.second; int w = it->second; cout << "u " << u << " v " << v << " w " << w << endl; } #endif return soma; } int main(){ long double x, y; int z = 1; while(true){ cin >> N; if(N == 0) break; /* Inicalização do grafo */ A.clear(); for(int i = 1; i <= N; i++){ /* Arestas & Distâncias & Caminho */ for(int j = 1; j <= N; j++){ dist[i][j] = INFINITY_VALUE; grafo[i][j] = 0; parente[i][j] = NULO; } /* Distâncias & Parentes na Diagonal */ dist[i][i] = 0; parente[i][i] = i; pai[i] = i; } /* Lê as arestas */ for(int i = 1; i <= N; i++){ /* Pega os valores de A e B*/ cin >> x; cin >> y; vertices[i] = make_pair(x, y); } for(int u = 1; u <= N; u++){ for(int v = 1; v <= N; v++){ /* Como temos um grafo não direcionado os dois caminhos são válidos */ grafo[u][v] += 1; grafo[v][u] += 1; /* Cordenadas de u */ long double xu = vertices[u].first; long double yu = vertices[u].second; /* Coordenadas de v */ long double xv = vertices[v].first; long double yv = vertices[v].second; /* Custo de u a v atual for maior que o custo novo substitui */ long double w_u_v = sqrt(pow(xu-xv, 2) + pow(yu-yv, 2)); dist[u][v] = w_u_v; dist[v][u] = w_u_v; /* Menor caminho de u a v */ parente[u][v] = u; parente[v][u] = v; } } /* Iremos construir uma arvore geradora minima usando Kruskal, e retornar o custo do menor caminho entre todos os nós */ long double retorno = Kruskal(); /* Não estamos interessado no custo total mas sim no menor valor que garante que haja um caminho direto ou indireto entre todos os nós. Se só existe um nó então retornamos 0, caso exista mais que um retornamos o valor máximo da nossa Arvore Geradora Minima no caso o set de A */ if(N == 1){ printf("%.4f\n", 0.0); } else{ printf("%.4Lf\n", max_value_set(A)); } } return 0; } <file_sep>/Lista_VI/PEDAGIO.cpp #include <iostream> #include <queue> #include <limits> #define INFINITY_VALUE std::numeric_limits<int>::max() #define MAX_NUM_VERTICES 51 #define UNDEFINED_VERTICE -1 /* Como a distância é fixa entre os nós distancia de u a v é 1 */ #define distancia(u,v) 1 using namespace std; typedef struct VerticeStruct{ int num; int distancia; int anterior; } Vertice; int grafo[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{0}}; int menor_caminho[MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; int C, L, E, P; void dijkstra(){ /* Criamos uma fila de prioridades */ priority_queue<pair<int, int> > Q; /* Adicionamos o vértice de origem */ Q.push(make_pair(0, L)); /* Enquanto nossa fila não estiver vazia */ while(!Q.empty()){ /* Extraimos o menor vertice de nossa fila */ Vertice *u = &vertices[Q.top().second]; Q.pop(); /* Para cada vizinho v de u */ for(int i = 1; i <= C; i++){ Vertice *v = &vertices[i]; /* Se o vertice u é vizinho de v */ if(grafo[u->num][v->num] > 0){ /* Some a distancia de u com a distancia de u a v como temos que a distância é fixa, ela é igual a 1 */ int alternativa = u->distancia + distancia(u, v); /* Se o novo caminho for o melhor caminho armazene ele */ if (alternativa < v->distancia){ v->distancia = alternativa; v->anterior = u->num; Q.push(make_pair(v->distancia, v->num)); } } } } } int main(){ int K = 1; do{ /* Lê os quatro inteiros */ cin >> C; cin >> E; cin >> L; cin >> P; /* Se condição de parada de execução for atingida */ if((C == 0) && (E == 0) && (L == 0) && (P == 0)){ break; } /* Inicialização dos vertices e arestas */ for (int i = 1; i <= C; i++){ for (int j = 1; j <= C; j++){ grafo[i][j] = 0; } vertices[i].num = i; vertices[i].distancia = INFINITY_VALUE; vertices[i].anterior = UNDEFINED_VERTICE; } /* Sabemos que L é a cidade aonde estamos logo inicializamos esta distância */ vertices[L].distancia = 0; /* Lê toda a entrada */ for(int i = 0; i < E; i++){ int O, D; cin >> O; cin >> D; grafo[O][D] += 1; grafo[D][O] += 1; } /* Agora iremos encontrar o melhor caminho de L até todos os nós adjacentes a L */ dijkstra(); if(K > 1){ cout << endl; } cout << "Teste " << K << endl; /* Após descobrir o melhor caminho a partir de L iremos varrer todos os vértices e printar o menor caminho ou seja o caminho com no máximo P de distância */ bool primeiro_elemento = true; for(int i = 1; i <= C; i++){ Vertice *v = &vertices[i]; if(v->num != L && v->distancia <= P){ if(primeiro_elemento){ cout << v->num; primeiro_elemento = false; } else{ cout << " " << v->num; } } } /* Quebra a linha do caminho apresentado */ cout << endl; K += 1; } while((C != 0) && (E != 0) && (L != 0) && (P != 0)); return 0; }<file_sep>/Lista_VI/DUENDE.cpp #include <bits/stdc++.h> #define INFINITY_VALUE std::numeric_limits<int>::max() #define MAX_NUM_VERTICES (10 * 10 + 1) #define UNDEFINED_VERTICE -1 /* Como a distância é fixa entre os nós distancia de u a v é 1 */ #define distancia(u,v) 1 using namespace std; typedef struct VerticeStruct{ int num; int distancia; int anterior; } Vertice; /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) int grafo[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{0}}; int menor_caminho[MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; int N, L, M, T; list<int> saidas; int mapa[11][11] = {{ 0 }}; void dijkstra(){ /* Criamos uma fila de prioridades */ priority_queue<pair<int, int> > Q; /* Adicionamos o vértice de origem */ Q.push(make_pair(0, L)); /* Enquanto nossa fila não estiver vazia */ while(!Q.empty()){ /* Extraimos o menor vertice de nossa fila */ Vertice *u = &vertices[Q.top().second]; Q.pop(); /* Para cada vizinho v de u */ for(int i = 0; i < T; i++){ Vertice *v = &vertices[i]; /* Se o vertice u é vizinho de v */ if(grafo[u->num][v->num] > 0){ /* Some a distancia de u com a distancia de u a v como temos que a distância é fixa, ela é igual a 1 */ int alternativa = u->distancia + distancia(u, v); /* Se o novo caminho for o melhor caminho armazene ele */ if (alternativa < v->distancia){ v->distancia = alternativa; v->anterior = u->num; Q.push(make_pair(v->distancia, v->num)); } } } } } int main(){ /* Lê os quatro inteiros */ cin >> N; cin >> M; /* Total de vertices */ T = N * M; /* Inicialização dos vertices e arestas */ saidas.clear(); for (int i = 0; i < T; i++){ for (int j = 0; j < T; j++){ grafo[i][j] = 0; } vertices[i].num = i; vertices[i].distancia = INFINITY_VALUE; vertices[i].anterior = UNDEFINED_VERTICE; } /* Lê todo o mapa */ for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ int tipo; cin >> tipo; mapa[i][j] = tipo; if(tipo == 3){ L = (i * M) + j; } else if(tipo == 0){ saidas.push_back((i * M) + j); } } } /* Constroi o grafo com o mapa recebido */ for(int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ if(mapa[i][j] != 2){ int lugar_atual = (i * M) + j; if((i + 1) < N && mapa[i + 1][j] != 2){ grafo[lugar_atual][lugar_atual + M] = 1; grafo[lugar_atual + M][lugar_atual] = 1; } if((j + 1) < M && mapa[i][j + 1] != 2){ grafo[lugar_atual][lugar_atual + 1] = 1; grafo[lugar_atual + 1][lugar_atual] = 1; } } } } /* Sabemos que L é a cidade aonde estamos logo inicializamos esta distância */ vertices[L].distancia = 0; /* Agora iremos encontrar o melhor caminho de L até todos os nós adjacentes a L */ dijkstra(); #ifdef DEBUG cout << endl; for(int i = 0; i < T; i++){ for(int j = 0; j < T; j++){ printf("%5d", grafo[i][j]); } cout << endl; } cout << endl << endl; for(int i = 0; i < T; i++){ printf("%s%d: %d\n", ((find(saidas.begin(), saidas.end(), i) != saidas.end()) ? "*" : ""), i, vertices[i].distancia); } cout << endl; #endif /* Após descobrir o melhor caminho a partir de L iremos varrer todos as saídas possíveis e printar a distância para o melhor caminho */ int menor_caminho = INFINITY_VALUE; for_each(it, saidas){ Vertice *v = &vertices[*it]; if(v->num != L && v->distancia <= menor_caminho){ menor_caminho = v->distancia; } } /* Imprime o resultado */ cout << menor_caminho << endl; return 0; }<file_sep>/Lista_VIII/MINIMO.cpp #include <bits/stdc++.h> using namespace std; /* Constantes do algoritmo */ #define MAX_NUM_VERTICES 120 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE 9999999 /* Indice nulo */ #define NULO -1 /* Ativar apenas durante o DEBUG */ //#define DEBUG typedef struct VerticeStruct{ int num; int cor; int d; int tempo_s; int tempo_f; struct VerticeStruct *anterior; } Vertice; int N, M; #define MAX_NUM_VERTICES 120 int distk[MAX_NUM_VERTICES][MAX_NUM_VERTICES][MAX_NUM_VERTICES]; /* Floyd Warshall */ void FloydWarshall(){ /* Executa o algoritmo de Floyd Warshall e computa as distancias */ for(int i = 1; i <= N; i++){ for(int j = 0; j < N; j++){ for(int k = 0; k < N; k++){ distk[i][j][k] = min(distk[i - 1][j][k], distk[i - 1][j][i - 1] + distk[i - 1][i - 1][k]); } } } } int main(){ int inst = 1; while(true){ /* Le os valores */ if(scanf("%d %d", &N, &M) == EOF){ break; } /* Inicializa os valores da distancia */ for(int i = 0; i <= N; i++){ for(int j = 0; j <= N; j++){ for(int k = 0; k <= N; k++){ if(j == k){ distk[i][j][k] = 0; } else{ distk[i][j][k] = INFINITY_VALUE; } } } } /* Le as arestas */ for(int i = 0; i < M; i++){ int u, v, w; cin >> u >> v >> w; distk[0][u - 1][v - 1] = min(distk[0][u - 1][v - 1], w); } /* Executa Floyd Warshal modificado para salvar as instancias k */ FloydWarshall(); int n_testes; cin >> n_testes; cout << "Instancia "<< inst << endl; /* Executa os testes */ for(int i = 0; i < n_testes; i++){ int u, v, t; cin >> u >> v >> t; if(distk[t][u - 1][v - 1] == INFINITY_VALUE){ cout << "-1" << endl; } else{ cout << distk[t][u - 1][v - 1] << endl; } } cout << endl; inst++; } return 0; }<file_sep>/Lista_VI/ENERGIA.cpp #include <iostream> #include <cstdlib> #include <list> #define MAX_VERTICES 101 #define BRANCO 0 #define CINZA 1 #define PRETO 2 using namespace std; typedef struct VerticeStruct{ int cor; int tempo_d; int tempo_f; int num; struct VerticeStruct *pai; } Vertice; /* Tempo Global */ int tempo = 0; /* Numero de Vertices */ int E; /* Numero de visitas */ int comp_conexa; /* Grafo & Vertices */ /* Matriz de Adjacência */ int grafo[MAX_VERTICES][MAX_VERTICES] = {{ 0 }}; /* Vertices */ Vertice vertices[MAX_VERTICES]; void DFS_VISIT(Vertice *u){ int i; Vertice *v; /* Atualiza os valores do tempo e do vertice */ tempo += 1; u->tempo_d = tempo; u->cor = CINZA; /* Para cada vertice adjacente ao vertice atual */ for(i = 1; i <= E; i++){ /* Pula para o próxima adjacência possivel */ if(grafo[u->num][i] == 0) continue; /* Vertice adjacente */ v = &vertices[i]; /* Se o vertice ainda não tiver sido visitado */ if(v->cor == BRANCO){ v->pai = u; DFS_VISIT(v); } } /* Finaliza a busca em profundidade */ u->cor = PRETO; tempo += 1; u->tempo_f = tempo; } int main(){ int i, j, k; int L, v1, v2; int test_num = 1; /* Executa enquanto E e L forem diferentes de 0 */ do{ /* Recupera E e L */ cin >> E; cin >> L; /* Para a execução se E e L são iguais a 0*/ if( E == 0 && L == 0 ) break; /* Inicializa a matriz de adjacência e os vertices*/ for(i = 1; i <= E; i++){ for(j = 1; j <= E; j++){ /* Matriz de adjacência */ grafo[i][j] = 0; } /* Vertices */ vertices[i].cor = BRANCO; vertices[i].pai = NULL; vertices[i].num = i; } /* Constrói a matriz de adjacências */ for(i = 0; i < L; i++){ /* Pega o vertice */ cin >> v1; cin >> v2; /* Adiciona uma adjacência entre os dois vértices */ grafo[v1][v2] += 1; grafo[v2][v1] += 1; } /* Executa uma busca em profundidade */ /* Inicializa o tempo */ tempo = 0; /* Inicializa as componentes conexas */ comp_conexa = 0; /* Para cada vertice se o vertice ainda não tiver sido visitado executa uma busca em profundidade */ for(int i = 1; i <= E; i++){ if(vertices[i].cor == BRANCO){ DFS_VISIT(&vertices[i]); comp_conexa += 1; } } /* Se este não for o primeiro teste imprima uma quebra de linha */ if(test_num > 1){ cout << endl; } /* Imprime o numero do teste */ cout << "Teste " << test_num << endl; /* Se o número de visitas for igual ao número de vértices, temos ao menos um caminho entre todos eles */ if(comp_conexa == 1){ cout << "normal" << endl; } else { cout << "falha" << endl; } /* Incrementa o numero de execuções */ test_num += 1; } while(E != 0 && L != 0); return EXIT_SUCCESS; } <file_sep>/Lista_II/BSEARCH1.cpp #include <bits/stdc++.h> #define MAX_SIZE_ARRAY 100001 using namespace std; long long N; long long vetor[MAX_SIZE_ARRAY] = { 0 }; long long binary_serch(long long valor){ long long esquerda = 0; long long direita = N - 1; long long meio = 0; while(esquerda <= direita){ meio = esquerda + (direita - esquerda) / 2; if(vetor[meio] == valor){ break; } else if(vetor[meio] > valor){ direita = meio - 1; } else{ esquerda = meio + 1; } } if(vetor[meio] == valor){ for(int i = meio; i >= 0; i--){ if(i == 0 && vetor[0] == valor){ return 0; } else if(i > 0 && vetor[i - 1] != valor){ return i; } } } return -1; } int main(){ long long Q; scanf("%lld %lld", &N, &Q); for(long long i = 0; i < N; i++){ scanf("%lld", &vetor[i]); } for(long long i = 0; i < Q; i++){ long long valor; scanf("%lld", &valor); printf("%lld\n", binary_serch(valor)); } return 0; }<file_sep>/Lista_II/CARTEI14.cpp #include <bits/stdc++.h> #define MAX_SIZE_ARRAY 45001 using namespace std; int N; int vetor[MAX_SIZE_ARRAY] = { 0 }; int binary_serch(int esquerda, int direita, int valor){ while(esquerda <= direita){ int meio = esquerda + (direita - esquerda) / 2; if(vetor[meio] == valor){ return meio; } else if(vetor[meio] > valor){ direita = meio - 1; } else{ esquerda = meio + 1; } } return -1; } int main(){ int M; scanf("%d %d", &N, &M); for(int i = 0; i < N; i++){ scanf("%d", &vetor[i]); } int atual = 0; int soma = 0; for(int i = 0; i < M; i++){ int valor; scanf("%d", &valor); int proxima_casa = binary_serch(0, N-1, valor); soma += proxima_casa > atual ? (proxima_casa - atual) : (atual - proxima_casa); //printf("%d - %d == %d\n", atual, proxima_casa, proxima_casa > atual ? (proxima_casa - atual) : (atual - proxima_casa)); atual = proxima_casa; } printf("%d\n", soma); return 0; }<file_sep>/README.md # LABII-Listas Listas de Laboratório de programação II - MATA 80 / UFBA <file_sep>/Lista_VI/ORKUT.cpp #include <iostream> #include <list> #include <queue> #include <map> #include <set> /* Constantes do algoritmo */ #define MAX_NUM_VERTICES 300 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* better find */ #define not_found_in(var) var.end() /* Max value between two vars */ #define max(var1, var2) (var1 > var2 ? var1 : var2) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE std::numeric_limits<int>::max() /* Ativar apenas durante o DEBUG */ //#define DEBUG using namespace std; typedef struct VerticeStruct{ int num; int cor; int d; int tempo_s; int tempo_f; struct VerticeStruct *anterior; } Vertice; /* Estrutura do grafo - arestas e vertices */ int saida[MAX_NUM_VERTICES]; int dependecia[MAX_NUM_VERTICES]; list<int> grafo[MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; /* Tempo Global */ int tempo; /* Variaveis do programa */ int N, M; /* Mapeamento dos vertices com string */ map<string, int> nome_vertices; map<int, string> id_vertices; /* Verifica a existência de dependecia */ #define nao_tem_dependecia(var) (dependecia[var] == 0) /* Ordena tarefas */ int OrdenacaoTopologica(){ /* Criamos uma fila de prioridades */ set<int> Q; /* Items ordenados */ int qtd_itens_ordenados = 0; /* Enfileiramos todos os valores que não tem precedência */ for(int i = 1; i <= N; i++){ if(nao_tem_dependecia(i)){ Q.insert(i); } } /* Enquanto a fila não estiver vazia */ while(!Q.empty()){ Vertice *u = &vertices[*(Q.begin())]; Q.erase(Q.begin()); #ifdef DEBUG cout << u->num << " "; #endif /* Para cada vértice adjacente a u */ for_each(it, grafo[u->num]){ Vertice *v = &vertices[*it]; dependecia[v->num] -= 1; if(nao_tem_dependecia(v->num)){ Q.insert(v->num); } } /* Após modificarmos a precedência dos nós adjacentes e empilharmos os que não tinham dependencia */ saida[qtd_itens_ordenados] = u->num; qtd_itens_ordenados += 1; } return qtd_itens_ordenados; } int main(){ int z = 1; do{ /* Lê as entradas */ cin >> N; /* Se condição de parada da aplicação for atingida */ if(N == 0) break; /* Inicalização do grafo */ nome_vertices.clear(); id_vertices.clear(); tempo = 0; for(int i = 1; i <= N; i++){ /* Vertices */ vertices[i].cor = BRANCO; vertices[i].num = i; vertices[i].anterior = NULL; /* Dependencias */ dependecia[i] = 0; /* Resposta */ saida[i] = 0; /* Valor de cada vertice */ /* Inicializa a chave se a mesma for nova na tabela de simbolos */ string amigo; cin >> amigo; nome_vertices[amigo] = i; id_vertices[i] = amigo; #ifdef DEBUG cout << ">>> " << amigo << " ID " << nome_vertices[amigo] << endl; #endif /* Arestas */ grafo[i].clear(); } /* Lê as arestas */ for(int i = 0; i < N; i++){ string amigo; int n_amigos; /* Pega o nome de cada amigo e a lista de amigos desse amigo */ cin >> amigo; cin >> n_amigos; /* Associa o valor da string a um numero inteiro qualquer */ int id_amigo = nome_vertices[amigo]; #ifdef DEBUG cout << "amigo = " << amigo << endl; cout << "id_amigo = " << id_amigo << " id_preador = " << id_predador << endl; #endif /* Como "ser amigo" é direcional */ for(int j = 0; j < n_amigos; j++){ string amigo_do_amigo; cin >> amigo_do_amigo; int id_amigo_do_amigo = nome_vertices[amigo_do_amigo]; grafo[id_amigo_do_amigo].push_back(id_amigo); dependecia[id_amigo] += 1; } } /* Tenta ordenar as tarefas */ int qtd_tarefas_ordenadas = OrdenacaoTopologica(); if(z > 1){ cout << '\n'; } cout << "Teste " << z << '\n'; /* Se a qtd de amigos ordenadas for igual ao total de nós imprimiremos a sequencia */ if(qtd_tarefas_ordenadas == N){ for(int i = 0; i < N; i++){ if(i > 0){ cout << ' '; } cout << id_vertices[saida[i]]; } } else{ /* Caso contrário imprimimos que não é possível */ cout << "impossivel"; } cout << '\n'; z += 1; }while(true); return 0; } <file_sep>/Lista_III/EELCS.cpp #include <bits/stdc++.h> #define MAX_STRING_SIZE 5001 #define max(A, B) (A > B ? A : B) using namespace std; char str1[MAX_STRING_SIZE]; char str2[MAX_STRING_SIZE]; int lcs_matrix_1[MAX_STRING_SIZE + 1] = { 0 }; int lcs_matrix_2[MAX_STRING_SIZE + 1] = { 0 }; int *lcs_previous_matrix; int *lcs_actual_matrix; int main(){ int lcs; scanf("%s%*c", str1); scanf("%s%*c", str2); int size_str1 = strlen(str1); int size_str2 = strlen(str2); // for(int i = 0, j = size_str1 - 1; i < size_str1; i++, j--){ // str2[j] = str1[i]; // } int z; for(int i = 1; i <= size_str1; i++){ if(i % 2){ lcs_previous_matrix = lcs_matrix_1; lcs_actual_matrix = lcs_matrix_2; } else{ lcs_previous_matrix = lcs_matrix_2; lcs_actual_matrix = lcs_matrix_1; } for(int j = 1; j <= size_str2; j++){ if(str1[i - 1] == str2[j - 1]){ lcs_actual_matrix[j] = lcs_previous_matrix[j - 1] + 1; } else{ lcs_actual_matrix[j] = max( lcs_previous_matrix[j], lcs_actual_matrix[j - 1]); } } } lcs = lcs_actual_matrix[size_str2]; printf("%d\n", lcs); return EXIT_SUCCESS; }<file_sep>/Lista_IX/MANUT.cpp #include <iostream> #include <list> #include <queue> #include <limits> /* Constantes do algoritmo */ #define MAX_NUM_VERTICES 450 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* better find */ #define not_found_in(var) var.end() /* Max value between two vars */ #define max_2(var1, var2) (var1 > var2 ? var1 : var2) /* Min value between two vars */ #define min_2(var1, var2) (var1 < var2 ? var1 : var2) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE std::numeric_limits<int>::max() /* Ativar apenas durante o DEBUG */ //#define DEBUG using namespace std; typedef struct VerticeStruct{ int num; int cor; int d; int low; int tempo_f; bool corte; struct VerticeStruct *anterior; } Vertice; /* Estrutura do grafo - arestas e vertices */ list<int> grafo[MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; /* Tempo Global */ int tempo; /* Variaveis do programa */ int N, M; void printaVazio(int qtd){ for(int i = 0; i < qtd; i++){ cout << " "; } } int root; int root_n; /* Visita os nós adjancentes, utilizando busca em profundidade */ void DFS_visit(Vertice *u){ /* Atualiza o valor do tempo e indica que está sendo visitado */ u->d = tempo; u->low = tempo; tempo += 1; u->cor = CINZA; /* Para cada vértice adjacente a u */ for_each(it, grafo[u->num]){ Vertice *v = &vertices[*it]; /* Caso ele seja branco */ if(v->cor == BRANCO){ /* Se for nó de raiz */ if(u->num == root){ root_n += 1; } v->anterior = u; DFS_visit(v); /* Verifica se temos uma aresta de corte e indica que são vertices de corte */ if(v->low >= u->d){ u->corte = true; #ifdef DEBUG cout << "ACHOU UM PONTO DE ARTICULACAO " << u->num << endl; #endif } u->low = min_2(u->low, v->low); } else if(u->anterior != v){ u->low = min(u->low, v->d); } } /* Finaliza a busca em profundidade do nó atual */ u->cor = PRETO; } int main(){ int z = 1; do{ /* Lê as entradas */ cin >> N; cin >> M; /* Se condição de parada da aplicação for atingida */ if(N == 0 && M == 0) break; /* Inicalização do grafo */ tempo = 0; root = 1; root_n = 0; for(int i = 1; i <= N; i++){ /* Vertices */ vertices[i].cor = BRANCO; vertices[i].num = i; vertices[i].low = 0; vertices[i].d = 0; vertices[i].anterior = NULL; vertices[i].corte = false; /* Arestas */ grafo[i].clear(); } /* Lê as arestas */ for(int i = 0; i < M; i++){ int X; int Y; cin >> X; cin >> Y; /* Adicionamos a ida e a volta para o vértice adjacente já que temos um grafo não direcionado */ grafo[X].push_back(Y); grafo[Y].push_back(X); } /* Executa uma DFS */ /* Iremos contar o tamanho de cada ciclo e armazenar o valor do ciclo maior */ for(int i = 1; i <= N; i++){ if(vertices[i].cor == BRANCO){ DFS_visit(&vertices[i]); } } /* Para o no raiz ser nó de corte ele precisa ter mais de 1 filho */ vertices[root].corte = (root_n > 1); if(z > 1){ cout << '\n'; } /* Imprime os vertices de corte */ cout << "Teste " << z << '\n'; int k = 0; for(int u = 1; u <= N; u++){ Vertice *v = &vertices[u]; if(v->corte){ if(k > 0){ cout << ' '; } k += 1; cout << v->num; } } if(k == 0){ cout << "nenhum"; } cout << '\n'; /* Contador de número de testes */ z += 1; }while(true); return 0; } <file_sep>/Lista_VI/IREVIR.cpp #include <iostream> #include <stack> #include <list> #define MAX_NUM_VERTICES 2200 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) // APENAS PARA PROPOSITOS DE DEBUG //#define DEBUG using namespace std; typedef struct VerticeStruct{ int num; int cor; int tempo_f; int tempo_s; // Ou d struct VerticeStruct *anterior; } Vertice; list<int> grafo[MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; /* Grafo transposto */ list<int> gr[MAX_NUM_VERTICES]; /* Tempo Global */ int tempo; /* Variaveis do programa */ int N, M; /* Pilha com a ordem de visitação */ stack<int> Q; /* Contador de SCC */ int scc_count; /* Visita os nós adjancentes, utilizando busca em profundidade */ void DFS_visit(Vertice V[MAX_NUM_VERTICES], Vertice *u){ /* Atualiza o valor do tempo e indica que está sendo visitado */ tempo += 1; u->tempo_s = tempo; u->cor = CINZA; #ifdef DEBUG cout << u->num << " "; #endif /* Para cada vértice adjacente a u */ for_each(it, gr[u->num]){ Vertice *v = &V[*it]; /* Se o vertice ainda não tiver sido visitado */ if(v->cor == BRANCO){ v->anterior = u; DFS_visit(V, v); } } /* Finaliza a busca em profundidade do nó atual */ u->cor = PRETO; tempo += 1; u->tempo_f = tempo; } /* Visita os nós adjancentes, utilizando busca em profundidade */ void DFS_visit_ordem(Vertice *u){ /* Atualiza o valor do tempo e indica que está sendo visitado */ tempo += 1; u->tempo_s = tempo; u->cor = CINZA; /* Para cada vértice adjacente a u */ for_each(it, grafo[u->num]){ Vertice *v = &vertices[*it]; /* Se o vertice ainda não tiver sido visitado */ if(v->cor == BRANCO){ v->anterior = u; DFS_visit_ordem(v); } } /* Finaliza a busca em profundidade do nó atual */ u->cor = PRETO; tempo += 1; u->tempo_f = tempo; /* Todos os nós que são acessiveis por u serão processados nesse momento */ Q.push(u->num); } /* Computa os SCC ou seja os Strongly Conected Components do grafo global */ void SCC_kosaraju(){ /* Toda vez que executarmos um DFS teremos que zerar o contador */ tempo = 0; /* Executa uma DFS */ /* Para cada vertice se o vertice ainda não tiver sido visitado executa uma busca em profundidade e computa seu tempo final de execução */ for(int i = 1; i <= N; i++){ if(vertices[i].cor == BRANCO){ DFS_visit_ordem(&vertices[i]); } } /* Cria um grafo transposto ou reverso */ Vertice V[MAX_NUM_VERTICES]; /* Inicializamos os vertices V de gr */ for(int i = 1; i <= N; i++){ V[i].cor = BRANCO; V[i].anterior = NULL; V[i].num = i; } /* Enquanto Q não estiver vazio */ tempo = 0; while(!Q.empty()){ Vertice *u = &V[Q.top()]; Q.pop(); /* Se o vertice não tiver sido visitado ainda */ if(u->cor == BRANCO){ DFS_visit(V, u); /* Incrementa o numero de SCC */ scc_count += 1; #ifdef DEBUG cout << endl; #endif } } } int main(){ do{ /* Lê as entradas */ cin >> N; cin >> M; /* Se condição de parada da aplicação for atingida */ if(N == 0 && M == 0) break; /* Inicalização do grafo */ scc_count = 0; for(int i = 1; i <= N; i++){ /* Vertices */ vertices[i].cor = BRANCO; vertices[i].anterior = NULL; vertices[i].num = i; /* Arestas */ gr[i].clear(); grafo[i].clear(); } /* Lê as arestas */ for(int i = 0; i < M; i++){ int V, W, P; cin >> V; cin >> W; cin >> P; /* Se o nó tiver apenas o caminho de ida */ grafo[V].push_back(W); /* Matriz transposta */ gr[W].push_back(V); /* Caso o mesmo tenha também a volta -- grafo direcionado */ if(P == 2){ grafo[W].push_back(V); gr[V].push_back(W); } } /* Executamos uma */ SCC_kosaraju(); /* Se tivermos apenas uma SCC então nosso grafo é fortemente conectado ou SCC */ cout << (scc_count == 1 ? "1" : "0") << endl; #ifdef DEBUG cout << "SCC = " << scc_count << endl; #endif }while(N != 0 && M != 0); return 0; } <file_sep>/Lista_VII/REDOTICA.cpp #include <iostream> #include <queue> #include <list> #include <limits> #include <set> #define MAX_NUM_VERTICES 101 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* better find */ #define not_found_in(var) var.end() /* Max value between two vars */ #define max_2(var1, var2) (var1 > var2 ? var1 : var2) #define min_2(var1, var2) (var1 < var2 ? var1 : var2) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE std::numeric_limits<int>::max() /* Indice nulo */ #define NULO -1 // APENAS PARA PROPOSITOS DE DEBUG //#define DEBUG using namespace std; typedef struct VerticeStruct{ int num; int cor; struct VerticeStruct *anterior; } Vertice; /* Estrutura do grafo - arestas e vertices */ int grafo[MAX_NUM_VERTICES][MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; /* Matrizes do Floyd Warshall */ int dist[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int custo[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int parente[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int pai[MAX_NUM_VERTICES] = { 0 }; /* Variaveis do programa */ int N, M; /* Floyd Warshall */ void FloydWarshall(){ /* Executa o algoritmo de Floyd Warshall e computa as distancias */ for(int k = 1; k <= N; k++){ for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if( dist[i][k] != INFINITY_VALUE && dist[k][j] != INFINITY_VALUE && (dist[i][k] + dist[k][j] < dist[i][j])){ dist[i][j] = dist[i][k] + dist[k][j]; parente[i][j] = k; } } } } #ifdef DEBUG for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if (dist[i][j] == INFINITY_VALUE){ printf("%7s", "INF"); } else{ printf ("%7d", dist[i][j]); } } cout << '\n'; } cout << '\n'; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if (parente[i][j] == NULO){ printf("%7s", "NIL"); } else{ printf ("%7d", parente[i][j]); } } cout << '\n'; } cout << '\n'; #endif } struct compare { bool operator ()(const pair<pair<int, int>, int>&i, const pair<pair<int, int>, int>&j){ return i.second <= j.second; }; }; struct compare2 { bool operator ()(const pair<pair<int, int>, int>&i, const pair<pair<int, int>, int>&j){ if(i.first.first != j.first.first) return (i.first.first < j.first.first); return (i.first.second < j.first.second); }; }; /* Distância de u a v */ #define w(u, v) (dist[u][v]) /* Define a união dos parentes */ #define union(u, v) pai[u] = pai[v] /* Procura o parente de um dado vértice */ int find_set(int v){ if(v != pai[v]) pai[v] = find_set(pai[v]); return pai[v]; } /* Arvore geradora minima do Kruskal */ set<pair<pair<int,int>,int>, compare2> A; int Kruskal(){ /* Pair de cordenadas e custo modelo: <<u,v>, custo>, e ordenamos o mesmo pelo custo */ set<pair<pair<int,int>,int>, compare> Q; /* Insere no set a lista de pares e custo */ for(int u = 1; u <= N; u++){ for(int v = 1; v <= N; v++){ if(grafo[u][v] != 0){ Q.insert(make_pair(make_pair(u, v), w(u,v))); #ifdef DEBUG cout << "u -- " << u << " | v -- " << v << " | w -- " << w(u,v) << endl; #endif } } } #ifdef DEBUG /* Imprime todos os nós - deve estar ordenado pelo peso */ cout << "Todas arestas" << endl; for_each(it, Q){ int u = it->first.first; int v = it->first.second; int w = it->second; cout << "u " << u << " v " << v << " w " << w << endl; } #endif /* While n of nodes is different of 0 */ int n_nodes = 0; int soma = 0; for_each(it, Q){ /* Pega os pares u e v da lista */ int u = it->first.first; int v = it->first.second; /* Executa o find_set para os nós u e v */ int find_set_u = find_set(u); int find_set_v = find_set(v); /* Se o pai de u for diferente do pai de v */ if(find_set_u != find_set_v){ /* Inserimos os valores de u, v e w ordenado */ int u_aux = it->first.first; int v_aux = it->first.second; int w_aux = it->second; /* Verificamos se u < v */ if(u_aux < v_aux){ A.insert(make_pair(make_pair(u_aux, v_aux), w_aux)); } else{ A.insert(make_pair(make_pair(v_aux, u_aux), w_aux)); } /* Adiciona o custo final e une os elementos */ soma += it->second; union(find_set_u, find_set_v); } /* Se já temos nossa arvore geradora minima paramos a execução */ if(A.size() == (N - 1)){ break; } } #ifdef DEBUG /* Imprime todos os nós da nossa arvore geradora minima */ cout << "Arvore geradora minima" << endl; for_each(it, A){ int u = it->first.first; int v = it->first.second; int w = it->second; cout << "u " << u << " v " << v << " w " << w << endl; } #endif return soma; } int main(){ int U, V, C; int z = 1; do{ /* Lê as entradas */ cin >> N; cin >> M; if(N == 0 && M == 0) break; /* Inicalização do grafo */ A.clear(); for(int i = 1; i <= N; i++){ /* Vertices */ vertices[i].cor = BRANCO; vertices[i].anterior = NULL; vertices[i].num = i; /* Arestas & Distâncias & Caminho */ for(int j = 1; j <= N; j++){ dist[i][j] = INFINITY_VALUE; grafo[i][j] = 0; parente[i][j] = NULO; } /* Distâncias & Parentes na Diagonal */ dist[i][i] = 0; parente[i][i] = i; pai[i] = i; } /* Lê as arestas */ for(int i = 0; i < M; i++){ /* Pega os valores de A e B*/ cin >> U; cin >> V; cin >> C; /* Como temos um grafo não direcionado os dois caminhos são válidos */ grafo[U][V] += 1; grafo[V][U] += 1; /* Custo de U a V */ dist[U][V] = C; dist[V][U] = C; /* Menor caminho de U a V */ parente[U][V] = U; parente[V][U] = V; } if(z > 1){ cout << endl; } /* Iremos construir uma arvore geradora minima usando Kruskal, e retornar o custo do menor caminho entre todos os nós */ int retorno = Kruskal(); cout << "Teste " << z << endl; for_each(it, A){ int u = it->first.first; int v = it->first.second; if(u < v){ cout << u << " " << v << endl; } else{ cout << v << " " << u << endl; } } /* Incrementamos o numero de testes executados */ z += 1; } while(true); return 0; } <file_sep>/Lista_VI/NATUREZA.cpp #include <iostream> #include <list> #include <queue> #include <map> // Essa eu ja tinha feito semestre passado também /* Constantes do algoritmo */ #define MAX_NUM_VERTICES 6002 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* better find */ #define not_found_in(var) var.end() /* Max value between two vars */ #define max(var1, var2) (var1 > var2 ? var1 : var2) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE std::numeric_limits<int>::max() /* Ativar apenas durante o DEBUG */ //#define DEBUG using namespace std; typedef struct VerticeStruct{ int num; int cor; int d; int tempo_s; int tempo_f; struct VerticeStruct *anterior; } Vertice; /* Estrutura do grafo - arestas e vertices */ list<int> grafo[MAX_NUM_VERTICES]; Vertice vertices[MAX_NUM_VERTICES]; /* Tempo Global */ int tempo; /* Variaveis do programa */ int C, R; /* Mapeamento dos vertices com string */ map<string, int> nome_vertices; void printaVazio(int qtd){ for(int i = 0; i < qtd; i++){ cout << " "; } } /* Visita os nós adjacentes, utilizando busca em largura */ int BFS(Vertice *s){ /* Começa a consulta do primeiro valor */ //Vertice *s = &vertices[1]; /* Inicializamos o nó em questão */ s->cor = CINZA; s->d = 0; s->anterior = NULL; /* Tamanho do ciclo */ int tamanho_ciclo = 1; /* Criamos uma fila de prioridades */ queue<int> Q; /* Enfileiramos o primeiro valor */ Q.push(s->num); /* Enquanto a fila não estiver vazia */ while(!Q.empty()){ Vertice *u = &vertices[Q.front()]; Q.pop(); #ifdef DEBUG cout << u->num << " "; #endif /* Para cada vértice adjacente a u */ for_each(it, grafo[u->num]){ Vertice *v = &vertices[*it]; /* Se o vertice não tiiver sido visitado, marca ele como visitado, enfileira e modifica */ if(v->cor == BRANCO){ /* Setamos os valores do vértice adjacente */ v->anterior = u; v->cor = CINZA; v->d = u->d + 1; /* Empilhamos o número do vértice adjacente atual */ Q.push(v->num); /* Incrementamos em 1 o tamanho do ciclo */ tamanho_ciclo += 1; } } /* Finaliza a consulta */ u->cor = PRETO; } #ifdef DEBUG cout << endl; #endif return tamanho_ciclo; } /* Visita os nós adjancentes, utilizando busca em profundidade */ int DFS_visit(Vertice *u, int grau){ /* Atualiza o valor do tempo e indica que está sendo visitado */ tempo += 1; u->tempo_s = tempo; u->cor = CINZA; /* Quantidade de nos */ int quantidade_ciclos = 1; #ifdef DEBUG printaVazio(grau); cout << " -- Inicio -- " << endl; #endif /* Para cada vértice adjacente a u */ for_each(it, grafo[u->num]){ Vertice *v = &vertices[*it]; /* Caso ele seja branco */ if(v->cor == BRANCO){ v->anterior = u; quantidade_ciclos += DFS_visit(v, grau + 3); #ifdef DEBUG printaVazio(grau); cout << " -- Encontrado Ciclo -- > X = " << quantidade_ciclos << endl; #endif } } #ifdef DEBUG printaVazio(grau); cout << " > " << quantidade_ciclos << endl; printaVazio(grau); cout << " -- Fim -- " << endl; #endif /* Finaliza a busca em profundidade do nó atual */ u->cor = PRETO; tempo += 1; u->tempo_f = tempo; /* Retorna o contador de ciclo */ return quantidade_ciclos; } int main(){ do{ /* Lê as entradas */ cin >> C; cin >> R; /* Se condição de parada da aplicação for atingida */ if(C == 0) break; /* Inicalização do grafo */ nome_vertices.clear(); tempo = 0; for(int i = 1; i <= C; i++){ /* Vertices */ vertices[i].cor = BRANCO; vertices[i].num = i; vertices[i].anterior = NULL; /* Valor de cada vertice */ /* Inicializa a chave se a mesma for nova na tabela de simbolos */ string alimento_ou_preador; cin >> alimento_ou_preador; //nome_vertices.insert(make_pair(alimento_ou_preador, i)); nome_vertices[alimento_ou_preador] = i; #ifdef DEBUG cout << ">>> " << alimento_ou_preador << " ID " << nome_vertices[alimento_ou_preador] << endl; #endif /* Arestas */ grafo[i].clear(); } /* Lê as arestas */ for(int i = 0; i < R; i++){ string alimento, preador; /* Pega o nome de cada alimento e seu respectivo predador */ cin >> alimento; cin >> preador; /* Associa o valor da string a um numero inteiro qualquer */ int id_alimento = nome_vertices[alimento]; int id_predador = nome_vertices[preador]; #ifdef DEBUG cout << "alimento = " << alimento << " preador = " << preador << endl; cout << "id_alimento = " << id_alimento << " id_preador = " << id_predador << endl; #endif /* Como alimento e preador estão na mesma cadeia, temos tanto a ida como a volta */ grafo[id_predador].push_back(id_alimento); grafo[id_alimento].push_back(id_predador); } /* Maior cadeia alimentar */ int maior_ciclo = 0; /* Executa uma DFS */ /* Iremos contar o tamanho de cada ciclo e armazenar o valor do ciclo maior */ for(int i = 1; i <= C; i++){ if(vertices[i].cor == BRANCO){ //int qtd_ciclos_atual = DFS_visit(&vertices[i], 0); int qtd_ciclos_atual = BFS(&vertices[i]); maior_ciclo = max(maior_ciclo, qtd_ciclos_atual); } } /* Imprime o maior ciclo */ cout << maior_ciclo << endl; }while(C != 0); return 0; } <file_sep>/Lista_VIII/PONTES09.cpp #include <bits/stdc++.h> #define INFINITY_VALUE std::numeric_limits<int>::max() #define MAX_NUM_VERTICES 1002 #define UNDEFINED_VERTICE -1 /* Distância de u a v */ #define distancia(u,v) v using namespace std; typedef struct VerticeStruct{ int num; int distancia; int anterior; } Vertice; /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) #define NAO_VISITADO 0 #define VISITANDO 1 #define VISITADO 2 Vertice vertices[MAX_NUM_VERTICES]; vector<pair<int, int> > grafo[MAX_NUM_VERTICES]; vector<int> menor_caminho; int N, M, L = 0; void dijkstra(){ /* Criamos uma fila de prioridades */ priority_queue<pair<int, int> > Q; /* Adicionamos o vértice de origem */ Q.push(make_pair(0, L)); /* Enquanto nossa fila não estiver vazia */ while(!Q.empty()){ /* Extraimos o menor vertice de nossa fila */ Vertice *u = &vertices[Q.top().second]; Q.pop(); /* Para cada vizinho v de u */ for(int vi = 0; vi < grafo[u->num].size(); vi++){ /* Vertice V */ int v = grafo[u->num][vi].first; int v_peso = grafo[u->num][vi].second; /* Some a distancia de u com a distancia de u a v como temos que a distância é fixa, ela é igual a 1 */ int alternativa = u->distancia + v_peso; /* Se o novo caminho for o melhor caminho armazene ele */ if (alternativa < vertices[v].distancia){ vertices[v].distancia = alternativa; vertices[v].anterior = u->num; Q.push(make_pair(vertices[v].distancia, vertices[v].num)); } } } } int main(){ cin >> N >> M; for(int i = 0; i <= N + 1; i++){ grafo[i].clear(); vertices[i].num = i; vertices[i].distancia = INFINITY_VALUE; vertices[i].anterior = UNDEFINED_VERTICE; } for(int i = 0; i < M; i++){ int S, T, B; cin >> S >> T >> B; grafo[S].push_back(make_pair(T, B)); grafo[T].push_back(make_pair(S, B)); } /* Destino a ser alcançado */ int destino = N + 1; vertices[0].distancia = 0; dijkstra(); cout << vertices[destino].distancia << endl; return 0; }<file_sep>/Lista_II/PROIBIDO.cpp #include <bits/stdc++.h> #define MAX_SIZE_ARRAY 140001 using namespace std; int N; int vetor[MAX_SIZE_ARRAY] = { 0 }; int cmpfunc (const void * a, const void * b) { return (*(int*)a - *(int*)b); } int binary_serch(int valor){ int esquerda = 0; int direita = N - 1; while(esquerda <= direita){ int meio = esquerda + (direita - esquerda) / 2; if(vetor[meio] == valor){ return meio; } else if(vetor[meio] > valor){ direita = meio - 1; } else{ esquerda = meio + 1; } } return -1; } int main(){ scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &vetor[i]); } qsort(vetor, N, sizeof(int), cmpfunc); while(true){ int valor; if(scanf("%d", &valor) == EOF) break; printf("%s\n", binary_serch(valor) != -1 ? "sim" : "nao"); } return 0; }<file_sep>/Lista_VI/DENGUE.cpp #include <iostream> #include <cstdio> #include <limits> /* Constantes do algoritmo */ #define MAX_NUM_VERTICES 120 #define BRANCO 0 #define CINZA 1 #define PRETO 2 /* For each */ #define for_each(member,container) for(typeof(container.begin()) member = container.begin(); \ member != container.end(); \ member ++ ) /* better find */ #define not_found_in(var) var.end() /* Max value between two vars */ #define max_2(var1, var2) (var1 > var2 ? var1 : var2) #define min_2(var1, var2) (var1 < var2 ? var1 : var2) /* Verifica a existência */ #define is_none(var) (var == NULL) #define is_not_none(var) (var != NULL) /* Valor infinito */ #define INFINITY_VALUE std::numeric_limits<int>::max() /* Indice nulo */ #define NULO -1 /* Ativar apenas durante o DEBUG */ //#define DEBUG using namespace std; typedef struct VerticeStruct{ int num; int cor; int d; int tempo_s; int tempo_f; struct VerticeStruct *anterior; } Vertice; /* Estrutura do grafo - arestas e vertices */ int grafo[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int dist[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; int parente[MAX_NUM_VERTICES][MAX_NUM_VERTICES] = {{ 0 }}; Vertice vertices[MAX_NUM_VERTICES]; /* Tempo Global */ int tempo; /* Variaveis do programa */ int N; /* Floyd Warshall */ int FloydWarshall(){ /* Executa o algoritmo de Floyd Warshall e computa as distancias */ for(int k = 1; k <= N; k++){ for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if( dist[i][k] != INFINITY_VALUE && dist[k][j] != INFINITY_VALUE && (dist[i][k] + dist[k][j] < dist[i][j])){ dist[i][j] = dist[i][k] + dist[k][j]; parente[i][j] = k; } } } } /* Inicia a menor distância entre todos os nós como sendo o infinito */ int menor_distancia = INFINITY_VALUE; int vertice_menor_distancia = 1; for(int u = 1; u <= N; u++){ int distancia = 0; for(int v = 1; v <= N; v++){ distancia = max_2(distancia, dist[u][v]); } if(distancia < menor_distancia){ menor_distancia = distancia; vertice_menor_distancia = u; } } #ifdef DEBUG for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if (dist[i][j] == INFINITY_VALUE){ printf("%7s", "INF"); } else{ printf ("%7d", dist[i][j]); } } cout << '\n'; } cout << '\n'; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if (parente[i][j] == NULO){ printf("%7s", "NIL"); } else{ printf ("%7d", parente[i][j]); } } cout << '\n'; } cout << '\n'; #endif return vertice_menor_distancia; } int main(){ int z = 1; /* CIN Improvements */ //ios_base::sync_with_stdio(false); cin.tie(NULL); do{ /* Lê as entradas */ cin >> N; /* Se condição de parada da aplicação for atingida */ if(N == 0) break; /* Inicalização do grafo */ tempo = 0; for(int i = 1; i <= N; i++){ /* Vertices */ vertices[i].cor = BRANCO; vertices[i].num = i; vertices[i].anterior = NULL; /* Arestas & Distâncias & Caminho */ for(int j = 1; j <= N; j++){ grafo[i][j] = 0; dist[i][j] = INFINITY_VALUE; parente[i][j] = NULO; } /* Distâncias Diagonal */ dist[i][i] = 0; parente[i][i] = i; } for(int i = 1; i < N; i++){ /* Inicialização das arestas informadas pelo usuario*/ int x; int y; cin >> x; cin >> y; /* Aqui temos um grafo não direcionado com custo igual para os dois lados*/ grafo[x][y] += 1; grafo[y][x] += 1; dist[x][y] = 1; dist[y][x] = 1; parente[x][y] = x; parente[y][x] = y; } /* Executa o algoritm de Floyd Warshall e retorna o nó de "centro" */ int resultado = 1; if(N > 1){ resultado = FloydWarshall(); } /* Imprime uma linha em branco entre os testes*/ if(z > 1){ cout << '\n'; } /* Imprime o resultado obtido */ cout << "Teste " << z << '\n'; cout << resultado << '\n'; /* Incrementa o número do teste */ z += 1; }while(N != 0); return 0; } <file_sep>/Lista_IV/EDIST.cpp #include <bits/stdc++.h> #define MAX_STRING_SIZE 2001 #define max(A, B) (A > B ? A : B) #define min(A, B) (A < B ? A : B) #define delete_char(MATRIX, A, B) (MATRIX[A - 1][B]) #define insert_char(MATRIX, A, B) (MATRIX[A][B - 1]) #define modify_char(MATRIX, A, B) (MATRIX[A - 1][B - 1]) using namespace std; char str1[MAX_STRING_SIZE]; char str2[MAX_STRING_SIZE]; int edit_distance[MAX_STRING_SIZE + 1][MAX_STRING_SIZE + 1] = {{ 0 }}; int main(){ int minimum_edit_distance; int n; scanf("%d%*c", &n); for(int t = 0; t < n; t++){ scanf("%s%*c", str1); scanf("%s%*c", str2); int size_str1 = strlen(str1); int size_str2 = strlen(str2); int max_str_size = max(size_str1, size_str2); for(int i = 0; i <= max_str_size; i++){ if(i <= size_str1){ edit_distance[i][0] = i; } if(i <= size_str2){ edit_distance[0][i] = i; } } for(int i = 1; i <= size_str1; i++){ for(int j = 1; j <= size_str2; j++){ if(str1[i - 1] == str2[j - 1]){ edit_distance[i][j] = edit_distance[i - 1][j - 1]; } else{ edit_distance[i][j] = 1 + min( min(delete_char(edit_distance, i, j), insert_char(edit_distance, i, j)), modify_char(edit_distance, i, j)); } } } #ifdef DEBUG printf("%s:%s\n", str1, str2); printf("%6c", ' '); for(int i = 0; i < size_str2; i++){ printf("%3c", str2[i]); } printf("\n"); for(int i = 0; i <= size_str1; i++){ printf("%3c", (i == 0 ? ' ' : str1[i - 1])); for(int j = 0; j <= size_str2; j++){ printf("%3d", edit_distance[i][j]); } printf("\n"); } #endif minimum_edit_distance = edit_distance[size_str1][size_str2]; printf("%d\n", minimum_edit_distance); } return EXIT_SUCCESS; }
8a439223f859f195a3f6690633058f30387da482
[ "Markdown", "C++" ]
18
C++
jefersonla/LABII-Listas
0cb5b990f9a1b4c9ea48883af05657fa8f149b1c
dbf91c88d86ab7417d8cbb6857a6bad00f7eacd5
refs/heads/master
<repo_name>mangelino997/Firebase-social-network<file_sep>/functions/handlers/users.ts //const {db} = require('../util/admin.tsx'); const config = require('../util/config'); const firebase = require('firebase'); // Initialize Firebase firebase.initializeApp(config); const { validateSignupData, validateLoginData, } = require("../util/validators"); let token = ""; let userId = ""; exports.signUp = (req: any, res: any) => { const newUser = { email: req.body.email, password: <PASSWORD>, confirmPassword: <PASSWORD>, handle: req.body.handle }; // errors and return errors if there const { valid, errors } = validateSignupData(newUser); if (!valid) return res.status(400).json(errors); // validate db.doc(`/users/ ${newUser.handle}`).get() .then((doc: any) => { if (doc.exists) { return res.status(400).json({ handle: 'this handle is already taken' }); } else { return firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password); } }) .then((data: any) => { userId = data.user.uid; return data.user.getIdToken(); }) .then((tokn: any) => { token = tokn; const userCredentials = { handle: newUser.handle, email: newUser.email, createdAt: new Date().toISOString(), userId: userId } return db.doc(`/users/${newUser.handle}`).set(userCredentials); }) .then(() => { return res.status(201).json({ token }); }) .catch((err: any) => { if (err.code === 'auth/email-already-in-use') return res.status(400).json({ email: "Email is already in use." }) else return res.status(500).json({ error: err.code }) }); } // exports.login = (req: any, res: any) => { const user = { email: req.body.email, password: <PASSWORD>.password } let errors: any = {}; if (isEmpty(user.email)) errors.email = 'Email must not be empty'; if (isEmpty(user.password)) errors.email = 'Password must not be empty'; // return errors if there if (Object.keys(errors).length > 0) return res.status(400).json(errors); firebase .auth() .signInWithEmailAndPassword(user.email, user.password) .then((data: any) => { return data.user.getIdToken(); }) .then((token: any) => { return res.json({ token }); }) .catch((err: any) => { console.error(err); // auth/wrong-password // auth/user-not-user return res .status(403) .json({ general: "Wrong credentials, please try again" }); }); }<file_sep>/functions/util/config.ts module.exports = { apiKey: "<KEY>", authDomain: "react-social-network-6b4e1.firebaseapp.com", databaseURL: "https://react-social-network-6b4e1.firebaseio.com", projectId: "react-social-network-6b4e1", storageBucket: "react-social-network-6b4e1.appspot.com", messagingSenderId: "626199538337", appId: "1:626199538337:web:64b8a60e18ec1adfa25ee0", measurementId: "G-3CEH9BP7B4" };<file_sep>/functions/util/admin.ts /* */ const admin = require('firebase-admin'); admin.initializeApp(); // get db const db = admin.firestore(); module.exports = {admin, db};<file_sep>/functions/src/index.ts import * as functions from 'firebase-functions'; const admin = require('firebase-admin'); admin.initializeApp(); const app = require('express')(); const { uuid } = require("uuidv4"); const config = { apiKey: "<KEY>", authDomain: "react-social-network-6b4e1.firebaseapp.com", databaseURL: "https://react-social-network-6b4e1.firebaseio.com", projectId: "react-social-network-6b4e1", storageBucket: "react-social-network-6b4e1.appspot.com", messagingSenderId: "626199538337", appId: "1:626199538337:web:64b8a60e18ec1adfa25ee0", measurementId: "G-3CEH9BP7B4" }; const firebase = require('firebase'); // Initialize Firebase firebase.initializeApp(config); const cors = require('cors'); app.use(cors()); // get db const db = admin.firestore(); /* handle token para que funcione debe coincidir el uid del usuario en Athentication (web de firebase) con el uid del usuario registrado en Cloud Firestore --> users */ const faAuth = (req: any, res: any, next: any) => { let idToken; if ( req.headers.authorization && req.headers.authorization.startsWith('Bearer ') ) { idToken = req.headers.authorization.split('Bearer ')[1]; } else { // No token found return res.status(403).json({ error: 'Unauthorized' }); } admin .auth() .verifyIdToken(idToken) .then((decodedToken: any) => { //res.status(200).json(decodedToken ); req.user = decodedToken; return db .collection('users') .where('userId', '==', decodedToken.uid) .limit(1) .get(); }) .then((data: any) => { req.user.handle = data.docs[0].data().handle; req.user.imageUrl = data.docs[0].data().imageUrl; return next(); }) .catch((err: any) => { // Error while verifying token return res.status(403).json(err); }); }; // forma de hacer un endpoint con Express app.get('/screams', (req: any, res: any) => { db .collection('screams') .orderBy('createdAt', 'desc') // para que el orderBy funcione hay que declararlo en Firestore -> indices .get() .then((data: any[]) => { let screams: any[] = []; data.forEach(element => { screams.push({ screamId: element.id, body: element.data().body, userHandle: element.data().userHandle, createdAt: element.data().createdAt, commentCount: element.data().commentCount, likeCount: element.data().likeCount, userImage: element.data().userImage }); }); return res.json(screams); }) .catch((err: any) => console.log(err)) }) // post one screa, app.post('/scream', faAuth, (req: any, res: any) => { if (req.body.body.trim() === '') { return res.status(400).json({ body: 'Body must not be empty' }); } const newScream = { body: req.body.body, userHandle: req.user.handle, // este viene de faAuth userImage: req.user.imageUrl, createdAt: new Date().toISOString(), likeCount: 0, commentCount: 0 }; db.collection('screams') .add(newScream) .then((doc: any) => { const resScream: any = newScream; resScream.screamId = doc.id; res.json(resScream); }) .catch((err: any) => { res.status(500).json({ error: 'something went wrong' }); }); }) // valida si el campo esta vacio const isEmpty = (field: string) => { if (field.trim() === '') return true else return false; } // valida si el email es correcto const isEmail = (email: string) => { const emailRegEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (email.match(emailRegEx)) return true; else return false; } // Sign up route let token = ""; let userId = ""; app.post('/signup', (req: any, res: any) => { const newUser = { email: req.body.email, password: <PASSWORD>, confirmPassword: <PASSWORD>, handle: req.body.handle }; // errors let errors: any = {}; if (isEmpty(newUser.email)) errors.email = 'Email must not be empty'; else if (!isEmail(newUser.email)) errors.email = 'Must be a valid Email'; if (isEmpty(newUser.password)) errors.password = 'Must not be empty'; if (newUser.password !== newUser.confirmPassword) errors.confirmPassword = '<PASSWORD>'; //la contrasenia no puede ser debil >5 caract if (isEmpty(newUser.handle)) errors.handle = 'Handle must not be empty'; // return errors if there if (Object.keys(errors).length > 0) return res.status(400).json(errors); // img const noImg = 'no-img.png'; // validate db.doc(`/users/ ${newUser.handle}`).get() .then((doc: any) => { if (doc.exists) { return res.status(400).json({ handle: 'this handle is already taken' }); } else { return firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password); } }) .then((data: any) => { userId = data.user.uid; return data.user.getIdToken(); }) .then((tokn: any) => { token = tokn; const userCredentials = { handle: newUser.handle, email: newUser.email, createdAt: new Date().toISOString(), imageUrl: `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${noImg}?alt=media`, userId: userId } return db.doc(`/users/${newUser.handle}`).set(userCredentials); }) .then(() => { return res.status(201).json({ token }); }) .catch((err: any) => { if (err.code === 'auth/email-already-in-use') return res.status(400).json({ email: "Email is already in use." }) else return res.status(500).json({ general: "Something went wrong, please try again." }) }); }); // Login app.post('/login', (req: any, res: any) => { const user = { email: req.body.email, password: req.body.<PASSWORD> } let errors: any = {}; if (isEmpty(user.email)) errors.email = 'Email must not be empty'; if (isEmpty(user.password)) errors.email = 'Password must not be empty'; // return errors if there if (Object.keys(errors).length > 0) return res.status(400).json(errors); firebase .auth() .signInWithEmailAndPassword(user.email, user.password) .then((data: any) => { return data.user.getIdToken(); }) .then((token: any) => { return res.json({ token }); }) .catch((err: any) => { // auth/wrong-password // auth/user-not-user return res .status(403) .json({ general: "Wrong credentials, please try again" }); }); }) /* upload img user install "npm i --save busboy" A node.js module for parsing incoming HTML form data. https://www.npmjs.com/package/busboy */ // Upload a profile image for user app.post('/user/img', faAuth, (req: any, res: any) => { const BusBoy = require("busboy"); const path = require("path"); const os = require("os"); const fs = require("fs"); const busboy = new BusBoy({ headers: req.headers }); let imageToBeUploaded: any = {}; let imageFileName: any; // String for image token let generatedToken = uuid(); busboy.on("file", (fieldname: any, file: any, filename: any, encoding: any, mimetype: any) => { console.log(fieldname, file, filename, encoding, mimetype); if (mimetype !== "image/jpeg" && mimetype !== "image/png") { return res.status(400).json({ error: "Wrong file type submitted" }); } // my.image.png => ['my', 'image', 'png'] const imageExtension = filename.split(".")[filename.split(".").length - 1]; // 32756238461724837.png imageFileName = `${Math.round( Math.random() * 1000000000000 ).toString()}.${imageExtension}`; const filepath = path.join(os.tmpdir(), imageFileName); imageToBeUploaded = { filepath, mimetype }; file.pipe(fs.createWriteStream(filepath)); }); busboy.on("finish", () => { admin .storage() .bucket() .upload(imageToBeUploaded.filepath, { resumable: false, metadata: { metadata: { contentType: imageToBeUploaded.mimetype, //Generate token to be appended to imageUrl firebaseStorageDownloadTokens: generatedToken, }, }, }) .then(() => { // Append token to url const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media&token=${generatedToken}`; return db.doc(`/users/${req.user.handle}`).update({ imageUrl }); }) .then(() => { return res.json({ message: "image uploaded successfully" }); }) .catch((err: any) => { console.error(err); return res.status(500).json({ error: "something went wrong" }); }); }); busboy.end(req.rawBody); // const BusBoy = require("busboy"); // const path = require("path"); // const os = require("os"); // const fs = require("fs"); // const busboy = new BusBoy({ headers: req.headers }); // let imageToBeUploaded: any = {}; // let imageFileName: any; // // String for image token // let generatedToken = '<PASSWORD>'; // busboy.on("file", (fieldname: any, file: any, filename: any, encoding: any, mimetype: any) => { // // fieldname, file, filename, encoding, mimetype // if (mimetype !== "image/jpeg" && mimetype !== "image/png") { // return res.status(400).json({ error: "Wrong file type submitted" }); // } // // my.image.png => ['my', 'image', 'png'] // const imageExtension = filename.split(".")[filename.split(".").length - 1]; // // 32756238461724837.png // imageFileName = `${Math.round( // Math.random() * 1000000000000 // ).toString()}.${imageExtension}`; // const filepath = path.join(os.tmpdir(), imageFileName); // imageToBeUploaded = { filepath, mimetype }; // file.pipe(fs.createWriteStream(filepath)); // }); // busboy.on("finish", () => { // admin // .storage() // .bucket() // .upload(imageToBeUploaded.filepath, { // resumable: false, // metadata: { // metadata: { // contentType: imageToBeUploaded.mimetype, // //Generate token to be appended to imageUrl // firebaseStorageDownloadTokens: generatedToken, // }, // }, // }) // .then(() => { // // Append token to url // // const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`; // const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media&token=${generatedToken}`; // return db.doc(`/users/${req.user.handle}`).update({ imageUrl }); // }) // .then(() => { // return res.json({ message: "image uploaded successfully" }); // }) // .catch((err: any) => { // return res.status(500).json({ error: "something went wrong" }); // }); // }); // busboy.end(req.rawBody); }); // get own user details app.get('/user', faAuth, (req: any, res: any) => { let userData: any = {}; db.doc(`/users/${req.user.handle}`) .get() .then((doc: any) => { if (doc.exists) { userData.credentials = doc.data(); return db .collection("likes") .where("userHandle", "==", req.user.handle) .get(); } }) .then((data: any) => { userData.likes = []; data.forEach((doc: any) => { userData.likes.push(doc.data()); }); return db .collection("notifications") .where("recipient", "==", req.user.handle) .orderBy("createdAt", "desc") // se crea el indice en cloud firestore .limit(10) .get(); }) .then((data: any) => { userData.notifications = []; data.forEach((doc: any) => { userData.notifications.push({ recipient: doc.data().recipient, sender: doc.data().sender, createdAt: doc.data().createdAt, screamId: doc.data().screamId, type: doc.data().type, read: doc.data().read, notificationId: doc.id, }); }); return res.json(userData); }) .catch((err: any) => { console.error(err); return res.status(500).json({ error: err.code }); }); }); // Get any user's details app.get('/user/:handle', (req: any, res: any) => { let userData: any = {}; db.doc(`/users/${req.params.handle}`) .get() .then((doc: any) => { if (doc.exists) { userData.user = doc.data(); return db .collection("screams") .where("userHandle", "==", req.params.handle) .orderBy("createdAt", "desc") .get(); } else { return res.status(404).json({ errror: "User not found" }); } }) .then((data: any) => { userData.screams = []; data.forEach((doc: any) => { userData.screams.push({ body: doc.data().body, createdAt: doc.data().createdAt, userHandle: doc.data().userHandle, userImage: doc.data().userImage, likeCount: doc.data().likeCount, commentCount: doc.data().commentCount, screamId: doc.id, }); }); return res.json(userData); }) .catch((err: any) => { console.error(err); return res.status(500).json({ error: err.code }); }); }); // add detail user app.post('/user', faAuth, (req: any, res: any) => { let userDetails = reduceUserDetails(req.body); db.doc(`/users/${req.user.handle}`) .update(userDetails) .then(() => { return res.json({ message: "Details added successfully" }); }) .catch((err: any) => { return res.status(500).json({ error: err.code }); }); }); const reduceUserDetails = (data: any) => { let userDetails: any = {}; if (!isEmpty(data.bio.trim())) userDetails.bio = data.bio; if (!isEmpty(data.website.trim())) { // https://website.com if (data.website.trim().substring(0, 4) !== 'http') { userDetails.website = `http://${data.website.trim()}`; } else userDetails.website = data.website; } if (!isEmpty(data.location.trim())) userDetails.location = data.location; return userDetails; }; app.post('/notifications', faAuth, (req: any, res: any) => { let batch = db.batch(); req.body.forEach((notificationId: any) => { const notification = db.doc(`/notifications/${notificationId}`); batch.update(notification, { read: true }); }); batch .commit() .then(() => { return res.json({ message: "Notifications marked read" }); }) .catch((err: any) => { console.error(err); return res.status(500).json({ error: err.code }); }); }); // Fetch one scream app.get('/scream/:screamId', (req: any, res: any) => { let screamData: any = {}; db.doc(`/screams/${req.params.screamId}`) .get() .then((doc: any) => { if (!doc.exists) { return res.status(404).json({ error: 'Scream not found' }); } screamData = doc.data(); screamData.screamId = doc.id; return db .collection('comments') .orderBy('createdAt', 'desc') .where('screamId', '==', req.params.screamId) .get(); }) .then((data: any) => { screamData.comments = []; data.forEach((doc: any) => { screamData.comments.push(doc.data()); }); return res.json(screamData); }) .catch((err: any) => { console.error(err); res.status(500).json({ error: err.code }); }); }); // Comment on a comment app.post('/scream/:screamId/comment', faAuth, (req: any, res: any) => { if (req.body.body.trim() === '') return res.status(400).json({ comment: 'Must not be empty' }); const newComment = { body: req.body.body, createdAt: new Date().toISOString(), screamId: req.params.screamId, userHandle: req.user.handle, userImage: req.user.imageUrl }; console.log(newComment); db.doc(`/screams/${req.params.screamId}`) .get() .then((doc: any) => { if (!doc.exists) { return res.status(404).json({ error: 'Scream not found' }); } return doc.ref.update({ commentCount: doc.data().commentCount + 1 }); }) .then(() => { return db.collection('comments').add(newComment); }) .then(() => { res.json(newComment); }) .catch((err: any) => { console.log(err); res.status(500).json({ error: 'Something went wrong' }); }); }); // Like a scream app.get('/scream/:screamId/like', faAuth, (req: any, res: any) => { const likeDocument = db .collection('likes') .where('userHandle', '==', req.user.handle) .where('screamId', '==', req.params.screamId) .limit(1); const screamDocument = db.doc(`/screams/${req.params.screamId}`); let screamData: any; screamDocument .get() .then((doc: any) => { if (doc.exists) { screamData = doc.data(); screamData.screamId = doc.id; return likeDocument.get(); } else { return res.status(404).json({ error: 'Scream not found' }); } }) .then((data: any) => { if (data.empty) { return db .collection('likes') .add({ screamId: req.params.screamId, userHandle: req.user.handle }) .then(() => { screamData.likeCount++; return screamDocument.update({ likeCount: screamData.likeCount }); }) .then(() => { return res.json(screamData); }); } else { return res.status(400).json({ error: 'Scream already liked' }); } }) .catch((err: any) => { console.error(err); res.status(500).json({ error: err.code }); }); }); // unlike scream app.get('/scream/:screamId/unlike', faAuth, (req: any, res: any) => { const likeDocument = db .collection('likes') .where('userHandle', '==', req.user.handle) .where('screamId', '==', req.params.screamId) .limit(1); const screamDocument = db.doc(`/screams/${req.params.screamId}`); let screamData: any; screamDocument .get() .then((doc: any) => { if (doc.exists) { screamData = doc.data(); screamData.screamId = doc.id; return likeDocument.get(); } else { return res.status(404).json({ error: 'Scream not found' }); } }) .then((data: any) => { if (data.empty) { return res.status(400).json({ error: 'Scream not liked' }); } else { return db .doc(`/likes/${data.docs[0].id}`) .delete() .then(() => { screamData.likeCount--; return screamDocument.update({ likeCount: screamData.likeCount }); }) .then(() => { res.json(screamData); }); } }) .catch((err: any) => { console.error(err); res.status(500).json({ error: err.code }); }); }); // Delete a scream app.delete('/scream/:screamId', faAuth, (req: any, res: any) => { const document = db.doc(`/screams/${req.params.screamId}`); document .get() .then((doc: any) => { if (!doc.exists) { return res.status(404).json({ error: 'Scream not found' }); } if (doc.data().userHandle !== req.user.handle) { return res.status(403).json({ error: 'Unauthorized' }); } else { return document.delete(); } }) .then(() => { res.json({ message: 'Scream deleted successfully' }); }) .catch((err: any) => { console.error(err); return res.status(500).json({ error: err.code }); }); }); // URL base https://base.com/api/ export const api = functions.https.onRequest(app); // Notifications exports.createNotificationOnLike = functions .region('us-central1') .firestore.document('likes/{id}') .onCreate((snapshot) => { return db .doc(`/screams/${snapshot.data().screamId}`) .get() .then((doc: any) => { if ( doc.exists && doc.data().userHandle !== snapshot.data().userHandle ) { return db.doc(`/notifications/${snapshot.id}`).set({ createdAt: new Date().toISOString(), recipient: doc.data().userHandle, sender: snapshot.data().userHandle, type: 'like', read: false, screamId: doc.id }); } }) .catch((err: any) => console.error(err)); }); exports.deleteNotificationOnUnLike = functions .region('us-central1') .firestore.document('likes/{id}') .onDelete((snapshot) => { return db .doc(`/notifications/${snapshot.id}`) .delete() .catch((err: any) => { console.error(err); return; }); }); exports.createNotificationOnComment = functions .region('us-central1') .firestore.document('comments/{id}') .onCreate((snapshot) => { return db .doc(`/screams/${snapshot.data().screamId}`) .get() .then((doc: any) => { if ( doc.exists && doc.data().userHandle !== snapshot.data().userHandle ) { return db.doc(`/notifications/${snapshot.id}`).set({ createdAt: new Date().toISOString(), recipient: doc.data().userHandle, sender: snapshot.data().userHandle, type: 'comment', read: false, screamId: doc.id }); } }) .catch((err: any) => { console.error(err); return; }); }); // handle change image for user exports.onUserImageChange = functions .region('us-central1') .firestore.document('/users/{userId}') .onUpdate((change) => { if (change.before.data().imageUrl !== change.after.data().imageUrl) { const batch = db.batch(); return db .collection('screams') .where('userHandle', '==', change.before.data().handle) .get() .then((data: any) => { data.forEach((doc: any) => { const scream = db.doc(`/screams/${doc.id}`); batch.update(scream, { userImage: change.after.data().imageUrl }); }); return batch.commit(); }); } else return true; }); // handle trigger for delete posts / screams exports.onScreamDelete = functions .region('us-central1') .firestore.document('/screams/{screamId}') .onDelete((snapshot, context) => { const screamId = context.params.screamId; const batch = db.batch(); return db .collection('comments') .where('screamId', '==', screamId) .get() .then((data: any) => { data.forEach((doc: any) => { batch.delete(db.doc(`/comments/${doc.id}`)); }); return db .collection('likes') .where('screamId', '==', screamId) .get(); }) .then((data: any) => { data.forEach((doc: any) => { batch.delete(db.doc(`/likes/${doc.id}`)); }); return db .collection('notifications') .where('screamId', '==', screamId) .get(); }) .then((data: any) => { data.forEach((doc: any) => { batch.delete(db.doc(`/notifications/${doc.id}`)); }); return batch.commit(); }) .catch((err: any) => console.error(err)); }); <file_sep>/functions/util/validators.ts // valida si el campo esta vacio const isEmpty = (field: string) => { if (field.trim() === '') return true else return false; } // valida si el email es correcto const isEmail = (email: string) => { const emailRegEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (email.match(emailRegEx)) return true; else return false; } exports.validateSignupData = (data: any) => { let errors: any = {}; if (isEmpty(data.email)) { errors.email = 'Must not be empty'; } else if (!isEmail(data.email)) { errors.email = 'Must be a valid email address'; } if (isEmpty(data.password)) errors.password = '<PASSWORD>'; if (data.password !== data.confirmPassword) errors.confirmPassword = '<PASSWORD>'; if (isEmpty(data.handle)) errors.handle = 'Must not be empty'; return { errors, valid: Object.keys(errors).length === 0 ? true : false }; }; exports.validateLoginData = (data) => { let errors: any = {}; if (isEmpty(data.email)) errors.email = 'Must not be empty'; if (isEmpty(data.password)) errors.password = 'Must not be empty'; return { errors, valid: Object.keys(errors).length === 0 ? true : false }; };<file_sep>/functions/handlers/screams.ts const { db: any } = require("../util/admin.ts"); /* */ exports.getAllScreams = (req: any, res: any) => { db .collection('screams') .orderBy('createdAt', 'desc') .get() .then((data: any[]) => { let screams: any[] = []; data.forEach(element => { screams.push({ screamId: element.id, body: element.data().body, userHandle: element.data().userHandle, createdAt: element.data().createdAt }); }); return res.json(screams); }) .catch((err: any) => console.log(err)) } exports.postOneScream = (req: any, res: any) => { const newScream = { body: req.body.body, userHandle: req.body.userHandle, createdAt: new Date().toISOString() } db .collection('screams') .add(newScream) .then((doc: any) => { res.json({ message: `document ${doc.id} created successfully` }) }) .catch((err: any) => res.status(500).json({ error: 'something went wrong' })) }
871da3224e4958ea2080663f3a87351e2cc85e3d
[ "TypeScript" ]
6
TypeScript
mangelino997/Firebase-social-network
f8ea859991d03859b47f66cb8365cad45a4e67d3
e515b0e6a81d485d3da26a467a4835b609d102f0
refs/heads/master
<repo_name>milieuinfo/webcomponent-vl-ui-multiselect<file_sep>/test/e2e/pages/vl-multiselect.page.js const VlMultiSelect = require('../components/vl-multiselect'); const {VlDatepicker} = require('vl-ui-datepicker').Test; const {Page, Config} = require('vl-ui-core').Test; const {Key} = require('selenium-webdriver'); const {By} = require('vl-ui-core').Test.Setup; class VlMultiSelectPage extends Page { async _getMultiSelect(selector) { return new VlMultiSelect(this.driver, selector); } async getStandardMultiselect() { return this._getMultiSelect('#multiselect'); } async getVoorgeselecteerdeMultiselect() { return this._getMultiSelect('#multiselect-voorgeselecteerd'); } async getGegroepeerdeMultiselect() { return this._getMultiSelect('#multiselect-gegroepeerd'); } async getErrorMultiselect() { return this._getMultiSelect('#multiselect-error'); } async getSuccessMultiselect() { return this._getMultiSelect('#multiselect-success'); } async getDisabledMultiselect() { return this._getMultiSelect('#multiselect-disabled'); } async getMultiselectMetSpecifiekAantalResultaten() { return this._getMultiSelect('#multiselect-specifiek'); } async getMultiselectMetOnbeperkteResultaten() { return this._getMultiSelect('#multiselect-onbeperkt'); } async getDatepickerMultiselect() { return this._getMultiSelect('#multiselect-datepicker'); } async getChangeEventMultiselect() { return this._getMultiSelect('#change-listener'); } async getEnableDisableMethodeMultiselect() { return this._getMultiSelect('#vl-multiselect-enable-disable-methode'); } async getSetGetMethodeMultiselect() { return this._getMultiSelect('#vl-multiselect-set-get-methode'); } async getDatepicker() { return new VlDatepicker(this.driver, '#datepicker'); } async enable() { return this.driver.findElement(By.css('#enable')).click(); } async disable() { return this.driver.findElement(By.css('#disable')).click(); } async kiesDuitsland() { return this.driver.findElement(By.css('#duitsland')).click(); } async kiesBelgieEnNederland() { return this.driver.findElement(By.css('#be-nl')).click(); } async verwijderSelectie() { return this.driver.findElement(By.css('#verwijder')).click(); } async closeAnyOpenDropdowns() { const body = await this.driver.findElement(By.css('body')); await body.sendKeys(Key.ESCAPE); } async load() { await super.load(Config.baseUrl + '/demo/vl-multiselect.html'); } } module.exports = VlMultiSelectPage; <file_sep>/index.js module.exports = { Test: { VlMultiSelect: require('./test/e2e/components/vl-multiselect'), }, }; <file_sep>/dist/vl-multiselect.js import {define} from '/node_modules/vl-ui-core/dist/vl-core.js'; import {VlSelect} from '/node_modules/vl-ui-select/dist/vl-select.js'; /** * VlMultiSelect * @class * @classdesc Gebruik een multiselect om een gebruiker toe te laten om in een lijst van vooropgestelde keuzes te zoeken, en enkele of alle passende keuzes te selecteren. * * @extends VlSelect * * @property {boolean} data-vl-block - Attribuut wordt gebruikt om ervoor te zorgen dat de textarea getoond wordt als een block element en bijgevolg de breedte van de parent zal aannemen. * @property {boolean} data-vl-error - Attribuut wordt gebruikt om aan te duiden dat het select element verplicht is of ongeldige tekst bevat. * @property {boolean} data-vl-success - Attribuut wordt gebruikt om aan te duiden dat het select element correct werd ingevuld. * @property {boolean} disabled - Attribuut wordt gebruikt om te voorkomen dat de gebruiker iets kan kiezen uit het select element. * * @see {@link http://www.github.com/milieuinfo/webcomponent-vl-ui-multiselect/releases/latest|Release notes} * @see {@link http://www.github.com/milieuinfo/webcomponent-vl-ui-multiselect/issues|Issues} * @see {@link https://webcomponenten.omgeving.vlaanderen.be/demo/vl-multiselect.html|Demo} */ export class VlMultiSelect extends VlSelect { static get readyEvent() { return 'VlMultiSelectReady'; } connectedCallback() { this.classList.add('vl-multiselect'); this.setAttribute('multiple', ''); this.setAttribute('data-vl-multiselect', ''); const hasSelected = this.hasSelected(); if (!hasSelected) this.value = undefined; super.connectedCallback(); } hasSelected() { const options = Array.from(this.querySelectorAll('option')); return options.some((option) => { return option.hasAttribute('selected'); }); } /** * Geeft de ready event naam. * * @return {string} */ get readyEvent() { return VlMultiSelect.readyEvent; } /** * Zet het geselecteerd option element op basis van de option value. * * @param {string} values - De option value van het option element dat gekozen moet worden. * @return {void} */ set values(values) { values.forEach((value) => { super.value = value; }); } /** * Geeft de waarde van de geselecteerde option elementen. * * @return {string[]} */ get values() { return [...this.selectedOptions].map((option) => { return option.value || ''; }); } get _dataVlSelectAttribute() { return this.getAttribute('data-vl-multiselect'); } get _inputElement() { return this.parentElement.querySelector('input'); } /** * Geef focus aan het select input element. */ focus() { this._inputElement.focus(); } } window.customElements.whenDefined('vl-select').then(() => define('vl-multiselect', VlMultiSelect, {extends: 'select'})); <file_sep>/test/e2e/components/pill.js const {By} = require('vl-ui-core').Test.Setup; class Pill { constructor(webElement) { this.webElement = webElement; } async value() { return this.webElement.getAttribute('data-value'); } async isSelected() { return true; } async text() { const span = await this.webElement.findElement(By.css('span')); return span.getAttribute('innerText'); } async remove() { const closeButton = await this.webElement.findElements(By.css('.vl-pill__close')); if (closeButton.length < 1) { throw new Error('Dit item kan niet verwijderd worden!'); } return closeButton[0].click(); } } module.exports = {Pill}; <file_sep>/test/e2e/multiselect.test.js const {assert, getDriver} = require('vl-ui-core').Test.Setup; const VlMultiSelectPage = require('./pages/vl-multiselect.page'); describe('vl-multiselect', async () => { let vlMultiSelectPage; before(async () => { vlMultiSelectPage = new VlMultiSelectPage(getDriver()); return vlMultiSelectPage.load(); }); afterEach(async () => { await vlMultiSelectPage.closeAnyOpenDropdowns(); }); it('als gebruiker kan ik de geselecteerde items opvragen', async () => { const multiselect = await vlMultiSelectPage.getVoorgeselecteerdeMultiselect(); const selectedItems = await multiselect.getSelectedItems(); assert.isTrue(selectedItems.some((item) => item.text === 'Brugge')); assert.isTrue(selectedItems.some((item) => item.value === 'Bruges')); }); it('als gebruiker kan ik een optie selecteren en deze zal dan in de combobox getoond worden', async () => { const multiselect = await vlMultiSelectPage.getStandardMultiselect(); const selectedItems = await multiselect.getSelectedItems(); const unselectedItems = await multiselect.getUnselectedItems(); const itemToSelect = unselectedItems.find((item) => item.text === 'Duitsland'); assert.isFalse(selectedItems.some((i) => i.text === 'Duitsland')); await multiselect.select(itemToSelect); const selectedItemsAfterUpdate = await multiselect.getSelectedItems(); assert.isTrue(selectedItemsAfterUpdate.some((i) => i.text === 'Duitsland')); }); it('de default multiselect heeft geen error of success attribuut', async () => { const multiselect = await vlMultiSelectPage.getStandardMultiselect(); await assert.eventually.isFalse(multiselect.isError()); await assert.eventually.isFalse(multiselect.isSuccess()); }); it('als gebruiker kan ik een gekozen optie verwijderen', async () => { const multiselect = await vlMultiSelectPage.getGegroepeerdeMultiselect(); const selectedItems = await multiselect.getSelectedItems(); const itemToUnSelect = selectedItems.find((item) => item.text === 'Brugge'); assert.isTrue(selectedItems.some((i) => i.text === 'Brugge')); await multiselect.unselect(itemToUnSelect); const selectedItemsAfterUnselect = await multiselect.getSelectedItems(); assert.isFalse(selectedItemsAfterUnselect.some((i) => i.text === 'Brugge')); }); it('als gebruiker kan ik een multiselect definieren als error multiselect', async () => { const multiselect = await vlMultiSelectPage.getErrorMultiselect(); await assert.eventually.isTrue(multiselect.isError()); }); it('als gebruiker kan ik een multiselect definieren als success multiselect', async () => { const multiselect = await vlMultiSelectPage.getSuccessMultiselect(); await assert.eventually.isTrue(multiselect.isSuccess()); }); it('als gebruiker kan ik een multiselect definieren als disabled', async () => { const multiselect = await vlMultiSelectPage.getDisabledMultiselect(); await assert.eventually.isTrue(multiselect.isDisabled()); }); it('het aantal resultaten van een zoekopdracht kan beperkt worden', async () => { const multiselect = await vlMultiSelectPage.getMultiselectMetSpecifiekAantalResultaten(); await multiselect.searchByPartialText('straat'); await assert.eventually.equal(multiselect.getNumberOfSearchResults(), 5); }); it('het aantal resultaten van een zoekopdracht is standaard niet beperkt', async () => { const multiselect = await vlMultiSelectPage.getMultiselectMetOnbeperkteResultaten(); await multiselect.searchByPartialText('straat'); await assert.eventually.isAbove(multiselect.getNumberOfSearchResults(), 4); }); it('als gebruiker kan ik luisteren naar een change event en onChange zal er een extra attribuut gezet worden', async () => { const multiselect = await vlMultiSelectPage.getChangeEventMultiselect(); await assert.eventually.isFalse(multiselect.hasAttribute('changed')); await multiselect.selectByValue('Germany'); await assert.eventually.isTrue(multiselect.hasAttribute('changed')); }); it('als gebruiker kan ik de multiselect via enable/disable-methode in/uit-schakelen', async () => { const multiselect = await vlMultiSelectPage.getEnableDisableMethodeMultiselect(); await vlMultiSelectPage.disable(); await assert.eventually.isTrue(multiselect.isDisabled()); await vlMultiSelectPage.enable(); await assert.eventually.isFalse(multiselect.isDisabled()); }); it('als gebruiker kan ik programmatorisch (een) waarde(s) toevoegen/verwijderen in de multiselect', async () => { const multiselect = await vlMultiSelectPage.getSetGetMethodeMultiselect(); await assert.eventually.isEmpty(multiselect.getSelectedItems()); await vlMultiSelectPage.kiesDuitsland(); const de = await multiselect.getSelectedItems(); assert.isTrue(de.some((i) => i.text === 'Duitsland')); await vlMultiSelectPage.kiesBelgieEnNederland(); const nlBe = await multiselect.getSelectedItems(); assert.isTrue(de.some((i) => i.text === 'Duitsland')); assert.isTrue(nlBe.some((i) => i.text === 'België')); assert.isTrue(nlBe.some((i) => i.text === 'Nederland')); await assert.eventually.lengthOf(multiselect.getSelectedItems(), 3); await vlMultiSelectPage.verwijderSelectie(); await assert.eventually.lengthOf(multiselect.getSelectedItems(), 2); }); it('als een multiselect boven een datepicker gerenderd wordt, kunnen zowel de multiselect als de datepicker correct gebruikt worden', async () => { const multiselect = await vlMultiSelectPage.getDatepickerMultiselect(); const datepicker = await vlMultiSelectPage.getDatepicker(); await datepicker.selectYear(2018); await datepicker.selectMonth('augustus'); await datepicker.selectDay(29); await assert.eventually.equal(datepicker.getInputValue(), `29.08.2018`); await multiselect.selectByValue('Germany'); const selectedItems = await multiselect.getSelectedItems(); assert.isTrue(selectedItems.some((item) => item.text === 'Duitsland')); }); it('als gebruiker kan ik opties groeperen', async () => { const multiselect = await vlMultiSelectPage.getGegroepeerdeMultiselect(); await assert.eventually.isTrue(multiselect.isGrouped()); await assert.eventually.isTrue(multiselect.hasHeadings()); }); it('de datepicker kan niet geopend worden wanneer de multiselect geopend is', async () => { const multiselect = await vlMultiSelectPage.getDatepickerMultiselect(); const datepicker = await vlMultiSelectPage.getDatepicker(); await multiselect.open(); await assert.isRejected(datepicker.selectDay(4)); }); it('als de gebruiker de multiselect opent wanneer de datepicker zichtbaar is, zal de datepicker verdwijnen', async () => { const multiselect = await vlMultiSelectPage.getDatepickerMultiselect(); const datepicker = await vlMultiSelectPage.getDatepicker(); await assert.eventually.isFalse(datepicker.isOpen()); await datepicker.open(); await assert.eventually.isTrue(datepicker.isOpen()); await multiselect.open(); await assert.eventually.isTrue(multiselect.isOpen()); await assert.eventually.isFalse(datepicker.isOpen()); }); });
dcf0f11cbc0e4feb6b5ea68fdc44960c755350ba
[ "JavaScript" ]
5
JavaScript
milieuinfo/webcomponent-vl-ui-multiselect
2522b734452613c3c31760fff9039faf9a3c0329
7cf76faad4f8c881eaa463493a1597b9a80c3da8
refs/heads/master
<repo_name>ProgrammedMikey/Pinterest-clone<file_sep>/app/Http/Controllers/SocialAuthController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\SocialAccountService; use Socialite; // socialite namespace use JWTAuth; class SocialAuthController extends Controller { // redirect function public function redirect(){ return Socialite::driver('facebook')->redirect(); } // callback function public function callback(SocialAccountService $service){ // when facebook call us a with token $user = $service->createOrGetUser(Socialite::driver('facebook')->user()); $token = JWTAuth::fromUser($user); // dd($token); return response()->json(['token' => $token]); // return redirect()->to('http://localhost:8080?' . 'token=' . $token); } }<file_sep>/readme.md # Pinterest Clone ### Live Version: https://mdasilva-pinterest.herokuapp.com/ ## User stories: - As an authenticated user, I can link to images. - As an authenticated user, I can delete images that I've linked to. - As an authenticated user, I can see a Pinterest-style wall of all the images I've linked to. - As an unauthenticated user, I can browse other users' walls of images. - As an authenticated user, if I upload an image that is broken, it will be replaced by a placeholder image.
0a30813d7da78fa8014a863d7854fe1244f03726
[ "Markdown", "PHP" ]
2
PHP
ProgrammedMikey/Pinterest-clone
352bc126dd82191fa16a848ed6e5068226e6eb8e
4fad7f24022ce3dbbc41e6017a38d0367af1e840
refs/heads/master
<repo_name>praveenprasannan/webdriverio-yarn-demo<file_sep>/pages/GoogleHomePage.js import Page from './Page'; import constants from '../shared/constants'; class GoogleHomePage extends Page { // Page elements static get searchBox() { return browser.element('#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input'); } static get searchButton() { return browser.element('#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)'); } // Actions static setSearchKey(value) { return this.searchBox.setValue(value); } static clickOnSearch() { return this.searchButton.click(); } // Helper Methods static doGoogleSearch(value) { this.setSearchKey(value); this.clickOnSearch(); return browser.waitUntil(() => this.title().includes(value), constants.BROWSER_WAIT, 'expected the search results page which contains the searched value within wait period'); } } export default GoogleHomePage; <file_sep>/tests/australia_test.js import { expect } from 'chai'; import HomePage from '../pages/AustraliaHomePage'; import constant from '../shared/constants'; describe('Australian Government Tests', () => { it('should open the Aus Govt homepage with the expected title', () => { HomePage.openUrl(constant.AU_HOMEPAGE); expect(HomePage.title()).to.equal('australia.gov.au'); }); it('should open myGov login page', () => { HomePage.clickOnMyGov(); expect(HomePage.title()).to.equal('Sign-in - myGov'); }); }); <file_sep>/shared/constants.js const constants = { BROWSER_WAIT: 3000, AU_HOMEPAGE: 'http://australia.gov.au/' }; export default constants; <file_sep>/README.md # WebdriverIO demo using Yarn Uses http://webdriver.io to execute selenium web tests. Tests can be run locally using the wdio.conf.js config file, which uses chromedriver to execute browser tests. ### Environment Setup #### 1. Global Dependencies * Install [Node.js](https://nodejs.org/en/) ``` $ brew install node ``` * Install [Yarn](https://yarnpkg.com/lang/en/docs/install/) ``` $ brew install yarn ``` #### 2. Project Dependencies * Install Node modules ``` $ yarn install ``` ### Running Tests * To run tests (for the test suite) ``` $ yarn test ``` * Run a single test (if you use the same folder structure) ``` $ yarn test --spec tests/folder/filename.js ``` ### Docs & further reading * http://webdriver.io * http://webdriver.io/guide/usage/selectors.html * http://blog.kevinlamping.com/selecting-elements-in-webdriverio <file_sep>/tests/google_test.js import { expect } from 'chai'; import HomePage from '../pages/GoogleHomePage'; describe('Google Tests', () => { it('should open the Google homepage with the expected title', () => { HomePage.open(); expect(HomePage.title()).to.equal('Google'); }); it('should do a search to get results', () => { HomePage.doGoogleSearch('sydney'); expect(HomePage.title()).to.equal('sydney - Google Search'); }); });
20582e2d3b664780a76f03976ff9555c2693b154
[ "JavaScript", "Markdown" ]
5
JavaScript
praveenprasannan/webdriverio-yarn-demo
90f12deac40920be9c7e83ffa6c83733e43a1bd7
70774cbfa4b3b6bf7854bf45da6876b2aa8b8e50
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Sun Mar 11 11:25:11 2018 @author: <NAME> The codes at https://github.com/analog-rl/Easy21 were referred to in creating this code """ #%% import os import sys # get the directory and add its path to python search path for modules dirpath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(dirpath) import numpy as np from easy21 import * import random import matplotlib.cm as cm # dealer card value: 1-10, player sum: 1-21 # note the state S consists of the dealer's showing card and the player's sum # initialization class MC_Agent: def __init__(self,environment,N0): self.N0 = N0; self.env = environment; # Intialize state value function to zero self.V= np.zeros((self.env.dealer_value_count,self.env.player_value_count)) # Initialize state-action pair to zero self.Q = np.zeros((self.env.dealer_value_count,self.env.player_value_count,self.env.action_count)) # N(s,a) is the number of times that action a has been selected from state s. self.N = np.zeros((self.env.dealer_value_count,self.env.player_value_count,self.env.action_count)) # return at each state-action pair, using a list of list of list self.G = []; for k in range(self.env.dealer_value_count*self.env.player_value_count): G1 =[]; for j in range (self.env.action_count): G1.append([]) self.G.append(G1) self.episodes = 0 self.count_wins = 0 # selecting an action according to the epsilon-greedy policy def select_action(self,state): dealer_id = state.dealer -1; player_id = state.player - 1; epsilon = self.N0/(self.N0+sum(self.N[dealer_id, player_id,:])) if random.random()< epsilon: if random.random() < 0.5: action = Action.hit; else: action = Action.stick else: action = Action.to_action(np.argmax(self.Q[dealer_id, player_id,:])) return action def train(self,episodes): for episode in range(episodes): episode_pairs = [] # random start s = self.env.gen_start_state() # generate an episode with the epsilon-greedy policy while not s.is_terminal: a = self.select_action(s) # update N(s,a) self.N[s.dealer-1,s.player-1,Action.as_int(a)] += 1 # store action-value pairs episode_pairs.append((s,a)) # execute action s, r= self.env.step(s,a) self.count_wins = self.count_wins+1 if r==1 else self.count_wins for s,a in episode_pairs: dealer_id = s.dealer-1 player_id = s.player-1 # update the state-action-return pair idx = dealer_id*10+player_id self.G[idx][Action.as_int(a)].append(r) # update Q(s,a) using a varying step size alpha = 1/N(st,at) alpha = 1.0/self.N[dealer_id,player_id,Action.as_int(a)] error = np.mean(self.G[idx][Action.as_int(a)]) - self.Q[dealer_id,player_id,Action.as_int(a)] self.Q[dealer_id,player_id,Action.as_int(a)] += alpha*error # update V(s) # ideally update of V(s) should happen only ONCE after update of Q(s,a) for all s,a in the episode; # but for coding simplifity, it is updated right after every update of Q(s,a). This should not influence the final results. self.V[dealer_id,player_id] = max(self.Q[dealer_id,player_id,:]) self.episodes = self.episodes + episodes def plot_frame(self, ax): def get_state_val(x,y): return self.V[x,y] X = np.arange(0,self.env.dealer_value_count,1) Y = np.arange(0,self.env.player_value_count,1) X,Y = np.meshgrid(X,Y) Z = get_state_val(X,Y) surf = ax.plot_surface(X,Y,Z,cmap=cm.bwr,antialiased=False) return surf #%% Train and generate the value function #import matplotlib.pyplot as plt #from mpl_toolkits.mplot3d import Axes3D #import matplotlib.cm as cm # # #N0 = 100 #agent = MC_Agent(Environment(),N0) #for i in range(1): # agent.train(50000) # #fig = plt.figure() #ax = fig.add_subplot(111,projection ='3d') #agent.plot_frame(ax) #plt.title('value function after %d episodes' % agent.episodes) #ax.set_xlabel('Dealer showing') #ax.set_ylabel('Player sum') #ax.set_zlabel('V(s)') #ax.set_xticks(range(1,agent.env.dealer_value_count+1)) #ax.set_yticks(range(1,agent.env.player_value_count+1)) #plt.show() #plt.savefig('Value function.png') # #%% animate the learning process #import matplotlib.animation as animation #def update(frame): # agent.train(10000) # # ax.clear() # surf = agent.plot_frame(ax) # plt.title('winning perc: %f frame:%s ' % (float(agent.count_wins)/agent.episodes,frame)) # fig.canvas.draw() # return surf # # #import matplotlib.pyplot as plt #import matplotlib.animation as animation #from mpl_toolkits.mplot3d import Axes3D #import matplotlib.cm as cm #N0 = 100 #agent = MC_Agent(Environment(),N0) ##fig=plt.figure('N0=%d' % N0) #fig = plt.figure('N100') #ax = fig.add_subplot(111,projection ='3d') #ani = animation.FuncAnimation(fig,update,4,repeat=False) # #ani.save('MC_process.gif',writer = 'imagemagick',fps=3) #plt.show() # show the gif #from IPython.display import Image #Image(url="MC_process.gif")<file_sep># -*- coding: utf-8 -*- """ Created on Wed Mar 7 10:12:25 2018 @author: <NAME> Reference: https://github.com/analog-rl/Easy21 """ #%% import random import matplotlib.pyplot as plt import numpy as np from enum import Enum class Action(Enum): stick = 0 hit = 1 class Card: def __init__(self,force_black = False): self.value = random.randint(1,10) if force_black or random.randint(1,3) != 3: self.is_black = True; else: self.is_black = False; self.value = -self.value; class State: def __init__ (self, dealer, player, is_terminal = False): self.dealer = dealer # the summation of the dealer self.player = player # the summation of the player self.is_terminal = is_terminal # whether the state is terminal def step (state, action): new_state = state; reward = 0; if action == Action.hit: new_state.player += Card().value; if new_state.player > 21 or new_state.player <1: new_state.is_terminal = True; reward = -1 return new_state, reward elif action == Action.stick: while not new_state.is_terminal: new_state.dealer += Card().value; if new_state.dealer > 21 or new_state.dealer < 1: new_state.is_terminal = True; reward = 1 elif new_state.dealer> 17: new_state.is_terminal = True; if new_state.player > new_state.dealer: reward = 1 elif new_state.player < new_state.dealer: reward = -1 return new_state, reward #%% Test: whether draws follow a prespecified distribution cards = [None]*10000; for i in np.arange(len(cards)): cards[i] = Card() f = plt.figure(1); plt.subplot(2,1,1) plt.title('Test: the value of the cards follow a uniform distribution \n between 1 and 10') card_value = [abs(card.value) for card in cards] plt.hist(card_value) plt.subplot(2,1,2) plt.title('Test: the probability of a red card (0) and a black card (1) \n are 1/3 and 2/3, respectively') card_is_black = [card.is_black for card in cards] plt.hist(card_is_black) plt.subplots_adjust(hspace = 0.6 ) # adjust the horizontal space between subplots #plt.show() plt.savefig("test1.png"); #%% Test: If the player’s sum exceeds 21, or becomes less than 1, then he “goes bust” and loses the game (reward -1) def test_player_bust(): state = State(Card(True).value, Card(True).value) action = Action.hit while not state.is_terminal: state, reward = step(state,action) return state, reward import matplotlib.pyplot as plt plt.figure(2) values = []; for i in range(10000): state,reward = test_player_bust() if state.player > 21 or state.player < 1: values.append(1) else: values.append(-1) print("error! The player's score should be >21 or <1 at the terminal state!") plt.hist(values) plt.title("Test: player bust >21 or <1") plt.savefig("test2.png") #%% Test: player stick. def test_player_stick(): state = State(Card(True).value, Card(True).value) action = Action.stick while not state.is_terminal: state, reward = step(state,action) return state, reward import matplotlib.pyplot as plt values = [] for i in range(10000): state,reward = test_player_stick() if state.dealer > 21 or state.dealer < 1: if reward == 1: values.append(1) else: values.append(-1) print('error! The player should have won!') elif state.player > state.dealer: if reward == 1: values.append(1) else: values.append(-2) print('error! The player should have won!') elif state.player == state.dealer: if reward == 0: values.append(1) else: values.append(-3) print('error! It should be a tie!') plt.figure(3) plt.hist(values) plt.title("Test: player stick") plt.savefig("test3.png") #%% play def play(): dealer = Card(True).value player = Card(True).value state = State(dealer,player) reward = 0 while not state.is_terminal: # print('dealer score:%d, player score:%d' % (state.dealer, state.player)) if state.player > 17: action = Action.stick else: action = Action.hit state, reward = step(state,action) # print('dealer score:%d, player score:%d' % (state.dealer, state.player)) print("reward = %d" % reward); return reward <file_sep># -*- coding: utf-8 -*- """ Implementation of Sarsa(\lambda) with binary features and linear function approximation for Easy21 following the algorithm presented in Section~12.7 of [Sutton & Barto, 2017] @author: Boran (Pan) Zhao """ #%% import os import sys # get the directory and add its path to python search path for modules dirpath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(dirpath) import numpy as np from easy21 import * from easy21_mc_control import * import random # dealer card value: 1-10, player sum: 1-21 # note the state S consists of the dealer's showing card and the player's summation # initialization class Sarsa_Approx_Agent: def __init__(self,environment,N0,lam): self.N0 = N0; self.lam = lam self.gamma = 1 self.mse = float('inf') self.env = environment; # Intialize state value function to zero self.V= np.zeros((self.env.dealer_value_count,self.env.player_value_count)) # Initialize state-action pair to zero self.Q = np.zeros((self.env.dealer_value_count,self.env.player_value_count,self.env.action_count)) # weight vecotor self.w = np.zeros((3,6,2)) # eligibility trace for the weight vector self.E = np.zeros((3,6,2)) self.features ={'dealer':[[1,4], [4,7],[7,10]], 'player':[[1, 6],[4, 9],[7,12],[10, 15],[13, 18],[16, 21]], 'action':[Action.hit,Action.stick]} self.episodes = 0 self.count_wins = 0 # determine phi(s,a) def feature_eval(self,s,a): Phi = np.zeros((3,6,2)) for dealer_interval_id, dealer_interval in enumerate(self.features['dealer']): if dealer_interval[0] <= s.dealer <= dealer_interval[1]: for player_interval_id, player_interval in enumerate(self.features['player']): if player_interval[0] <= s.player <= player_interval[1]: Phi[dealer_interval_id,player_interval_id,Action.as_int(a)]=1 return Phi # selecting an action according to the epsilon-greedy policy def select_action(self,state): dealer_id = state.dealer -1 player_id = state.player - 1 # epsilon for exploration # epsilon = self.N0/(self.N0+sum(self.N[dealer_id, player_id,:])) # use a constant epsilon for exploration epsilon = 0.05 if random.random()< epsilon: if random.random() < 0.5: action = Action.hit; else: action = Action.stick else: action = Action.to_action(np.argmax(self.Q[dealer_id, player_id,:])) return action def train(self,num_episodes): for episode in range(num_episodes): # random start s = self.env.gen_start_state() # reset the eligibility traces.... Is this really necessary? self.E = np.zeros((3,6,2)) # generate an episode with the epsilon-greedy policy and update Q(s,a) and E(s,a) in each step a = self.select_action(s) while not s.is_terminal: # update N(s,a) # self.N[s.dealer-1,s.player-1,Action.as_int(a)] += 1 # execute action a and observe s_new, r s_new, r= self.env.step(s,a) td_error = r # identify the active features and update their corresponding eligibility trace elements Phi =self.feature_eval(s,a) td_error -= np.sum(self.w*Phi) # accumulating traces self.E += Phi # replacing traces # self.E = Phi # for dealer_interval_id, dealer_interval in enumerate(self.features['dealer']): # if dealer_interval[0] <= s.dealer <= dealer_interval[1]: # for player_interval_id, player_interval in enumerate(self.features['player']): # if player_interval[0] <= s.player <= player_interval[1]: # td_error -= self.w[dealer_interval_id,dealer_interval_id,Action.as_int(a)] # # accumulating traces # self.E[dealer_interval_id,dealer_interval_id,Action.as_int(a)] += 1 # # replacing traces # self.E[dealer_interval_id,dealer_interval_id,Action.as_int(a)] = 1 if not s_new.is_terminal: # select a new action a_new using policy dervied from Q a_new = self.select_action(s_new) Phi = self.feature_eval(s_new,a_new) td_error += np.sum(self.gamma*(self.w*Phi)) # using a constant step size for exploration alpha = 0.05 #update the weight vector and eligibility trace self.w += alpha*td_error*self.E self.E *= self.gamma*self.lam # update s and s = s_new if not s_new.is_terminal: a = a_new self.count_wins = self.count_wins+1 if r==1 else self.count_wins # report the mean-squared error mean((Q(s,a)-Qmc(s,a))^2 and the winning percentage self.episodes = self.episodes + num_episodes # update the Q function self.update_Q() def update_Q(self): for dealer_id in range(self.Q.shape[0]): for player_id in range(self.Q.shape[1]): for action_id in range(self.Q.shape[2]): Phi = self.feature_eval(State(dealer_id+1,player_id+1), Action.to_action(action_id)) self.Q[dealer_id,player_id,action_id] = np.sum(Phi*self.w) def update_V(self): for dealer_id in range(self.V.shape[0]): for player_id in range(self.V.shape[1]): self.V[dealer_id,player_id] = max(self.Q[dealer_id,player_id,:]) def plot_frame(self, ax): def get_state_val(x,y): return self.V[x,y] X = np.arange(0,self.env.dealer_value_count,1) Y = np.arange(0,self.env.player_value_count,1) X,Y = np.meshgrid(X,Y) Z = get_state_val(X,Y) surf = ax.plot_surface(X,Y,Z,cmap=cm.bwr,antialiased=False) return surf #%% Train and generate the Q function with Monte Carlo control #import matplotlib.pyplot as plt #from mpl_toolkits.mplot3d import Axes3D #import matplotlib.cm as cm # #N0 = 100 #mc_agent = MC_Agent(Environment(),N0) #mc_agent.train(int(1e6)) #print('After %s episodes, winning percentage:%f' % (mc_agent.episodes, mc_agent.count_wins/mc_agent.episodes)) # #fig = plt.figure(1) #ax = fig.add_subplot(111,projection ='3d') #mc_agent.plot_frame(ax) #plt.title('value function after %d episodes' % mc_agent.episodes) #ax.set_xlabel('Dealer showing') #ax.set_ylabel('Player sum') #ax.set_zlabel('V(s)') #ax.set_xticks(range(1,mc_agent.env.dealer_value_count+1)) #ax.set_yticks(range(1,mc_agent.env.player_value_count+1)) ##plt.savefig('Value function.png') #plt.show() #Qmc = mc_agent.Q #%% Train with Sarsa(lambda) with linear function approximation using different lambda while printing the MSE of Q import matplotlib.pyplot as plt Lambda = np.linspace(0,1,11) fig = plt.figure('MSE under different lambda values') mse = [] Color = ['b','g','r','c','m','y','k'] LineStyle =['-','--',':','-.'] for i in range(len(Lambda)): mse.append([]) # Learn and plot the result for lam_id,lam in enumerate(Lambda): # print('lambda = %s'% lam) agent = Sarsa_Approx_Agent(Environment(),N0,lam) for i in range(1000): agent.train(1) agent.mse = np.mean((agent.Q-Qmc)**2) mse[lam_id].append(agent.mse) print('lambda = %s, MSE: %f, winning percentage:%f' % (agent.lam, agent.mse, agent.count_wins/agent.episodes)) X = list(range(1,len(mse[0])+1)) fig = plt.figure('MSE against lambda') plt.plot(Lambda, [x[-1] for x in mse]) plt.xlabel('lambda') plt.ylabel('mean-squared error') plt.savefig('MSE against lambda under linear approximation') plt.show() fig = plt.figure('Learning process') plt.subplot(211) plt.plot(X,mse[0],color = Color[0], linestyle=LineStyle[0%4]) plt.xlabel('episode') plt.ylabel('MSE') plt.title('lambda = 0') plt.subplot(212) plt.plot(X,mse[-1],color = Color[0], linestyle=LineStyle[0%4]) plt.xlabel('episode') plt.ylabel('MSE') plt.title('lambda = 1') plt.savefig('Learning process for lambda 0 and 1 under linear approximation') plt.show() <file_sep># -*- coding: utf-8 -*- """ Implementation of Sarsa(\lambda) for Easy21 @author: <NAME> """ #%% import os import sys # get the directory and add its path to python search path for modules dirpath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(dirpath) import numpy as np from easy21 import * from easy21_mc_control import * import random # dealer card value: 1-10, player sum: 1-21 # note the state S consists of the dealer's showing card and the player's sum # initialization class Sarsa_Agent: def __init__(self,environment,N0,lam): self.N0 = N0; self.lam = lam self.gamma = 1 self.mse = float('inf') self.env = environment; # Intialize state value function to zero self.V= np.zeros((self.env.dealer_value_count,self.env.player_value_count)) # Initialize state-action pair to zero self.Q = np.zeros((self.env.dealer_value_count,self.env.player_value_count,self.env.action_count)) # N(s,a) is the number of times that action a has been selected from state s. self.N = np.zeros((self.env.dealer_value_count,self.env.player_value_count,self.env.action_count)) # eligibility trace for every state-action pair self.E = np.zeros((self.env.dealer_value_count,self.env.player_value_count,self.env.action_count)) self.episodes = 0 self.count_wins = 0 # selecting an action according to the epsilon-greedy policy def select_action(self,state): dealer_id = state.dealer -1; player_id = state.player - 1; epsilon = self.N0/(self.N0+sum(self.N[dealer_id, player_id,:])) if random.random()< epsilon: if random.random() < 0.5: action = Action.hit; else: action = Action.stick else: action = Action.to_action(np.argmax(self.Q[dealer_id, player_id,:])) return action def train(self,num_episodes): for episode in range(num_episodes): # random start s = self.env.gen_start_state() # generate an episode with the epsilon-greedy policy and update Q(s,a) and E(s,a) in each step a = self.select_action(s) while not s.is_terminal: # update N(s,a) self.N[s.dealer-1,s.player-1,Action.as_int(a)] += 1 # execute action a and observe s_new, r s_new, r= self.env.step(s,a) dealer_id = s.dealer-1 player_id = s.player-1 if s_new.is_terminal: Q_new = 0 else: # select a new action a_new using policy dervied from Q a_new = self.select_action(s_new) dealer_id_new = s_new.dealer-1 player_id_new = s_new.player-1 Q_new = self.Q[dealer_id_new,player_id_new,Action.as_int(a_new)] # using a varying step size alpha = 1/N(st,at) alpha = 1.0/self.N[dealer_id,player_id,Action.as_int(a)] # calculate TD error td_error = r + self.gamma*Q_new - self.Q[dealer_id,player_id,Action.as_int(a)] # update the eligibility trace self.E[dealer_id,player_id, Action.as_int(a)] += 1 #update the Q and E for all state-action pairs self.Q += alpha*td_error*self.E self.E *= self.gamma*self.lam # for q,e in np.nditer([self.Q,self.E],op_flags =['readwrite']): # q[...] = q + alpha*td_error*e # e[...] = self.gamma*self.lam*e # update s and s = s_new if not s_new.is_terminal: a = a_new self.count_wins = self.count_wins+1 if r==1 else self.count_wins # report the mean-squared error mean((Q(s,a)-Qmc(s,a))^2 and the winning percentage self.episodes = self.episodes + num_episodes def update_V(self): for dealer_id in range(self.V.shape[0]): for player_id in range(self.V.shape[1]): self.V[dealer_id,player_id] = max(self.Q[dealer_id,player_id,:]) def plot_frame(self, ax): def get_state_val(x,y): return self.V[x,y] X = np.arange(0,self.env.dealer_value_count,1) Y = np.arange(0,self.env.player_value_count,1) X,Y = np.meshgrid(X,Y) Z = get_state_val(X,Y) surf = ax.plot_surface(X,Y,Z,cmap=cm.bwr,antialiased=False) return surf #%% Train and generate the Q function with Monte Carlo control import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.cm as cm N0 = 100 mc_agent = MC_Agent(Environment(),N0) mc_agent.train(int(1e6)) print('After %s episodes, winning percentage:%f' % (mc_agent.episodes, mc_agent.count_wins/mc_agent.episodes)) fig = plt.figure(1) ax = fig.add_subplot(111,projection ='3d') mc_agent.plot_frame(ax) plt.title('value function after %d episodes' % mc_agent.episodes) ax.set_xlabel('Dealer showing') ax.set_ylabel('Player sum') ax.set_zlabel('V(s)') ax.set_xticks(range(1,mc_agent.env.dealer_value_count+1)) ax.set_yticks(range(1,mc_agent.env.player_value_count+1)) plt.savefig('Value function from MC.png') plt.show() Qmc = mc_agent.Q #%% Train with Sarsa(lambda) using different lambda while printing the MSE of Q Lambda = np.linspace(0,1,10) fig = plt.figure('MSE under different lambda values') mse = [] Color = ['b','g','r','c','m','y','k'] LineStyle =['-','--',':','-.'] for i in range(len(Lambda)): mse.append([]) # Learn and plot the result for lam_id,lam in enumerate(Lambda): # print('lambda = %s'% lam) agent = Sarsa_Agent(Environment(),N0,lam) for i in range(1000): agent.train(1) agent.mse = np.mean((agent.Q-Qmc)**2) mse[lam_id].append(agent.mse) print('lambda = %s, MSE: %f, winning percentage:%f' % (agent.lam, agent.mse, agent.count_wins/agent.episodes)) X = list(range(1,len(mse[0])+1)) fig = plt.figure('MSE against lambda') plt.plot(Lambda, [x[-1] for x in mse]) plt.xlabel('lambda') plt.ylabel('mean-squared error') plt.savefig('MSE against lambda') plt.show() fig = plt.figure('Learning process') plt.subplot(211) plt.plot(X,mse[0],color = Color[0], linestyle=LineStyle[0%4]) plt.xlabel('episode') plt.ylabel('MSE') plt.title('lambda = 0') plt.subplot(212) plt.plot(X,mse[-1],color = Color[0], linestyle=LineStyle[0%4]) plt.xlabel('episode') plt.ylabel('MSE') plt.title('lambda = 1') plt.savefig('Learning process for lambda 0 and 1') plt.show() ##%% animate the learning process (does not work at this moment) #import matplotlib.animation as animation #def update(frame): # agent.train(10000) # # ax.clear() # surf = agent.plot_frame(ax) # plt.title('winning perc: %f frame:%s ' % (float(agent.count_wins)/agent.episodes,frame)) # fig.canvas.draw() # return surf # #import matplotlib.pyplot as plt #import matplotlib.animation as animation #from mpl_toolkits.mplot3d import Axes3D #import matplotlib.cm as cm #N0 = 100 #agent = MC_Agent(Environment(),N0) ##fig=plt.figure('N0=%d' % N0) #fig = plt.figure('N100') #ax = fig.add_subplot(111,projection ='3d') #ani = animation.FuncAnimation(fig,update,4,repeat=False) # #ani.save('MC_process.gif',writer = 'imagemagick',fps=3) #plt.show() ## show the gif ##from IPython.display import Image ##Image(url="MC_process.gif")<file_sep># Easy21 1 Implementation of Easy21: easy21-implement.py 2 Monte-Carlo Control in Easy21: easy21_mc_control.py 3 TD Learning in Easy21: easy21_sarsa_lambda.py 4 Linear Function Approximation in Easy21: easy21_sarsa_lambda_approx 5 Discussion What are the pros and cons of bootstrapping in Easy21?<br> Pros: no need to wait until the end of an episode, accelerate the learning process, decrease the variance <br> Cons: may introduce bias Would you expect bootstrapping to help more in blackjack or Easy21 ? Why? <br> Help more in Easy21, because it takes a longer time on average to finish an episode in easy21 due to the fact that a value of a card can be negative depending on its color. What are the pros and cons of function approximation in Easy21?<br> Pros: memory saving, learning speed acceleration<br> Cons: can only solve the problem approximately since a function approximator cannot represent all the state-action values accurately How would you modify the function approximator suggested in this section to get better results in Easy21?<br> Have no idea right now. <file_sep># -*- coding: utf-8 -*- """ Created on Sun Mar 11 15:21:25 2018 @author: <NAME> """ # -*- coding: utf-8 -*- """ Created on Wed Mar 7 10:12:25 2018 @author: <NAME> The codes at https://github.com/analog-rl/Easy21 were referred to in creating this code """ #%% import random import matplotlib.pyplot as plt import copy from enum import Enum class Action(Enum): hit = 0 stick = 1 @staticmethod def to_action(n): return Action.hit if n==0 else Action.stick @staticmethod def as_int(a): return 0 if a==Action.hit else 1 class Card: def __init__(self,force_black = False): self.value = random.randint(1,10) if force_black or random.randint(1,3) != 3: self.is_black = True; else: self.is_black = False; self.value = -self.value; class State: def __init__ (self, dealer, player, is_terminal = False): self.dealer = dealer # the summation of the dealer self.player = player # the summation of the player self.is_terminal = is_terminal # whether the state is terminal class Environment: def __init__(self): self.dealer_value_count = 10; # [1:10], note that black card is enforced at the start self.player_value_count = 21; # [1:21] self.action_count = 2; # hit and stick def gen_start_state(self): s = State(Card(True).value,Card(True).value) return s def step(self, state, action): # new_state = state does not work because modifying new_state will influence state new_state = copy.copy(state) reward = 0; if action == Action.hit: new_state.player += Card().value; if new_state.player > 21 or new_state.player <1: new_state.is_terminal = True; reward = -1 return new_state, reward elif action == Action.stick: while not new_state.is_terminal: new_state.dealer += Card().value; if new_state.dealer > 21 or new_state.dealer < 1: new_state.is_terminal = True; reward = 1 elif new_state.dealer> 17: new_state.is_terminal = True; if new_state.player > new_state.dealer: reward = 1 elif new_state.player < new_state.dealer: reward = -1 return new_state, reward
0afd9a76b8d751b1170a2a4fa73af488b9f9a058
[ "Markdown", "Python" ]
6
Python
vishalgandhi804/Easy21
d5b52a189158e9ffe0735cda4bd6c4a34e0afc62
8780a4c9f895ba89bed6deabdf47d1e1e1887099
refs/heads/master
<repo_name>angelomesquita/WorkshopGit<file_sep>/application/Bootstrap.php <?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { public function _initTestando() { $this=$this; $x = 10; $c = 10; } }
d9a6b9677e06f2a1e7370b865bcc355a49ff138e
[ "PHP" ]
1
PHP
angelomesquita/WorkshopGit
fb17dc06774e8a5c9273864bd024325b7bf3be6b
e4d8611325ce0a4beafd5ea059f418f05776201a
refs/heads/master
<repo_name>michael-simons/classgraph<file_sep>/src/main/java/io/github/classgraph/MethodInfo.java /* * This file is part of ClassGraph. * * Author: <NAME> * * Hosted at: https://github.com/classgraph/classgraph * * -- * * The MIT License (MIT) * * Copyright (c) 2019 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.classgraph; import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import io.github.classgraph.ClassInfo.RelType; import io.github.classgraph.Classfile.MethodTypeAnnotationDecorator; import nonapi.io.github.classgraph.types.ParseException; import nonapi.io.github.classgraph.types.TypeUtils; import nonapi.io.github.classgraph.types.TypeUtils.ModifierType; import nonapi.io.github.classgraph.utils.Assert; import nonapi.io.github.classgraph.utils.LogNode; /** * Holds metadata about methods of a class encountered during a scan. All values are taken directly out of the * classfile for the class. */ public class MethodInfo extends ScanResultObject implements Comparable<MethodInfo>, HasName { /** Defining class name. */ private String declaringClassName; /** Method name. */ private String name; /** Method modifiers. */ private int modifiers; /** Method annotations. */ AnnotationInfoList annotationInfo; /** * The JVM-internal type descriptor (missing type parameters, but including types for synthetic and mandated * method parameters). */ private String typeDescriptorStr; /** The parsed type descriptor. */ private transient MethodTypeSignature typeDescriptor; /** * The type signature (may have type parameter information included, if present and available). Method parameter * types are unaligned. */ private String typeSignatureStr; /** The parsed type signature (or null if none). Method parameter types are unaligned. */ private transient MethodTypeSignature typeSignature; /** * Unaligned parameter names. These are only produced in JDK8+, and only if the commandline switch `-parameters` * is provided at compiletime. */ private String[] parameterNames; /** * Unaligned parameter modifiers. These are only produced in JDK8+, and only if the commandline switch * `-parameters` is provided at compiletime. */ private int[] parameterModifiers; /** Unaligned parameter annotations. */ AnnotationInfo[][] parameterAnnotationInfo; /** Aligned method parameter info. */ private transient MethodParameterInfo[] parameterInfo; /** True if this method has a body. */ private boolean hasBody; /** The type annotation decorators for the {@link MethodTypeSignature} instance. */ private List<MethodTypeAnnotationDecorator> typeAnnotationDecorators; private String[] thrownExceptionNames; private transient ClassInfoList thrownExceptions; // ------------------------------------------------------------------------------------------------------------- /** Default constructor for deserialization. */ MethodInfo() { super(); } /** * Constructor. * * @param definingClassName * The name of the enclosing class. * @param methodName * The name of the method. * @param methodAnnotationInfo * The list of {@link AnnotationInfo} objects for any annotations on the method. * @param modifiers * The method modifier bits. * @param typeDescriptorStr * The internal method type descriptor string. * @param typeSignatureStr * The internal method type signature string, or null if none. * @param parameterNames * The parameter names. * @param parameterModifiers * The parameter modifiers. * @param parameterAnnotationInfo * The parameter {@link AnnotationInfo}. * @param hasBody * True if this method has a body. */ MethodInfo(final String definingClassName, final String methodName, final AnnotationInfoList methodAnnotationInfo, final int modifiers, final String typeDescriptorStr, final String typeSignatureStr, final String[] parameterNames, final int[] parameterModifiers, final AnnotationInfo[][] parameterAnnotationInfo, final boolean hasBody, final List<MethodTypeAnnotationDecorator> methodTypeAnnotationDecorators, final String[] thrownExceptionNames) { super(); this.declaringClassName = definingClassName; this.name = methodName; this.modifiers = modifiers; this.typeDescriptorStr = typeDescriptorStr; this.typeSignatureStr = typeSignatureStr; this.parameterNames = parameterNames; this.parameterModifiers = parameterModifiers; this.parameterAnnotationInfo = parameterAnnotationInfo; this.annotationInfo = methodAnnotationInfo == null || methodAnnotationInfo.isEmpty() ? null : methodAnnotationInfo; this.hasBody = hasBody; this.typeAnnotationDecorators = methodTypeAnnotationDecorators; this.thrownExceptionNames = thrownExceptionNames; } // ------------------------------------------------------------------------------------------------------------- /** * Returns the name of the method. Note that constructors are named {@code "<init>"}, and private static class * initializer blocks are named {@code "<clinit>"}. * * @return The name of the method. */ @Override public String getName() { return name; } /** * Returns the modifier bits for the method. * * @return The modifier bits for the method. */ public int getModifiers() { return modifiers; } /** * Get the method modifiers as a String, e.g. "public static final". For the modifier bits, call * {@link #getModifiers()}. * * @return The modifiers for the method, as a String. */ public String getModifiersStr() { final StringBuilder buf = new StringBuilder(); TypeUtils.modifiersToString(modifiers, ModifierType.METHOD, isDefault(), buf); return buf.toString(); } /** * Get the {@link ClassInfo} object for the class that declares this method. * * @return The {@link ClassInfo} object for the declaring class. * * @see #getClassName() */ @Override public ClassInfo getClassInfo() { return super.getClassInfo(); } /** * Returns the parsed type descriptor for the method, which will not include type parameters. If you need * generic type parameters, call {@link #getTypeSignature()} instead. * * @return The parsed type descriptor for the method. */ public MethodTypeSignature getTypeDescriptor() { if (typeDescriptor == null) { try { typeDescriptor = MethodTypeSignature.parse(typeDescriptorStr, declaringClassName); typeDescriptor.setScanResult(scanResult); if (typeAnnotationDecorators != null) { for (final MethodTypeAnnotationDecorator decorator : typeAnnotationDecorators) { decorator.decorate(typeDescriptor); } } } catch (final ParseException e) { throw new IllegalArgumentException(e); } } return typeDescriptor; } /** * Returns the type descriptor string for the method, which will not include type parameters. If you need * generic type parameters, call {@link #getTypeSignatureStr()} instead. * * @return The type descriptor string for the method. */ public String getTypeDescriptorStr() { return typeDescriptorStr; } /** * Returns the parsed type signature for the method, possibly including type parameters. If this returns null, * indicating that no type signature information is available for this method, call {@link #getTypeDescriptor()} * instead. * * @return The parsed type signature for the method, or null if not available. * @throws IllegalArgumentException * if the method type signature cannot be parsed (this should only be thrown in the case of * classfile corruption, or a compiler bug that causes an invalid type signature to be written to * the classfile). */ public MethodTypeSignature getTypeSignature() { if (typeSignature == null && typeSignatureStr != null) { try { typeSignature = MethodTypeSignature.parse(typeSignatureStr, declaringClassName); typeSignature.setScanResult(scanResult); if (typeAnnotationDecorators != null) { for (final MethodTypeAnnotationDecorator decorator : typeAnnotationDecorators) { decorator.decorate(typeSignature); } } } catch (final ParseException e) { throw new IllegalArgumentException( "Invalid type signature for method " + getClassName() + "." + getName() + (getClassInfo() != null ? " in classpath element " + getClassInfo().getClasspathElementURI() : "") + " : " + typeSignatureStr, e); } } return typeSignature; } /** * Returns the type signature string for the method, possibly including type parameters. If this returns null, * indicating that no type signature information is available for this method, call * {@link #getTypeDescriptorStr()} instead. * * @return The type signature string for the method, or null if not available. */ public String getTypeSignatureStr() { return typeSignatureStr; } /** * Returns the parsed type signature for the method, possibly including type parameters. If the type signature * string is null, indicating that no type signature information is available for this method, returns the * parsed type descriptor instead. * * @return The parsed type signature for the method, or if not available, the parsed type descriptor for the * method. */ public MethodTypeSignature getTypeSignatureOrTypeDescriptor() { MethodTypeSignature typeSig = null; try { typeSig = getTypeSignature(); if (typeSig != null) { return typeSig; } } catch (final Exception e) { // Ignore } return getTypeDescriptor(); } /** * Returns the type signature string for the method, possibly including type parameters. If the type signature * string is null, indicating that no type signature information is available for this method, returns the type * descriptor string instead. * * @return The type signature string for the method, or if not available, the type descriptor string for the * method. */ public String getTypeSignatureOrTypeDescriptorStr() { if (typeSignatureStr != null) { return typeSignatureStr; } else { return typeDescriptorStr; } } /** * Returns the list of exceptions thrown by the method, as a {@link ClassInfoList}. * * @return The list of exceptions thrown by the method, as a {@link ClassInfoList} (the list may be empty). */ public ClassInfoList getThrownExceptions() { if (thrownExceptions == null && thrownExceptionNames != null) { thrownExceptions = new ClassInfoList(thrownExceptionNames.length); for (final String thrownExceptionName : thrownExceptionNames) { final ClassInfo classInfo = scanResult.getClassInfo(thrownExceptionName); if (classInfo != null) { thrownExceptions.add(classInfo); classInfo.setScanResult(scanResult); } } } return thrownExceptions == null ? ClassInfoList.EMPTY_LIST : thrownExceptions; } /** * Returns the exceptions thrown by the method, as an array. * * @return The exceptions thrown by the method, as an array (the array may be empty). */ public String[] getThrownExceptionNames() { return thrownExceptionNames == null ? new String[0] : thrownExceptionNames; } // ------------------------------------------------------------------------------------------------------------- /** * Returns true if this method is a constructor. Constructors have the method name {@code * "<init>"}. This returns false for private static class initializer blocks, which are named * {@code "<clinit>"}. * * @return True if this method is a constructor. */ public boolean isConstructor() { return "<init>".equals(name); } /** * Returns true if this method is public. * * @return True if this method is public. */ public boolean isPublic() { return Modifier.isPublic(modifiers); } /** * Returns true if this method is private. * * @return True if this method is private. */ public boolean isPrivate() { return Modifier.isPrivate(modifiers); } /** * Returns true if this method is protected. * * @return True if this method is protected. */ public boolean isProtected() { return Modifier.isProtected(modifiers); } /** * Returns true if this method is static. * * @return True if this method is static. */ public boolean isStatic() { return Modifier.isStatic(modifiers); } /** * Returns true if this method is final. * * @return True if this method is final. */ public boolean isFinal() { return Modifier.isFinal(modifiers); } /** * Returns true if this method is synchronized. * * @return True if this method is synchronized. */ public boolean isSynchronized() { return Modifier.isSynchronized(modifiers); } /** * Returns true if this method is a bridge method. * * @return True if this is a bridge method. */ public boolean isBridge() { return (modifiers & 0x0040) != 0; } /** * Returns true if this method is synthetic. * * @return True if this is synthetic. */ public boolean isSynthetic() { return (modifiers & 0x1000) != 0; } /** * Returns true if this method is a varargs method. * * @return True if this is a varargs method. */ public boolean isVarArgs() { return (modifiers & 0x0080) != 0; } /** * Returns true if this method is a native method. * * @return True if this method is native. */ public boolean isNative() { return Modifier.isNative(modifiers); } /** * Returns true if this method is abstract. * * @return True if this method is abstract. */ public boolean isAbstract() { return Modifier.isAbstract(modifiers); } /** * Returns true if this method is strict. * * @return True if this method is strict. */ public boolean isStrict() { return Modifier.isStrict(modifiers); } /** * Returns true if this method has a body (i.e. has an implementation in the containing class). * * @return True if this method has a body. */ public boolean hasBody() { return hasBody; } /** * Returns true if this is a default method (i.e. if this is a method in an interface and the method has a * body). * * @return True if this is a default method. */ public boolean isDefault() { final ClassInfo classInfo = getClassInfo(); return classInfo != null && classInfo.isInterface() && hasBody; } // ------------------------------------------------------------------------------------------------------------- /** * Get the available information on method parameters. * * @return The {@link MethodParameterInfo} objects for the method parameters, one per parameter. */ public MethodParameterInfo[] getParameterInfo() { if (parameterInfo == null) { // Get params from the type descriptor, and from the type signature if available List<TypeSignature> paramTypeDescriptors = null; int numParams = 0; try { final MethodTypeSignature typeSig = getTypeDescriptor(); if (typeSig != null) { paramTypeDescriptors = typeSig.getParameterTypeSignatures(); numParams = paramTypeDescriptors.size(); } } catch (final Exception e) { // Ignore } List<TypeSignature> paramTypeSignatures = null; try { final MethodTypeSignature typeSig = getTypeSignature(); if (typeSig != null) { paramTypeSignatures = typeSig.getParameterTypeSignatures(); } } catch (final Exception e) { // Ignore } // Figure out the number of params in the alignment (should be num params in type descriptor) if (paramTypeSignatures != null && paramTypeSignatures.size() > numParams) { // Should not happen throw new ClassGraphException( "typeSignatureParamTypes.size() > typeDescriptorParamTypes.size() for method " + declaringClassName + "." + name); } // Figure out number of other fields that need alignment, and check length for consistency final int otherParamMax = Math.max(parameterNames == null ? 0 : parameterNames.length, Math.max(parameterModifiers == null ? 0 : parameterModifiers.length, parameterAnnotationInfo == null ? 0 : parameterAnnotationInfo.length)); if (otherParamMax > numParams) { // Should not happen throw new ClassGraphException("Type descriptor for method " + declaringClassName + "." + name + " has insufficient parameters"); } // Kotlin is very inconsistent about the arity of each of the parameter metadata types, see: // https://github.com/classgraph/classgraph/issues/175#issuecomment-363031510 // As a workaround, we assume that any synthetic / mandated parameters must come first in the // parameter list, when the arities don't match, and we right-align the metadata fields. // This is probably the safest assumption across JVM languages, even though this convention // is by no means the only possibility. (Unfortunately we can't just rely on the modifier // bits to find synthetic / mandated parameters, because these bits are not always available, // and even when they are, they don't always give the right alignment, at least for Kotlin- // generated code). // Actually the Java spec says specifically: "The signature and descriptor of a given method // or constructor may not correspond exactly, due to compiler-generated artifacts. In particular, // the number of TypeSignatures that encode formal arguments in MethodTypeSignature may be less // than the number of ParameterDescriptors in MethodDescriptor." String[] paramNamesAligned = null; if (parameterNames != null && numParams > 0) { if (parameterNames.length == numParams) { // No alignment necessary paramNamesAligned = parameterNames; } else { // Right-align when not the right length paramNamesAligned = new String[numParams]; for (int i = 0, lenDiff = numParams - parameterNames.length; i < parameterNames.length; i++) { paramNamesAligned[lenDiff + i] = parameterNames[i]; } } } int[] paramModifiersAligned = null; if (parameterModifiers != null && numParams > 0) { if (parameterModifiers.length == numParams) { // No alignment necessary paramModifiersAligned = parameterModifiers; } else { // Right-align when not the right length paramModifiersAligned = new int[numParams]; for (int i = 0, lenDiff = numParams - parameterModifiers.length; i < parameterModifiers.length; i++) { paramModifiersAligned[lenDiff + i] = parameterModifiers[i]; } } } AnnotationInfo[][] paramAnnotationInfoAligned = null; if (parameterAnnotationInfo != null && numParams > 0) { if (parameterAnnotationInfo.length == numParams) { // No alignment necessary paramAnnotationInfoAligned = parameterAnnotationInfo; } else { // Right-align when not the right length paramAnnotationInfoAligned = new AnnotationInfo[numParams][]; for (int i = 0, lenDiff = numParams - parameterAnnotationInfo.length; i < parameterAnnotationInfo.length; i++) { paramAnnotationInfoAligned[lenDiff + i] = parameterAnnotationInfo[i]; } } } List<TypeSignature> paramTypeSignaturesAligned = null; if (paramTypeSignatures != null && numParams > 0) { if (paramTypeSignatures.size() == numParams) { // No alignment necessary paramTypeSignaturesAligned = paramTypeSignatures; } else { // Right-align when not the right length paramTypeSignaturesAligned = new ArrayList<>(numParams); for (int i = 0, n = numParams - paramTypeSignatures.size(); i < n; i++) { // Left-pad with nulls paramTypeSignaturesAligned.add(null); } paramTypeSignaturesAligned.addAll(paramTypeSignatures); } } // Generate MethodParameterInfo entries parameterInfo = new MethodParameterInfo[numParams]; for (int i = 0; i < numParams; i++) { parameterInfo[i] = new MethodParameterInfo(this, paramAnnotationInfoAligned == null ? null : paramAnnotationInfoAligned[i], paramModifiersAligned == null ? 0 : paramModifiersAligned[i], paramTypeDescriptors == null ? null : paramTypeDescriptors.get(i), paramTypeSignaturesAligned == null ? null : paramTypeSignaturesAligned.get(i), paramNamesAligned == null ? null : paramNamesAligned[i]); parameterInfo[i].setScanResult(scanResult); } } return parameterInfo; } // ------------------------------------------------------------------------------------------------------------- /** * Get a list of annotations on this method, along with any annotation parameter values. * * @return a list of annotations on this method, along with any annotation parameter values, wrapped in * {@link AnnotationInfo} objects, or the empty list if none. */ public AnnotationInfoList getAnnotationInfo() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } return annotationInfo == null ? AnnotationInfoList.EMPTY_LIST : AnnotationInfoList.getIndirectAnnotations(annotationInfo, /* annotatedClass = */ null); } /** * Get a the non-{@link Repeatable} annotation on this method, or null if the method does not have the * annotation. (Use {@link #getAnnotationInfoRepeatable(Class)} for {@link Repeatable} annotations.) * * @param annotation * The annotation. * @return An {@link AnnotationInfo} object representing the annotation on this method, or null if the method * does not have the annotation. */ public AnnotationInfo getAnnotationInfo(final Class<? extends Annotation> annotation) { Assert.isAnnotation(annotation); return getAnnotationInfo(annotation.getName()); } /** * Get a the named non-{@link Repeatable} annotation on this method, or null if the method does not have the * named annotation. (Use {@link #getAnnotationInfoRepeatable(String)} for {@link Repeatable} annotations.) * * @param annotationName * The annotation name. * @return An {@link AnnotationInfo} object representing the named annotation on this method, or null if the * method does not have the named annotation. */ public AnnotationInfo getAnnotationInfo(final String annotationName) { return getAnnotationInfo().get(annotationName); } /** * Get a the {@link Repeatable} annotation on this method, or the empty list if the method does not have the * annotation. * * @param annotation * The annotation. * @return An {@link AnnotationInfoList} containing all instances of the annotation on this method, or the empty * list if the method does not have the annotation. */ public AnnotationInfoList getAnnotationInfoRepeatable(final Class<? extends Annotation> annotation) { Assert.isAnnotation(annotation); return getAnnotationInfoRepeatable(annotation.getName()); } /** * Get a the named {@link Repeatable} annotation on this method, or the empty list if the method does not have * the named annotation. * * @param annotationName * The annotation name. * @return An {@link AnnotationInfoList} containing all instances of the named annotation on this method, or the * empty list if the method does not have the named annotation. */ public AnnotationInfoList getAnnotationInfoRepeatable(final String annotationName) { return getAnnotationInfo().getRepeatable(annotationName); } /** * Check if this method has the annotation. * * @param annotation * The annotation. * @return true if this method has the annotation. */ public boolean hasAnnotation(final Class<? extends Annotation> annotation) { Assert.isAnnotation(annotation); return hasAnnotation(annotation.getName()); } /** * Check if this method has the named annotation. * * @param annotationName * The name of an annotation. * @return true if this method has the named annotation. */ public boolean hasAnnotation(final String annotationName) { return getAnnotationInfo().containsName(annotationName); } /** * Check if this method has a parameter with the annotation. * * @param annotation * The method parameter annotation. * @return true if this method has a parameter with the annotation. */ public boolean hasParameterAnnotation(final Class<? extends Annotation> annotation) { Assert.isAnnotation(annotation); return hasParameterAnnotation(annotation.getName()); } /** * Check if this method has a parameter with the named annotation. * * @param annotationName * The name of a method parameter annotation. * @return true if this method has a parameter with the named annotation. */ public boolean hasParameterAnnotation(final String annotationName) { for (final MethodParameterInfo methodParameterInfo : getParameterInfo()) { if (methodParameterInfo.hasAnnotation(annotationName)) { return true; } } return false; } // ------------------------------------------------------------------------------------------------------------- /** * Load and return the classes of each of the method parameters. * * @return An array of the {@link Class} references for each method parameter. */ private Class<?>[] loadParameterClasses() { final MethodParameterInfo[] allParameterInfo = getParameterInfo(); final List<Class<?>> parameterClasses = new ArrayList<>(allParameterInfo.length); for (final MethodParameterInfo mpi : allParameterInfo) { final TypeSignature parameterType = mpi.getTypeSignatureOrTypeDescriptor(); parameterClasses.add(parameterType.loadClass()); } return parameterClasses.toArray(new Class<?>[0]); } /** * Load the class this method is associated with, and get the {@link Method} reference for this method. Only * call this if {@link #isConstructor()} returns false, otherwise an {@link IllegalArgumentException} will be * thrown. Instead call {@link #loadClassAndGetConstructor()} for constructors. * * @return The {@link Method} reference for this method. * @throws IllegalArgumentException * if the method does not exist, or if the method is a constructor. */ public Method loadClassAndGetMethod() throws IllegalArgumentException { if (isConstructor()) { throw new IllegalArgumentException( "Need to call loadClassAndGetConstructor() for constructors, not loadClassAndGetMethod()"); } final Class<?>[] parameterClassesArr = loadParameterClasses(); try { return loadClass().getMethod(getName(), parameterClassesArr); } catch (final NoSuchMethodException e1) { try { return loadClass().getDeclaredMethod(getName(), parameterClassesArr); } catch (final NoSuchMethodException es2) { throw new IllegalArgumentException("Method not found: " + getClassName() + "." + getName()); } } } /** * Load the class this constructor is associated with, and get the {@link Constructor} reference for this * constructor. Only call this if {@link #isConstructor()} returns true, otherwise an * {@link IllegalArgumentException} will be thrown. Instead call {@link #loadClassAndGetMethod()} for non-method * constructors. * * @return The {@link Constructor} reference for this constructor. * @throws IllegalArgumentException * if the constructor does not exist, or if the method is not a constructor. */ public Constructor<?> loadClassAndGetConstructor() throws IllegalArgumentException { if (!isConstructor()) { throw new IllegalArgumentException( "Need to call loadClassAndGetMethod() for non-constructor methods, not " + "loadClassAndGetConstructor()"); } final Class<?>[] parameterClassesArr = loadParameterClasses(); try { return loadClass().getConstructor(parameterClassesArr); } catch (final NoSuchMethodException e1) { try { return loadClass().getDeclaredConstructor(parameterClassesArr); } catch (final NoSuchMethodException es2) { throw new IllegalArgumentException("Constructor not found for class " + getClassName()); } } } // ------------------------------------------------------------------------------------------------------------- /** * Handle {@link Repeatable} annotations. * * @param allRepeatableAnnotationNames * the names of all repeatable annotations */ void handleRepeatableAnnotations(final Set<String> allRepeatableAnnotationNames) { if (annotationInfo != null) { annotationInfo.handleRepeatableAnnotations(allRepeatableAnnotationNames, getClassInfo(), RelType.METHOD_ANNOTATIONS, RelType.CLASSES_WITH_METHOD_ANNOTATION, RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION); } if (parameterAnnotationInfo != null) { for (int i = 0; i < parameterAnnotationInfo.length; i++) { final AnnotationInfo[] pai = parameterAnnotationInfo[i]; if (pai != null && pai.length > 0) { boolean hasRepeatableAnnotation = false; for (final AnnotationInfo ai : pai) { if (allRepeatableAnnotationNames.contains(ai.getName())) { hasRepeatableAnnotation = true; break; } } if (hasRepeatableAnnotation) { final AnnotationInfoList aiList = new AnnotationInfoList(pai.length); aiList.addAll(Arrays.asList(pai)); aiList.handleRepeatableAnnotations(allRepeatableAnnotationNames, getClassInfo(), RelType.METHOD_PARAMETER_ANNOTATIONS, RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION, RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION); parameterAnnotationInfo[i] = aiList.toArray(new AnnotationInfo[0]); } } } } } // ------------------------------------------------------------------------------------------------------------- /** * Get the name of the class that declares this method. * * @return The name of the declaring class. * * @see #getClassInfo() */ @Override public String getClassName() { return declaringClassName; } /* (non-Javadoc) * @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult) */ @Override void setScanResult(final ScanResult scanResult) { super.setScanResult(scanResult); if (this.typeDescriptor != null) { this.typeDescriptor.setScanResult(scanResult); } if (this.typeSignature != null) { this.typeSignature.setScanResult(scanResult); } if (this.annotationInfo != null) { for (final AnnotationInfo ai : this.annotationInfo) { ai.setScanResult(scanResult); } } if (this.parameterAnnotationInfo != null) { for (final AnnotationInfo[] pai : this.parameterAnnotationInfo) { if (pai != null) { for (final AnnotationInfo ai : pai) { ai.setScanResult(scanResult); } } } } if (this.parameterInfo != null) { for (final MethodParameterInfo mpi : parameterInfo) { mpi.setScanResult(scanResult); } } if (this.thrownExceptions != null) { for (final ClassInfo thrownException : thrownExceptions) { thrownException.setScanResult(scanResult); } } } /** * Get {@link ClassInfo} objects for any classes referenced in the type descriptor or type signature. * * @param classNameToClassInfo * the map from class name to {@link ClassInfo}. * @param refdClassInfo * the referenced class info */ @Override protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo, final Set<ClassInfo> refdClassInfo, final LogNode log) { try { final MethodTypeSignature methodSig = getTypeSignature(); if (methodSig != null) { methodSig.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log); } } catch (final IllegalArgumentException e) { if (log != null) { log.log("Illegal type signature for method " + getClassName() + "." + getName() + ": " + getTypeSignatureStr()); } } try { final MethodTypeSignature methodDesc = getTypeDescriptor(); if (methodDesc != null) { methodDesc.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log); } } catch (final IllegalArgumentException e) { if (log != null) { log.log("Illegal type descriptor for method " + getClassName() + "." + getName() + ": " + getTypeDescriptorStr()); } } if (annotationInfo != null) { for (final AnnotationInfo ai : annotationInfo) { ai.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log); } } for (final MethodParameterInfo mpi : getParameterInfo()) { final AnnotationInfo[] aiArr = mpi.annotationInfo; if (aiArr != null) { for (final AnnotationInfo ai : aiArr) { ai.findReferencedClassInfo(classNameToClassInfo, refdClassInfo, log); } } } if (thrownExceptionNames != null) { final ClassInfoList thrownExceptions = getThrownExceptions(); if (thrownExceptions != null) { for (int i = 0; i < thrownExceptions.size(); i++) { classNameToClassInfo.put(thrownExceptionNames[i], thrownExceptions.get(i)); } } } } // ------------------------------------------------------------------------------------------------------------- /** * Test class name, method name and type descriptor for equals(). * * @param obj * the object to compare for equality * @return true if equal */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (!(obj instanceof MethodInfo)) { return false; } final MethodInfo other = (MethodInfo) obj; return declaringClassName.equals(other.declaringClassName) && typeDescriptorStr.equals(other.typeDescriptorStr) && name.equals(other.name); } /** * Use hashcode of class name, method name and type descriptor. * * @return the hashcode */ @Override public int hashCode() { return name.hashCode() + typeDescriptorStr.hashCode() * 11 + declaringClassName.hashCode() * 57; } /** * Sort in order of class name, method name, then type descriptor. * * @param other * the other {@link MethodInfo} to compare. * @return the result of the comparison. */ @Override public int compareTo(final MethodInfo other) { final int diff0 = declaringClassName.compareTo(other.declaringClassName); if (diff0 != 0) { return diff0; } final int diff1 = name.compareTo(other.name); if (diff1 != 0) { return diff1; } return typeDescriptorStr.compareTo(other.typeDescriptorStr); } // ------------------------------------------------------------------------------------------------------------- /** * Get a string representation of the method. Note that constructors are named {@code "<init>"}, and private * static class initializer blocks are named {@code "<clinit>"}. * * @param useSimpleNames * the use simple names * @param buf * the buf */ @Override protected void toString(final boolean useSimpleNames, final StringBuilder buf) { final MethodTypeSignature methodType = getTypeSignatureOrTypeDescriptor(); if (annotationInfo != null) { for (final AnnotationInfo annotation : annotationInfo) { if (buf.length() > 0) { buf.append(' '); } annotation.toString(useSimpleNames, buf); } } if (modifiers != 0) { if (buf.length() > 0) { buf.append(' '); } TypeUtils.modifiersToString(modifiers, ModifierType.METHOD, isDefault(), buf); } final List<TypeParameter> typeParameters = methodType.getTypeParameters(); if (!typeParameters.isEmpty()) { if (buf.length() > 0) { buf.append(' '); } buf.append('<'); for (int i = 0; i < typeParameters.size(); i++) { if (i > 0) { buf.append(", "); } typeParameters.get(i).toString(useSimpleNames, buf); } buf.append('>'); } if (!isConstructor()) { if (buf.length() > 0) { buf.append(' '); } methodType.getResultType().toStringInternal(useSimpleNames, /* annotationsToExclude = */ annotationInfo, buf); } buf.append(' '); if (name != null) { buf.append(useSimpleNames ? ClassInfo.getSimpleName(name) : name); } // If at least one param is named, then use placeholder names for unnamed params, // otherwise don't show names for any params final MethodParameterInfo[] allParamInfo = getParameterInfo(); boolean hasParamNames = false; for (final MethodParameterInfo methodParamInfo : allParamInfo) { if (methodParamInfo.getName() != null) { hasParamNames = true; break; } } // Find varargs param index, if present -- this is, for varargs methods, the last argument that // is not a synthetic or mandated parameter (turns out the Java compiler can tack on parameters // *after* the varargs parameter, for variable capture with anonymous inner classes -- see #260). int varArgsParamIndex = -1; if (isVarArgs()) { for (int i = allParamInfo.length - 1; i >= 0; --i) { final int mods = allParamInfo[i].getModifiers(); if ((mods & /* synthetic */ 0x1000) == 0 && (mods & /* mandated */ 0x8000) == 0) { final TypeSignature paramType = allParamInfo[i].getTypeSignatureOrTypeDescriptor(); if (paramType instanceof ArrayTypeSignature) { varArgsParamIndex = i; break; } } } } buf.append('('); for (int i = 0, numParams = allParamInfo.length; i < numParams; i++) { final MethodParameterInfo paramInfo = allParamInfo[i]; if (i > 0) { buf.append(", "); } if (paramInfo.annotationInfo != null) { for (final AnnotationInfo ai : paramInfo.annotationInfo) { ai.toString(useSimpleNames, buf); buf.append(' '); } } MethodParameterInfo.modifiersToString(paramInfo.getModifiers(), buf); final TypeSignature paramTypeSignature = paramInfo.getTypeSignatureOrTypeDescriptor(); if (i == varArgsParamIndex) { // Show varargs params correctly -- replace last "[]" with "..." if (!(paramTypeSignature instanceof ArrayTypeSignature)) { throw new IllegalArgumentException( "Got non-array type for last parameter of varargs method " + name); } final ArrayTypeSignature arrayType = (ArrayTypeSignature) paramTypeSignature; if (arrayType.getNumDimensions() == 0) { throw new IllegalArgumentException( "Got a zero-dimension array type for last parameter of varargs method " + name); } arrayType.getElementTypeSignature().toString(useSimpleNames, buf); for (int j = 0; j < arrayType.getNumDimensions() - 1; j++) { buf.append("[]"); } buf.append("..."); } else { // Exclude parameter annotations from type annotations at toplevel of type signature, // so that annotation is not listed twice final AnnotationInfoList annotationsToExclude; if (paramInfo.annotationInfo == null || paramInfo.annotationInfo.length == 0) { annotationsToExclude = null; } else { annotationsToExclude = new AnnotationInfoList(paramInfo.annotationInfo.length); annotationsToExclude.addAll(Arrays.asList(paramInfo.annotationInfo)); } paramTypeSignature.toStringInternal(useSimpleNames, annotationsToExclude, buf); } if (hasParamNames) { final String paramName = paramInfo.getName(); if (paramName != null) { buf.append(' '); buf.append(paramName); } } } buf.append(')'); // when throws signature is present, it includes both generic type variables and class names if (!methodType.getThrowsSignatures().isEmpty()) { buf.append(" throws "); for (int i = 0; i < methodType.getThrowsSignatures().size(); i++) { if (i > 0) { buf.append(", "); } methodType.getThrowsSignatures().get(i).toString(useSimpleNames, buf); } } else { if (thrownExceptionNames != null && thrownExceptionNames.length > 0) { buf.append(" throws "); for (int i = 0; i < thrownExceptionNames.length; i++) { if (i > 0) { buf.append(", "); } buf.append(useSimpleNames ? ClassInfo.getSimpleName(thrownExceptionNames[i]) : thrownExceptionNames[i].replace('$', '.')); } } } } } <file_sep>/Zero-Bugs-Commitment.md # The Zero Bugs Commitment This project adheres to the **Zero Bugs Commitment** (`#ZeroBugs`). This is a commitment to practice *responsible software engineering*, *proactive community participation*, and *positive community engagement*, with a goal of keeping the count of known or open bugs at zero, while respecting and cultivating contributions. **As developers of this project, we pledge that:** ## (1) We will prioritize fixing bugs over implementing new features. *(Motivation: It is human nature to be much more interested in building new things than doing the hard work to fix old, broken things.)* 💡 We pledge, wherever reasonable, to prioritize fixing known bugs above implementing new features, with the goal of **keeping the count of known or open bugs at zero**. ## (2) We will take responsibility for code we have written or contributed to. *(Motivation: As attention shifts between projects, it is difficult to return to work on old code. This can lead to bit rot.)* 💡 We pledge to take long-term responsibility for any significant code we create or contribute to, fixing problems and updating code as necessary to prevent bit rot. If we can no longer fulfill this responsibility, we will find someone else who can assume the responsibility for our code. Note that this is about taking *personal responsibility* for our own work, not about who has *official maintainership* for a project or piece of code. ## (3) We will be responsive during the bugfixing process. *(Motivation: It is easy to delay responding to a bug report, a bug comment or a request until the issue becomes forgotten or obsolete. This is the unfortunate end state of a significant proportion of bug reports filed across the open source ecosystem.)* 💡 We pledge to be responsive to bug reports, comments and requests currently open in our project's bug tracker, and to be proactive in resolving problems as quickly as practical. ## (4) We will be respectful and inclusive. *(Motivation: Open source communities have been known to reject halting but earnest efforts of new contributors. Bug trackers are also full of pet complaints and bugs closed as `#WONTFIX`, without a significant attempt to understand core issues, or to find a solution or compromise.)* 💡 We pledge to cultivate contributions and growth in our community by welcoming, encouraging, and helping users who offer contributions; by striving to listen to the needs and requests of community members; and by trying to find a reasonable solution or middle ground when there is a disagreement. --- **THIS DOCUMENT IS IN THE PUBLIC DOMAIN** You are strongly encouraged to share this commitment, to make this commitment yourself for software that you develop or maintain, and to encourage others to do the same. **To sign this pledge**, you can add the following wording to your project homepage, linking to this document, or to your own copy or your own version of this document: | **This project adheres to the [Zero Bugs Commitment](https://github.com/classgraph/classgraph/blob/master/Zero-Bugs-Commitment.md).** | |-----------------------------| You may modify or redistribute this document at will without restriction. However, please leave a record of your changes below. #### Version history: 0.1: Original version (author: <NAME>)
9c75ff9a1ec4b7062196c0ba4ab2535cfd4ac84b
[ "Markdown", "Java" ]
2
Java
michael-simons/classgraph
f63b521a5203cea79498d7f33bc4253861513848
f26f60b94ce2375ce4376b94f09cfac08a829a40
refs/heads/Sysex
<repo_name>203Electronics/USBComposite_stm32f1<file_sep>/HIDReports.cpp #include "USBComposite.h" #define REPORT(name, ...) \ static uint8_t raw_ ## name[] = { __VA_ARGS__ }; \ static const HIDReportDescriptor desc_ ## name = { raw_ ##name, sizeof(raw_ ##name) }; \ const HIDReportDescriptor* hidReport ## name = & desc_ ## name; REPORT(KeyboardMouseJoystick, HID_MOUSE_REPORT_DESCRIPTOR(), HID_KEYBOARD_REPORT_DESCRIPTOR(), HID_JOYSTICK_REPORT_DESCRIPTOR()); REPORT(KeyboardMouse, HID_MOUSE_REPORT_DESCRIPTOR(), HID_KEYBOARD_REPORT_DESCRIPTOR()); REPORT(Keyboard, HID_KEYBOARD_REPORT_DESCRIPTOR()); REPORT(Mouse, HID_MOUSE_REPORT_DESCRIPTOR()); REPORT(AbsMouse, HID_ABS_MOUSE_REPORT_DESCRIPTOR()); REPORT(KeyboardJoystick, HID_KEYBOARD_REPORT_DESCRIPTOR(), HID_JOYSTICK_REPORT_DESCRIPTOR()); REPORT(Joystick, HID_JOYSTICK_REPORT_DESCRIPTOR()); REPORT(BootKeyboard, HID_BOOT_KEYBOARD_REPORT_DESCRIPTOR()); REPORT(Consumer, HID_CONSUMER_REPORT_DESCRIPTOR()); <file_sep>/USBHID.cpp /* Copyright (c) 2011, <NAME> * Copyright (c) 2017-2018, <NAME> ** ** Permission to use, copy, modify, and/or distribute this software for ** any purpose with or without fee is hereby granted, provided that the ** above copyright notice and this permission notice appear in all copies. ** ** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ** SOFTWARE. */ #include "USBComposite.h" #include <string.h> #include <stdint.h> #include <libmaple/nvic.h> #include "usb_hid.h" #include "usb_composite_serial.h" #include "usb_generic.h" #include <libmaple/usb.h> #include <string.h> #include <libmaple/iwdg.h> /* * USB HID interface */ bool USBHID::init(USBHID* me) { usb_hid_setTXEPSize(me->txPacketSize); HIDReporter* r = me->profiles; if (me->baseChunk.data != NULL) { /* user set an explicit report for USBHID */ while (r != NULL) { r->reportID = r->userSuppliedReportID; if (r->reportID != 0) r->reportBuffer[0] = r->reportID; r = r->next; } usb_hid_set_report_descriptor(&(me->baseChunk)); } else { uint8 reportID = HID_AUTO_REPORT_ID_START; while (r != NULL) { if (r->forceUserSuppliedReportID) r->reportID = r->userSuppliedReportID; else r->reportID = reportID++; if (r->reportID != 0) r->reportBuffer[0] = r->reportID; r = r->next; } usb_hid_set_report_descriptor(me->chunkList); } return true; } bool USBHID::registerComponent() { return USBComposite.add(&usbHIDPart, this, (USBPartInitializer)&USBHID::init); } void USBHID::setReportDescriptor(const uint8_t* report_descriptor, uint16_t report_descriptor_length) { baseChunk.dataLength = report_descriptor_length; baseChunk.data = report_descriptor; baseChunk.next = NULL; } void USBHID::clear() { clearBuffers(); baseChunk.data = NULL; baseChunk.dataLength = 0; baseChunk.next = NULL; chunkList = NULL; profiles = NULL; } void USBHID::addReport(HIDReporter* r, bool always) { if (! always && ! autoRegister) return; r->next = NULL; if (profiles == NULL) { profiles = r; } else { HIDReporter* tail = profiles; while (tail != r && tail->next != NULL) { tail = tail->next; } if (tail == r) return; tail->next = r; } struct usb_chunk* chunkTail = chunkList; if (chunkTail == NULL) { chunkList = &(r->reportChunks[0]); chunkTail = chunkList; } else { while (chunkTail->next != NULL) chunkTail = chunkTail->next; chunkTail->next = &(r->reportChunks[0]); chunkTail = chunkTail->next; } chunkTail->next = &(r->reportChunks[1]); chunkTail = chunkTail->next; chunkTail->next = &(r->reportChunks[2]); chunkTail = chunkTail->next; chunkTail->next = NULL; } void USBHID::setReportDescriptor(const HIDReportDescriptor* report) { if (report == NULL) setReportDescriptor(NULL, 0); else setReportDescriptor(report->descriptor, report->length); } void USBHID::begin(const uint8_t* report_descriptor, uint16_t report_descriptor_length) { if (enabledHID) return; setReportDescriptor(report_descriptor, report_descriptor_length); USBComposite.clear(); registerComponent(); USBComposite.begin(); enabledHID = true; } void USBHID::begin(const HIDReportDescriptor* report) { if (report == NULL) begin(NULL, 0); else begin(report->descriptor, report->length); } void USBHID::setBuffers(uint8_t type, volatile HIDBuffer_t* fb, int count) { usb_hid_set_buffers(type, fb, count); } bool USBHID::addBuffer(uint8_t type, volatile HIDBuffer_t* buffer) { return 0 != usb_hid_add_buffer(type, buffer); } void USBHID::clearBuffers(uint8_t type) { usb_hid_clear_buffers(type); } void USBHID::clearBuffers() { clearBuffers(HID_REPORT_TYPE_OUTPUT); clearBuffers(HID_REPORT_TYPE_FEATURE); } void USBHID::end(void){ if(enabledHID) { USBComposite.end(); enabledHID = false; } } void USBHID::begin(USBCompositeSerial serial, const uint8_t* report_descriptor, uint16_t report_descriptor_length) { USBComposite.clear(); setReportDescriptor(report_descriptor, report_descriptor_length); registerComponent(); serial.registerComponent(); USBComposite.begin(); } void USBHID::begin(USBCompositeSerial serial, const HIDReportDescriptor* report) { begin(serial, report->descriptor, report->length); } void HIDReporter::sendReport() { // while (usb_is_transmitting() != 0) { // } unsigned toSend = bufferSize; uint8* b = reportBuffer; while (toSend) { unsigned delta = usb_hid_tx(b, toSend); toSend -= delta; b += delta; } // while (usb_is_transmitting() != 0) { // } /* flush out to avoid having the pc wait for more data */ usb_hid_tx(NULL, 0); } void HIDReporter::registerProfile(bool always) { for (uint32 i=0; i<3; i++) { reportChunks[i].data = NULL; reportChunks[i].dataLength = 0; } if (reportDescriptor.descriptor != NULL) { int32_t reportIDOffset = -1; if (! forceUserSuppliedReportID) { uint32_t i = 0; /* * parse bits of beginning of report looking for a single-byte report ID (0x85 ID) */ while (i < reportDescriptor.length && reportIDOffset < 0) { if (reportDescriptor.descriptor[i]==0x85) { if (i+1 < reportDescriptor.length) reportIDOffset = i+1; } // the lowest 2 bit determine the data length of the tag if ((reportDescriptor.descriptor[i] & 3) == 3) i += 5; else i += 1 + (reportDescriptor.descriptor[i] & 3); } if (i >= reportDescriptor.length) { forceUserSuppliedReportID = true; } } if (forceUserSuppliedReportID) { reportChunks[0].data = reportDescriptor.descriptor; reportChunks[0].dataLength = reportDescriptor.length; } else { reportChunks[0].data = reportDescriptor.descriptor; reportChunks[0].dataLength = reportIDOffset; reportChunks[1].data = &(reportID); reportChunks[1].dataLength = 1; reportChunks[2].data = reportDescriptor.descriptor+reportIDOffset+1; reportChunks[2].dataLength = reportDescriptor.length - (reportIDOffset+1); } } HID.addReport(this, always); } HIDReporter::HIDReporter(USBHID& _HID, const HIDReportDescriptor* r, uint8_t* _buffer, unsigned _size, uint8_t _reportID, bool forceReportID) : HID(_HID) { if (r != NULL) { memcpy(&reportDescriptor, r, sizeof(reportDescriptor)); } else { reportDescriptor.descriptor = NULL; reportDescriptor.length = 0; } if (_reportID == 0) { reportBuffer = _buffer+1; bufferSize = _size-1; } else { reportBuffer = _buffer; bufferSize = _size; } memset(reportBuffer, 0, bufferSize); userSuppliedReportID = _reportID; if (_size > 0 && _reportID != 0 && ! forceReportID) { reportBuffer[0] = _reportID; forceUserSuppliedReportID = false; } else { forceUserSuppliedReportID = true; } registerProfile(false); } HIDReporter::HIDReporter(USBHID& _HID, const HIDReportDescriptor* r, uint8_t* _buffer, unsigned _size) : HID(_HID) { if (r != NULL) { memcpy(&reportDescriptor, r, sizeof(reportDescriptor)); } else { reportDescriptor.descriptor = NULL; reportDescriptor.length = 0; } reportBuffer = _buffer; bufferSize = _size; memset(_buffer, 0, _size); userSuppliedReportID = 0; forceUserSuppliedReportID = true; registerProfile(false); } void HIDReporter::setFeature(uint8_t* in) { return usb_hid_set_feature(reportID, in); } uint16_t HIDReporter::getData(uint8_t type, uint8_t* out, uint8_t poll) { return usb_hid_get_data(type, reportID, out, poll); } uint16_t HIDReporter::getFeature(uint8_t* out, uint8_t poll) { return usb_hid_get_data(HID_REPORT_TYPE_FEATURE, reportID, out, poll); } uint16_t HIDReporter::getOutput(uint8_t* out, uint8_t poll) { return usb_hid_get_data(HID_REPORT_TYPE_OUTPUT, reportID, out, poll); } <file_sep>/USBMIDI.cpp /****************************************************************************** * This started out as a munging of Tymm Twillman's arduino Midi Library into the Libusb class, * though by now very little of the original code is left, except for the class API and * comments. <NAME> kindly gave <NAME> permission to relicense his code under the MIT * license, which fixed a nasty licensing mess. * * The MIT License * * Copyright (c) 2010 <NAME>. * Copyright (c) 2013 <NAME>. * Copyright (c) 2013 <NAME>, Suspect Devices. * (c) 2003-2008 <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * *****************************************************************************/ /** * @brief USB MIDI device with a class compatible with maplemidi */ #include "USBComposite.h" #include <string.h> #include <stdint.h> #undef true #undef false #include <wirish.h> #include "usb_midi_device.h" #include <libmaple/usb.h> #include "usb_generic.h" /* * USBMIDI interface */ #define USB_TIMEOUT 50 void USBMIDI::setChannel(unsigned int channel) { channelIn_ = channel; } bool USBMIDI::init(USBMIDI* me) { usb_midi_setTXEPSize(me->txPacketSize); usb_midi_setRXEPSize(me->rxPacketSize); return true; } bool USBMIDI::registerComponent() { return USBComposite.add(&usbMIDIPart, this, (USBPartInitializer)&USBMIDI::init); } void USBMIDI::begin(unsigned channel) { setChannel(channel); if (enabled) return; USBComposite.clear(); registerComponent(); USBComposite.begin(); enabled = true; } void USBMIDI::end(void) { if (enabled) { USBComposite.end(); enabled = false; } } void USBMIDI::writePacket(uint32 p) { this->writePackets(&p, 1); } void USBMIDI::writePackets(const void *buf, uint32 len) { if (!this->isConnected() || !buf) { return; } uint32 txed = 0; uint32 old_txed = 0; uint32 start = millis(); uint32 sent = 0; while (txed < len && (millis() - start < USB_TIMEOUT)) { sent = usb_midi_tx((const uint32*)buf + txed, len - txed); txed += sent; if (old_txed != txed) { start = millis(); } old_txed = txed; } if (sent == usb_midi_txEPSize) { while (usb_midi_is_transmitting() != 0) { } /* flush out to avoid having the pc wait for more data */ usb_midi_tx(NULL, 0); } } uint32 USBMIDI::available(void) { return usb_midi_data_available(); } uint32 USBMIDI::readPackets(void *buf, uint32 len) { if (!buf) { return 0; } uint32 rxed = 0; while (rxed < len) { rxed += usb_midi_rx((uint32*)buf + rxed, len - rxed); } return rxed; } /* Blocks forever until 1 byte is received */ uint32 USBMIDI::readPacket(void) { uint32 p; this->readPackets(&p, 1); return p; } uint8 USBMIDI::pending(void) { return usb_midi_get_pending(); } uint8 USBMIDI::isConnected(void) { return usb_is_connected(USBLIB) && usb_is_configured(USBLIB); } // These are midi status message types are defined in MidiSpec.h union EVENT_t { uint32 i; uint8 b[4]; MIDI_EVENT_PACKET_t p; }; // Handle decoding incoming MIDI traffic a word at a time -- remembers // what it needs to from one call to the next. // // This is a private function & not meant to be called from outside this class. // It's used whenever data is available from the USB port. // void USBMIDI::dispatchPacket(uint32 p) { union EVENT_t e; e.i=p; switch (e.p.cin) { case CIN_SYSEX ... CIN_SYSEX_ENDS_IN_3: appendSysex(e.p.cin,e.p.midi0,e.p.midi1,e.p.midi2); break; case CIN_3BYTE_SYS_COMMON: if (e.p.midi0 == MIDIv1_SONG_POSITION_PTR) { handleSongPosition(((uint16)e.p.midi2)<<7|((uint16)e.p.midi1)); } break; case CIN_2BYTE_SYS_COMMON: switch (e.p.midi0) { case MIDIv1_SONG_SELECT: handleSongSelect(e.p.midi1); break; case MIDIv1_MTC_QUARTER_FRAME: // reference library doesnt handle quarter frame. break; } break; case CIN_NOTE_OFF: handleNoteOff(MIDIv1_VOICE_CHANNEL(e.p.midi0), e.p.midi1, e.p.midi2); break; case CIN_NOTE_ON: handleNoteOn(MIDIv1_VOICE_CHANNEL(e.p.midi0), e.p.midi1, e.p.midi2); break; case CIN_AFTER_TOUCH: handleVelocityChange(MIDIv1_VOICE_CHANNEL(e.p.midi0), e.p.midi1, e.p.midi2); break; case CIN_CONTROL_CHANGE: handleControlChange(MIDIv1_VOICE_CHANNEL(e.p.midi0), e.p.midi1, e.p.midi2); break; case CIN_PROGRAM_CHANGE: handleProgramChange(MIDIv1_VOICE_CHANNEL(e.p.midi0), e.p.midi1); break; case CIN_CHANNEL_PRESSURE: handleAfterTouch(MIDIv1_VOICE_CHANNEL(e.p.midi0), e.p.midi1); break; case CIN_PITCH_WHEEL: handlePitchChange(((uint16)e.p.midi2)<<7|((uint16)e.p.midi1)); break; case CIN_1BYTE: switch (e.p.midi0) { case MIDIv1_CLOCK: handleSync(); break; case MIDIv1_TICK: break; case MIDIv1_START: handleStart(); break; case MIDIv1_CONTINUE: handleContinue(); break; case MIDIv1_STOP: handleStop(); break; case MIDIv1_ACTIVE_SENSE: handleActiveSense(); break; case MIDIv1_RESET: handleReset(); break; case MIDIv1_TUNE_REQUEST: handleTuneRequest(); break; default: break; } break; } } // Try to read data from USB port & pass anything read to processing function void USBMIDI::poll(void) { while(available()) { dispatchPacket(readPacket()); } } static union EVENT_t outPacket; // since we only use one at a time no point in reallocating it // Send Midi NOTE OFF message to a given channel, with note 0-127 and velocity 0-127 void USBMIDI::sendNoteOff(unsigned int channel, unsigned int note, unsigned int velocity) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_NOTE_OFF; outPacket.p.midi0=MIDIv1_NOTE_OFF|(channel & 0x0f); outPacket.p.midi1=note; outPacket.p.midi2=velocity; writePacket(outPacket.i); } // Send Midi NOTE ON message to a given channel, with note 0-127 and velocity 0-127 void USBMIDI::sendNoteOn(unsigned int channel, unsigned int note, unsigned int velocity) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_NOTE_ON; outPacket.p.midi0=MIDIv1_NOTE_ON|(channel & 0x0f); outPacket.p.midi1=note; outPacket.p.midi2=velocity; writePacket(outPacket.i); } // Send a Midi VELOCITY CHANGE message to a given channel, with given note 0-127, // and new velocity 0-127 // Note velocity change == polyphonic aftertouch. // Note aftertouch == channel pressure. void USBMIDI::sendVelocityChange(unsigned int channel, unsigned int note, unsigned int velocity) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_AFTER_TOUCH; outPacket.p.midi0=MIDIv1_AFTER_TOUCH |(channel & 0x0f); outPacket.p.midi1=note; outPacket.p.midi2=velocity; writePacket(outPacket.i); } // Send a Midi CC message to a given channel, as a given controller 0-127, with given // value 0-127 void USBMIDI::sendControlChange(unsigned int channel, unsigned int controller, unsigned int value) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_CONTROL_CHANGE; outPacket.p.midi0=MIDIv1_CONTROL_CHANGE |(channel & 0x0f); outPacket.p.midi1=controller; outPacket.p.midi2=value; writePacket(outPacket.i); } // Send a Midi PROGRAM CHANGE message to given channel, with program ID 0-127 void USBMIDI::sendProgramChange(unsigned int channel, unsigned int program) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_PROGRAM_CHANGE; outPacket.p.midi0=MIDIv1_PROGRAM_CHANGE |(channel & 0x0f); outPacket.p.midi1=program; writePacket(outPacket.i); } // Send a Midi AFTER TOUCH message to given channel, with velocity 0-127 void USBMIDI::sendAfterTouch(unsigned int channel, unsigned int velocity) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_CHANNEL_PRESSURE; outPacket.p.midi0=MIDIv1_CHANNEL_PRESSURE |(channel & 0x0f); outPacket.p.midi1=velocity; writePacket(outPacket.i); } // Send a Midi PITCH CHANGE message, with a 14-bit pitch (always for all channels) void USBMIDI::sendPitchChange(unsigned int pitch) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_PITCH_WHEEL; outPacket.p.midi0=MIDIv1_PITCH_WHEEL; outPacket.p.midi1= (uint8) pitch & 0x07F; outPacket.p.midi2= (uint8) (pitch>>7) & 0x7f; writePacket(outPacket.i); } // Send a Midi SONG POSITION message, with a 14-bit position (always for all channels) void USBMIDI::sendSongPosition(unsigned int position) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_3BYTE_SYS_COMMON; outPacket.p.midi0=MIDIv1_SONG_POSITION_PTR; outPacket.p.midi1= (uint8) position & 0x07F; outPacket.p.midi2= (uint8) (position>>7) & 0x7f; writePacket(outPacket.i); } // Send a Midi SONG SELECT message, with a song ID of 0-127 (always for all channels) void USBMIDI::sendSongSelect(unsigned int song) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_2BYTE_SYS_COMMON; outPacket.p.midi0=MIDIv1_SONG_SELECT; outPacket.p.midi1= (uint8) song & 0x07F; writePacket(outPacket.i); } // Send a Midi TUNE REQUEST message (TUNE REQUEST is always for all channels) void USBMIDI::sendTuneRequest(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_TUNE_REQUEST; writePacket(outPacket.i); } // Send a Midi SYNC message (SYNC is always for all channels) void USBMIDI::sendSync(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_CLOCK; writePacket(outPacket.i); } // Send a Midi START message (START is always for all channels) void USBMIDI::sendStart(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_START ; writePacket(outPacket.i); } // Send a Midi CONTINUE message (CONTINUE is always for all channels) void USBMIDI::sendContinue(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_CONTINUE ; writePacket(outPacket.i); } // Send a Midi STOP message (STOP is always for all channels) void USBMIDI::sendStop(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_STOP ; writePacket(outPacket.i); } // Send a Midi ACTIVE SENSE message (ACTIVE SENSE is always for all channels) void USBMIDI::sendActiveSense(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_ACTIVE_SENSE ; writePacket(outPacket.i); } // Send a Midi RESET message (RESET is always for all channels) void USBMIDI::sendReset(void) { outPacket.p.cable=DEFAULT_MIDI_CABLE; outPacket.p.cin=CIN_1BYTE; outPacket.p.midi0=MIDIv1_RESET ; writePacket(outPacket.i); } const uint32 midiNoteFrequency_10ths[128] = { 82, 87, 92, 97, 103, 109, 116, 122, 130, 138, 146, 154, 164, 173, 184, 194, 206, 218, 231, 245, 260, 275, 291, 309, 327, 346, 367, 389, 412, 437, 462, 490, 519, 550, 583, 617, 654, 693, 734, 778, 824, 873, 925, 980, 1038, 1100, 1165, 1235, 1308, 1386, 1468, 1556, 1648, 1746, 1850, 1960, 2077, 2200, 2331, 2469, 2616, 2772, 2937, 3111, 3296, 3492, 3700, 3920, 4153, 4400, 4662, 4939, 5233, 5544, 5873, 6223, 6593, 6985, 7400, 7840, 8306, 8800, 9323, 9878, 10465, 11087, 11747, 12445, 13185, 13969, 14800, 15680, 16612, 17600, 18647, 19755, 20930, 22175, 23493, 24890, 26370, 27938, 29600, 31360, 33224, 35200, 37293, 39511, 41860, 44349, 46986, 49780, 52740, 55877, 59199, 62719, 66449, 70400, 74586, 79021, 83720, 88698, 93973, 99561, 105481, 111753, 118398, 125439 }; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" // Placeholders. You should subclass the Midi base class and define these to have your // version called. void USBMIDI::handleNoteOff(unsigned int channel, unsigned int note, unsigned int velocity) {} void USBMIDI::handleNoteOn(unsigned int channel, unsigned int note, unsigned int velocity) {} void USBMIDI::handleVelocityChange(unsigned int channel, unsigned int note, unsigned int velocity) {} void USBMIDI::handleControlChange(unsigned int channel, unsigned int controller, unsigned int value) {} void USBMIDI::handleProgramChange(unsigned int channel, unsigned int program) {} void USBMIDI::handleAfterTouch(unsigned int channel, unsigned int velocity) {} void USBMIDI::handlePitchChange(unsigned int pitch) {} void USBMIDI::handleSongPosition(unsigned int position) {} void USBMIDI::handleSongSelect(unsigned int song) {} void USBMIDI::handleTuneRequest(void) {} void USBMIDI::handleSync(void) {} void USBMIDI::handleStart(void) {} void USBMIDI::handleContinue(void) {} void USBMIDI::handleStop(void) {} void USBMIDI::handleActiveSense(void) {} void USBMIDI::handleReset(void) {} void USBMIDI::appendSysex(uint8_t cin, uint8_t midi0, uint8_t midi1, uint8_t midi2) { if (cin == CIN_SYSEX && midi0 == MIDIv1_SYSEX_START) // new sysex string { sysexstring[0] = midi1; sysexstring[1] = midi2; sysexpos = 2; } else if (cin == CIN_SYSEX && midi1 != MIDIv1_SYSEX_START) // parsing sysex { sysexstring[sysexpos] = midi0; sysexstring[sysexpos + 1] = midi1; sysexstring[sysexpos + 2] = midi2; sysexpos += 3; } else // sysex ends { uint32_t sysexlen; if(midi0 == MIDIv1_SYSEX_START) //Edge case - only one variable was passed in Sysex { sysexstring[0] = midi1; sysexlen = 1; } else { switch(cin) { case CIN_SYSEX_ENDS_IN_1: sysexlen = sysexpos; break; case CIN_SYSEX_ENDS_IN_2: sysexlen = sysexpos + 1; break; case CIN_SYSEX_ENDS_IN_3: sysexlen = sysexpos + 2; break; } sysexstring[sysexpos] = midi0; sysexstring[sysexpos + 1] = midi1; sysexstring[sysexpos + 2] = midi2; } sysexpos = 0; handleSysex(sysexstring, sysexlen); } } void USBMIDI::handleSysex(uint8_t *sysexBuffer, uint32 len) {} void USBMIDI::sendSysex(uint8_t *sysexBuffer, uint32 len) //Header&Ending excluded { outPacket.p.cable=DEFAULT_MIDI_CABLE; if(len == 1) { outPacket.p.cin=CIN_SYSEX_ENDS_IN_3; outPacket.p.midi0= MIDIv1_SYSEX_START; outPacket.p.midi1= sysexBuffer[0]; outPacket.p.midi2= MIDIv1_SYSEX_END; writePacket(outPacket.i); } else { outPacket.p.cin=CIN_SYSEX; outPacket.p.midi0= MIDIv1_SYSEX_START; outPacket.p.midi1= sysexBuffer[0]; outPacket.p.midi2= sysexBuffer[1]; writePacket(outPacket.i); if(len > 2) //Edge case { for(uint16_t i = 2; i < len - 2; i +=3) { outPacket.p.midi0= sysexBuffer[i]; outPacket.p.midi1= sysexBuffer[i+1]; outPacket.p.midi2= sysexBuffer[i+2]; writePacket(outPacket.i); } } switch((len - 2) % 3) { case 2: outPacket.p.cin=CIN_SYSEX_ENDS_IN_3; outPacket.p.midi0= sysexBuffer[len-2]; outPacket.p.midi1= sysexBuffer[len-1]; outPacket.p.midi2= MIDIv1_SYSEX_END; writePacket(outPacket.i); break; case 1: outPacket.p.cin=CIN_SYSEX_ENDS_IN_2; outPacket.p.midi0= sysexBuffer[len-1]; outPacket.p.midi1= MIDIv1_SYSEX_END; outPacket.p.midi2= NULL; writePacket(outPacket.i); break; case 0: outPacket.p.cin=CIN_SYSEX_ENDS_IN_1; outPacket.p.midi0= MIDIv1_SYSEX_END; outPacket.p.midi1= NULL; outPacket.p.midi2= NULL; writePacket(outPacket.i); break; } } } #pragma GCC diagnostic pop <file_sep>/examples/sysex/sysex.ino #include <USBComposite.h> //Header(0xF0)and ending(0xF7) are excluded. class myMidi : public USBMIDI { virtual void handleNoteOff(unsigned int channel, unsigned int note, unsigned int velocity) { CompositeSerial.print("Note off: ch:"); CompositeSerial.print(channel); CompositeSerial.print(" note:"); CompositeSerial.print(note); CompositeSerial.print(" velocity:"); CompositeSerial.println(velocity); } virtual void handleNoteOn(unsigned int channel, unsigned int note, unsigned int velocity) { CompositeSerial.print("Note on: ch:"); CompositeSerial.print(channel); CompositeSerial.print(" note:"); CompositeSerial.print(note); CompositeSerial.print(" velocity:"); CompositeSerial.println(velocity); } virtual void handleSysex(uint8_t *sysexBuffer, uint32 len) { CompositeSerial.print("Sysex - len:"); CompositeSerial.print(len); CompositeSerial.print(" "); for(int i = 0; i < len; i++) { CompositeSerial.print(sysexBuffer[i]); CompositeSerial.print(" "); } CompositeSerial.println(); USBMIDI::sendSysex(sysexBuffer, len); CompositeSerial.println("Sysex returned"); } }; myMidi midi; USBCompositeSerial CompositeSerial; void setup() { USBComposite.setProductId(0x0030); midi.registerComponent(); CompositeSerial.registerComponent(); USBComposite.begin(); } void loop() { midi.poll(); } <file_sep>/USBMIDI.h /****************************************************************************** * The MIT License * * Copyright (c) 2010 <NAME>. * Copyright (c) 2013 <NAME>. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @brief Wirish USB MIDI port (MidiUSB). */ #ifndef _USBMIDI_H_ #define _USBMIDI_H_ #define MAX_SYSEX_SIZE 1024 //#include <Print.h> #include <boards.h> #include <USBComposite.h> #include "usb_generic.h" /* * This is the Midi class. If you are just sending Midi data, you only need to make an * instance of the class, passing it your USB port -- in most cases it looks like * * USBMidi midi; * * then you don't need to do anything else; you can start using it to send Midi messages, * e.g. * * midi.sendNoteOn(1, note, velocity); * * If you are using it to receive Midi data, it's a little more complex & you will need * to subclass the Midi class. * * For people not used to C++ this may look confusing, but it's actually pretty easy. * Note that you only need to write the functions for event types you want to handle. * They should match the names & prototypes of the functions in the class; look at * the functions in the Midi class below that have the keyword "virtual" to see which * ones you can use. * * Here's an example of one that takes NOTE ON, NOTE OFF, and CONTROL CHANGE: * * class MyMidi : public USBMidi { * public: * * // Need this to compile; it just hands things off to the Midi class. * MyMidi() : USBMidi(s) {} * * void handleNoteOn(unsigned int channel, unsigned int note, unsigned int velocity) * { * if (note == 40) {digitalWrite(13, HIGH); } * } * * void handleNoteOff(unsigned int channel, unsigned int note, unsigned int velocity) * { * if (note == 40) { digitalWrite(13, LOW); } * } * * void handleControlChange(unsigned int channel, unsigned int controller, * unsigned int value) * { * analogWrite(6, value * 2); * } * * Then you need to make an instance of this class: * * MyMidi midi(); * * If receiving Midi data, you also need to call the poll function every time through * loop(); e.g. * * void loop() { * midi.poll(); * } * * This causes the Midi class to read data from the USB port and process it. */ class USBMIDI { private: bool enabled = false; /* Private Receive Parameters */ // The channel this Midi instance receives data for (0 means all channels) int channelIn_; /* Internal functions */ // Called whenever data is read from the USB port void dispatchPacket(uint32 packet); uint32 txPacketSize = 64; uint32 rxPacketSize = 64; public: static bool init(USBMIDI* me); // This registers this USB composite device component with the USBComposite class instance. bool registerComponent(); void setChannel(unsigned channel=0); unsigned getChannel() { return channelIn_; } void setRXPacketSize(uint32 size=64) { rxPacketSize = size; } void setTXPacketSize(uint32 size=64) { txPacketSize = size; } // Call to start the USB port, at given baud. For many applications // the default parameters are just fine (which will cause messages for all // MIDI channels to be delivered) void begin(unsigned int channel = 0); //void begin(); void end(); uint32 available(void); uint32 readPackets(void *buf, uint32 len); uint32 readPacket(void); void writePacket(uint32); // void write(const char *str); void writePackets(const void*, uint32); uint8 isConnected(); uint8 pending(); // poll() should be called every time through loop() IF dealing with incoming MIDI // (if you're only SENDING MIDI events from the Arduino, you don't need to call // poll); it causes data to be read from the USB port and processed. void poll(); // Call these to send MIDI messages of the given types void sendNoteOff(unsigned int channel, unsigned int note, unsigned int velocity = 0); void sendNoteOn(unsigned int channel, unsigned int note, unsigned int velocity = 127); void sendVelocityChange(unsigned int channel, unsigned int note, unsigned int velocity); void sendControlChange(unsigned int channel, unsigned int controller, unsigned int value); void sendProgramChange(unsigned int channel, unsigned int program); void sendAfterTouch(unsigned int channel, unsigned int velocity); void sendPitchChange(unsigned int pitch); void sendSongPosition(unsigned int position); void sendSongSelect(unsigned int song); void sendTuneRequest(void); void sendSync(void); void sendStart(void); void sendContinue(void); void sendStop(void); void sendActiveSense(void); void sendReset(void); // Overload these in a subclass to get MIDI messages when they come in virtual void handleNoteOff(unsigned int channel, unsigned int note, unsigned int velocity); virtual void handleNoteOn(unsigned int channel, unsigned int note, unsigned int velocity); virtual void handleVelocityChange(unsigned int channel, unsigned int note, unsigned int velocity); virtual void handleControlChange(unsigned int channel, unsigned int controller, unsigned int value); virtual void handleProgramChange(unsigned int channel, unsigned int program); virtual void handleAfterTouch(unsigned int channel, unsigned int velocity); virtual void handlePitchChange(unsigned int pitch); virtual void handleSongPosition(unsigned int position); virtual void handleSongSelect(unsigned int song); virtual void handleTuneRequest(void); virtual void handleSync(void); virtual void handleStart(void); virtual void handleContinue(void); virtual void handleStop(void); virtual void handleActiveSense(void); virtual void handleReset(void); // sysex experimental void appendSysex(uint8_t cin, uint8_t midi0, uint8_t midi1, uint8_t midi2); virtual void handleSysex(uint8_t *sysexBuffer, uint32 len); uint8_t sysexstring[MAX_SYSEX_SIZE]; uint32_t sysexpos; void sendSysex(uint8_t *sysexBuffer, uint32 len); }; extern const uint32 midiNoteFrequency_10ths[128]; #endif <file_sep>/usb_midi_device.c /****************************************************************************** * The MIT License * * Copyright (c) 2011 LeafLabs LLC. * Copyright (c) 2013 <NAME>. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file libmaple/usb/stm32f1/usb_midi_device.c * @brief USB MIDI. * * FIXME: this works on the STM32F1 USB peripherals, and probably no * place else. Nonportable bits really need to be factored out, and * the result made cleaner. */ #include <string.h> #include "usb_generic.h" #include "usb_midi_device.h" #include <MidiSpecs.h> #include <MinSysex.h> #include <libmaple/usb.h> #include <libmaple/delay.h> /* Private headers */ #include "usb_lib_globals.h" #include "usb_reg_map.h" /* usb_lib headers */ #include "usb_type.h" #include "usb_core.h" #include "usb_def.h" static void midiDataTxCb(void); static void midiDataRxCb(void); static void usbMIDIReset(void); #define MIDI_ENDPOINT_RX 0 #define MIDI_ENDPOINT_TX 1 #define USB_MIDI_RX_ENDP (midiEndpoints[MIDI_ENDPOINT_RX].address) #define USB_MIDI_TX_ENDP (midiEndpoints[MIDI_ENDPOINT_TX].address) #define USB_MIDI_RX_ENDPOINT_INFO (&midiEndpoints[MIDI_ENDPOINT_RX]) #define USB_MIDI_TX_ENDPOINT_INFO (&midiEndpoints[MIDI_ENDPOINT_TX]) #define USB_MIDI_RX_PMA_PTR (midiEndpoints[MIDI_ENDPOINT_RX].pma) #define USB_MIDI_TX_PMA_PTR (midiEndpoints[MIDI_ENDPOINT_TX].pma) /* * Descriptors */ typedef struct { // usb_descriptor_config_header Config_Header; /* Control Interface */ usb_descriptor_interface AC_Interface; AC_CS_INTERFACE_DESCRIPTOR(1) AC_CS_Interface; /* Control Interface */ usb_descriptor_interface MS_Interface; MS_CS_INTERFACE_DESCRIPTOR MS_CS_Interface; MIDI_IN_JACK_DESCRIPTOR MIDI_IN_JACK_1; MIDI_IN_JACK_DESCRIPTOR MIDI_IN_JACK_2; MIDI_OUT_JACK_DESCRIPTOR(1) MIDI_OUT_JACK_3; MIDI_OUT_JACK_DESCRIPTOR(1) MIDI_OUT_JACK_4; usb_descriptor_endpoint DataOutEndpoint; MS_CS_BULK_ENDPOINT_DESCRIPTOR(1) MS_CS_DataOutEndpoint; usb_descriptor_endpoint DataInEndpoint; MS_CS_BULK_ENDPOINT_DESCRIPTOR(1) MS_CS_DataInEndpoint; } __packed usb_descriptor_config; static const usb_descriptor_config usbMIDIDescriptor_Config = { /* .Config_Header = { .bLength = sizeof(usb_descriptor_config_header), .bDescriptorType = USB_DESCRIPTOR_TYPE_CONFIGURATION, .wTotalLength = sizeof(usb_descriptor_config), .bNumInterfaces = 0x02, .bConfigurationValue = 0x01, .iConfiguration = 0x00, .bmAttributes = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED), .bMaxPower = MAX_POWER, }, */ .AC_Interface = { .bLength = sizeof(usb_descriptor_interface), .bDescriptorType = USB_DESCRIPTOR_TYPE_INTERFACE, .bInterfaceNumber = 0x00, // PATCH .bAlternateSetting = 0x00, .bNumEndpoints = 0x00, .bInterfaceClass = USB_INTERFACE_CLASS_AUDIO, .bInterfaceSubClass = USB_INTERFACE_AUDIOCONTROL, .bInterfaceProtocol = 0x00, .iInterface = 0x00, }, .AC_CS_Interface = { .bLength = AC_CS_INTERFACE_DESCRIPTOR_SIZE(1), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_INTERFACE, .SubType = 0x01, .bcdADC = 0x0100, .wTotalLength = AC_CS_INTERFACE_DESCRIPTOR_SIZE(1), .bInCollection = 0x01, .baInterfaceNr = {0x01}, }, .MS_Interface = { .bLength = sizeof(usb_descriptor_interface), .bDescriptorType = USB_DESCRIPTOR_TYPE_INTERFACE, .bInterfaceNumber = 0x01, // PATCH .bAlternateSetting = 0x00, .bNumEndpoints = 0x02, .bInterfaceClass = USB_INTERFACE_CLASS_AUDIO, .bInterfaceSubClass = USB_INTERFACE_MIDISTREAMING, .bInterfaceProtocol = 0x00, .iInterface = 0, // was 0x04 }, .MS_CS_Interface = { .bLength = sizeof(MS_CS_INTERFACE_DESCRIPTOR), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_INTERFACE, .SubType = 0x01, .bcdADC = 0x0100, .wTotalLength = sizeof(MS_CS_INTERFACE_DESCRIPTOR) +sizeof(MIDI_IN_JACK_DESCRIPTOR) +sizeof(MIDI_IN_JACK_DESCRIPTOR) +MIDI_OUT_JACK_DESCRIPTOR_SIZE(1) +MIDI_OUT_JACK_DESCRIPTOR_SIZE(1) +sizeof(usb_descriptor_endpoint) +MS_CS_BULK_ENDPOINT_DESCRIPTOR_SIZE(1) +sizeof(usb_descriptor_endpoint) +MS_CS_BULK_ENDPOINT_DESCRIPTOR_SIZE(1) /* 0x41-4 */, }, .MIDI_IN_JACK_1 = { .bLength = sizeof(MIDI_IN_JACK_DESCRIPTOR), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_INTERFACE, .SubType = MIDI_IN_JACK, .bJackType = MIDI_JACK_EMBEDDED, .bJackId = 0x01, .iJack = 0x05, }, .MIDI_IN_JACK_2 = { .bLength = sizeof(MIDI_IN_JACK_DESCRIPTOR), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_INTERFACE, .SubType = MIDI_IN_JACK, .bJackType = MIDI_JACK_EXTERNAL, .bJackId = 0x02, .iJack = 0x00, }, .MIDI_OUT_JACK_3 = { .bLength = MIDI_OUT_JACK_DESCRIPTOR_SIZE(1), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_INTERFACE, .SubType = MIDI_OUT_JACK, .bJackType = MIDI_JACK_EMBEDDED, .bJackId = 0x03, .bNrInputPins = 0x01, .baSourceId = {0x02}, .baSourcePin = {0x01}, .iJack = 0x00, }, .MIDI_OUT_JACK_4 = { .bLength = MIDI_OUT_JACK_DESCRIPTOR_SIZE(1), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_INTERFACE, .SubType = MIDI_OUT_JACK, .bJackType = MIDI_JACK_EXTERNAL, // .bJackId = 0x04, .bJackId = 0x03, .bNrInputPins = 0x01, .baSourceId = {0x01}, .baSourcePin = {0x01}, .iJack = 0x00, }, .DataOutEndpoint = { .bLength = sizeof(usb_descriptor_endpoint), .bDescriptorType = USB_DESCRIPTOR_TYPE_ENDPOINT, .bEndpointAddress = (USB_DESCRIPTOR_ENDPOINT_OUT | 0), // PATCH: USB_MIDI_RX_ENDP .bmAttributes = USB_EP_TYPE_BULK, .wMaxPacketSize = 64, // PATCH .bInterval = 0x00, }, .MS_CS_DataOutEndpoint = { .bLength = MS_CS_BULK_ENDPOINT_DESCRIPTOR_SIZE(1), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_ENDPOINT, .SubType = 0x01, .bNumEmbMIDIJack = 0x01, .baAssocJackID = {0x01}, }, .DataInEndpoint = { .bLength = sizeof(usb_descriptor_endpoint), .bDescriptorType = USB_DESCRIPTOR_TYPE_ENDPOINT, .bEndpointAddress = (USB_DESCRIPTOR_ENDPOINT_IN | 0), // PATCH: USB_MIDI_TX_ENDP .bmAttributes = USB_EP_TYPE_BULK, .wMaxPacketSize = 64, // PATCH .bInterval = 0x00, }, .MS_CS_DataInEndpoint = { .bLength = MS_CS_BULK_ENDPOINT_DESCRIPTOR_SIZE(1), .bDescriptorType = USB_DESCRIPTOR_TYPE_CS_ENDPOINT, .SubType = 0x01, .bNumEmbMIDIJack = 0x01, .baAssocJackID = {0x03}, }, }; /* I/O state */ /* Received data */ static volatile uint32 midiBufferRx[64/4]; /* Read index into midiBufferRx */ static volatile uint32 rx_offset = 0; /* Transmit data */ static volatile uint32 midiBufferTx[64/4]; /* Write index into midiBufferTx */ static volatile uint32 tx_offset = 0; /* Number of bytes left to transmit */ static volatile uint32 n_unsent_packets = 0; /* Are we currently sending an IN packet? */ static volatile uint8 transmitting = 0; /* Number of unread bytes */ static volatile uint32 n_unread_packets = 0; uint32_t usb_midi_txEPSize = 64; static uint32_t rxEPSize = 64; // eventually all of this should be in a place for settings which can be written to flash. volatile uint8 myMidiChannel = DEFAULT_MIDI_CHANNEL; volatile uint8 myMidiDevice = DEFAULT_MIDI_DEVICE; volatile uint8 myMidiCable = DEFAULT_MIDI_CABLE; volatile uint8 myMidiID[] = { LEAFLABS_MMA_VENDOR_1,LEAFLABS_MMA_VENDOR_2,LEAFLABS_MMA_VENDOR_3,0}; #define OUT_BYTE(s,v) out[(uint8*)&(s.v)-(uint8*)&s] #define OUT_16(s,v) *(uint16_t*)&OUT_BYTE(s,v) // OK on Cortex which can handle unaligned writes static USBEndpointInfo midiEndpoints[2] = { { .callback = midiDataRxCb, .pmaSize = 64, // patch .type = USB_GENERIC_ENDPOINT_TYPE_BULK, .tx = 0 }, { .callback = midiDataTxCb, .pmaSize = 64, // patch .type = USB_GENERIC_ENDPOINT_TYPE_BULK, .tx = 1, } }; static void getMIDIPartDescriptor(uint8* out) { memcpy(out, &usbMIDIDescriptor_Config, sizeof(usbMIDIDescriptor_Config)); // patch to reflect where the part goes in the descriptor OUT_BYTE(usbMIDIDescriptor_Config, AC_Interface.bInterfaceNumber) += usbMIDIPart.startInterface; OUT_BYTE(usbMIDIDescriptor_Config, MS_Interface.bInterfaceNumber) += usbMIDIPart.startInterface; OUT_BYTE(usbMIDIDescriptor_Config, AC_CS_Interface.baInterfaceNr) += usbMIDIPart.startInterface; OUT_BYTE(usbMIDIDescriptor_Config, DataOutEndpoint.bEndpointAddress) += USB_MIDI_RX_ENDP; OUT_BYTE(usbMIDIDescriptor_Config, DataInEndpoint.bEndpointAddress) += USB_MIDI_TX_ENDP; OUT_16(usbMIDIDescriptor_Config, DataInEndpoint.wMaxPacketSize) = usb_midi_txEPSize; OUT_16(usbMIDIDescriptor_Config, DataOutEndpoint.wMaxPacketSize) = usb_midi_txEPSize; } USBCompositePart usbMIDIPart = { .numInterfaces = 2, .numEndpoints = sizeof(midiEndpoints)/sizeof(*midiEndpoints), .descriptorSize = sizeof(usbMIDIDescriptor_Config), .getPartDescriptor = getMIDIPartDescriptor, .usbInit = NULL, .usbReset = usbMIDIReset, .usbDataSetup = NULL, .usbNoDataSetup = NULL, .endpoints = midiEndpoints }; void usb_midi_setTXEPSize(uint32_t size) { size = (size+3)/4*4; if (size == 0 || size > 64) size = 64; midiEndpoints[1].pmaSize = size; usb_midi_txEPSize = size; } void usb_midi_setRXEPSize(uint32_t size) { size = (size+3)/4*4; if (size == 0 || size > 64) size = 64; midiEndpoints[0].pmaSize = size; rxEPSize = size; } /* * MIDI interface */ /* This function is non-blocking. * * It copies data from a usercode buffer into the USB peripheral TX * buffer, and returns the number of bytes copied. */ uint32 usb_midi_tx(const uint32* buf, uint32 packets) { uint32 bytes=packets*4; /* Last transmission hasn't finished, so abort. */ if (usb_midi_is_transmitting()) { /* Copy to TxBuffer */ return 0; /* return len */ } /* We can only put usb_midi_txEPSize bytes in the buffer. */ if (bytes > usb_midi_txEPSize) { bytes = usb_midi_txEPSize; packets=bytes/4; } /* Queue bytes for sending. */ if (packets) { usb_copy_to_pma_ptr((uint8 *)buf, bytes, USB_MIDI_TX_PMA_PTR); } // We still need to wait for the interrupt, even if we're sending // zero bytes. (Sending zero-size packets is useful for flushing // host-side buffers.) n_unsent_packets = packets; transmitting = 1; usb_generic_set_tx(USB_MIDI_TX_ENDPOINT_INFO, bytes); return packets; } uint32 usb_midi_data_available(void) { return n_unread_packets; } uint8 usb_midi_is_transmitting(void) { return transmitting; } uint16 usb_midi_get_pending(void) { return n_unsent_packets; } /* Nonblocking byte receive. * * Copies up to len bytes from our private data buffer (*NOT* the PMA) * into buf and deq's the FIFO. */ uint32 usb_midi_rx(uint32* buf, uint32 packets) { /* Copy bytes to buffer. */ uint32 n_copied = usb_midi_peek(buf, packets); /* Mark bytes as read. */ n_unread_packets -= n_copied; rx_offset += n_copied; /* If all bytes have been read, re-enable the RX endpoint, which * was set to NAK when the current batch of bytes was received. */ if (n_unread_packets == 0) { usb_generic_enable_rx(USB_MIDI_RX_ENDPOINT_INFO); rx_offset = 0; } return n_copied; } /* Nonblocking byte lookahead. * * Looks at unread bytes without marking them as read. */ uint32 usb_midi_peek(uint32* buf, uint32 packets) { uint32 i; if (packets > n_unread_packets) { packets = n_unread_packets; } for (i = 0; i < packets; i++) { buf[i] = midiBufferRx[i + rx_offset]; } return packets; } /* * Callbacks */ static void midiDataTxCb(void) { n_unsent_packets = 0; transmitting = 0; } static void midiDataRxCb(void) { usb_generic_pause_rx(USB_MIDI_RX_ENDPOINT_INFO); n_unread_packets = usb_get_ep_rx_count(USB_MIDI_RX_ENDP) / 4; /* This copy won't overwrite unread bytes, since we've set the RX * endpoint to NAK, and will only set it to VALID when all bytes * have been read. */ usb_copy_from_pma_ptr((uint8*)midiBufferRx, n_unread_packets * 4, USB_MIDI_RX_PMA_PTR); // discard volatile LglSysexHandler((uint32*)midiBufferRx,(uint32*)&rx_offset,(uint32*)&n_unread_packets); if (n_unread_packets == 0) { usb_generic_enable_rx(USB_MIDI_RX_ENDPOINT_INFO); rx_offset = 0; } } static void usbMIDIReset(void) { /* Reset the RX/TX state */ n_unread_packets = 0; n_unsent_packets = 0; rx_offset = 0; } // .............THIS IS NOT WORKING YET................ // send debugging information to static uint8_t sysexbuffer[80]={CIN_SYSEX,0xF0,0x7D,0x33,CIN_SYSEX,0x33,0x00,0xf7}; // !!!bad hardcoded number foo !!! uint8_t iSysHexLine(uint8_t rectype, uint16_t address, uint8_t *payload,uint8_t payloadlength, uint8_t *buffer); void sendThroughSysex(char *printbuffer, int bufferlength) { int n; n = iSysHexLine(1, 0 , (uint8_t *) printbuffer, (uint8_t) bufferlength , sysexbuffer+6); usb_midi_tx((uint32*)sysexbuffer,n/4); } #define HIGHBYTE(x) ((uint8_t) (((x) >> 8) & 0x00ff) ) #define LOWBYTE(x) ((uint8_t) ((x) & 0x00ff) ) #define HIGHNIBBLE(x) ((((uint8_t)(x)) & 0xF0) >> 4) #define LOWNIBBLE(x) (((uint8_t)(x)) & 0x0F) #define HEXCHAR(c) ((c>9)?55+c:48+c) uint8_t iSysHexLine(uint8_t rectype, uint16_t address, uint8_t *payload,uint8_t payloadlength, uint8_t *buffer) { int i=0; int j; int thirdone; uint8_t n=0; uint16_t checksum=0; //uint16_t length=0; buffer[i++]=':'; checksum+=payloadlength; buffer[i++]=HEXCHAR(HIGHNIBBLE(payloadlength)); buffer[i++]=HEXCHAR(LOWNIBBLE(payloadlength)); buffer[i++]=CIN_SYSEX; n=HIGHBYTE(address); checksum+=n; buffer[i++]=HEXCHAR(HIGHNIBBLE(n)); buffer[i++]=HEXCHAR(LOWNIBBLE(n)); n=LOWBYTE(address); checksum+=n; buffer[i++]=HEXCHAR(HIGHNIBBLE(n)); buffer[i++]=CIN_SYSEX; buffer[i++]=HEXCHAR(LOWNIBBLE(n)); n=rectype; checksum+=n; buffer[i++]=HEXCHAR(HIGHNIBBLE(n)); buffer[i++]=HEXCHAR(LOWNIBBLE(n)); buffer[i++]=CIN_SYSEX; thirdone=0; for (j=0; j<payloadlength ; j++) { n=payload[j]; checksum+=n; buffer[i++]=HEXCHAR(HIGHNIBBLE(n)); if (++thirdone==3) { buffer[i++]=CIN_SYSEX; thirdone=0; } buffer[i++]=HEXCHAR(LOWNIBBLE(n)); if (++thirdone==3) { buffer[i++]=CIN_SYSEX; thirdone=0; } } if (thirdone==0) { buffer[i-1]=CIN_SYSEX_ENDS_IN_3; } n=~((uint8_t) checksum&0x00ff)+1; buffer[i++]=HEXCHAR(HIGHNIBBLE(n)); if (thirdone==1) { buffer[i++]=CIN_SYSEX_ENDS_IN_2; } buffer[i++]=HEXCHAR(LOWNIBBLE(n)); if (thirdone==2) { buffer[i++]=CIN_SYSEX_ENDS_IN_1; } buffer[i++]=0xf7; return i+thirdone; } <file_sep>/usb_generic.c /****************************************************************************** * The MIT License * * Copyright (c) 2011 LeafLabs LLC. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file libmaple/usb/stm32f1/usb_hid.c * @brief USB HID (human interface device) support * * FIXME: this works on the STM32F1 USB peripherals, and probably no * place else. Nonportable bits really need to be factored out, and * the result made cleaner. */ //#define MATCHING_ENDPOINT_RANGES // make RX and TX endpoints fall in the same range for each part #include <string.h> #include <libmaple/libmaple_types.h> #include <libmaple/usb.h> #include <libmaple/delay.h> #include <libmaple/gpio.h> #include <usb_lib_globals.h> #include <usb_reg_map.h> //#include <usb_core.h> #include <board/board.h> /* usb_lib headers */ #include "usb_type.h" #include "usb_core.h" #include "usb_def.h" #include "usb_generic.h" const char DEFAULT_PRODUCT[] = "Maple"; const char DEFAULT_MANUFACTURER[] = "LeafLabs"; static uint8* usbGetConfigDescriptor(uint16 length); static void usbInit(void); static void usbReset(void); static void usbClearFeature(void); static void usbSetConfiguration(void); static RESULT usbDataSetup(uint8 request); static RESULT usbNoDataSetup(uint8 request); static RESULT usbGetInterfaceSetting(uint8 interface, uint8 alt_setting); static uint8* usbGetStringDescriptor(uint16 length); static uint8* usbGetConfigDescriptor(uint16 length); static uint8* usbGetDeviceDescriptor(uint16 length); static void usbSetConfiguration(void); static void usbSetDeviceAddress(void); static uint32 disconnect_delay = 500; // in microseconds static struct usb_chunk* control_tx_chunk_list = NULL; static uint8 control_tx_chunk_buffer[USB_EP0_BUFFER_SIZE]; static volatile uint8* control_tx_buffer = NULL; static uint16 control_tx_length = 0; static volatile uint8* control_tx_done = NULL; static volatile uint8* control_rx_buffer = NULL; static uint16 control_rx_length = 0; static volatile uint8* control_rx_done = NULL; uint16 epTypes[4] = { USB_EP_EP_TYPE_BULK, USB_EP_EP_TYPE_CONTROL, USB_EP_EP_TYPE_ISO, USB_EP_EP_TYPE_INTERRUPT }; #define LEAFLABS_ID_VENDOR 0x1EAF #define MAPLE_ID_PRODUCT 0x0024 // was 0x0024 #define USB_DEVICE_CLASS 0x00 #define USB_DEVICE_SUBCLASS 0x00 #define DEVICE_PROTOCOL 0x01 //#define REQUEST_TYPE 0b01100000u #define REQUEST_RECIPIENT 0b00011111u static usb_descriptor_device usbGenericDescriptor_Device = { .bLength = sizeof(usb_descriptor_device), .bDescriptorType = USB_DESCRIPTOR_TYPE_DEVICE, .bcdUSB = 0x0200, .bDeviceClass = USB_DEVICE_CLASS, .bDeviceSubClass = USB_DEVICE_SUBCLASS, .bDeviceProtocol = DEVICE_PROTOCOL, .bMaxPacketSize0 = 0x40, .idVendor = LEAFLABS_ID_VENDOR, .idProduct = MAPLE_ID_PRODUCT, .bcdDevice = 0x0200, .iManufacturer = 0x01, .iProduct = 0x02, .iSerialNumber = 0x00, .bNumConfigurations = 0x01, }; typedef struct { usb_descriptor_config_header Config_Header; uint8 descriptorData[MAX_USB_DESCRIPTOR_DATA_SIZE]; } __packed usb_descriptor_config; static usb_descriptor_config usbConfig; #define MAX_POWER (100 >> 1) static const usb_descriptor_config_header Base_Header = { .bLength = sizeof(usb_descriptor_config_header), .bDescriptorType = USB_DESCRIPTOR_TYPE_CONFIGURATION, .wTotalLength = 0, .bNumInterfaces = 0, .bConfigurationValue = 0x01, .iConfiguration = 0x00, .bmAttributes = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED), .bMaxPower = MAX_POWER, }; static ONE_DESCRIPTOR Device_Descriptor = { (uint8*)&usbGenericDescriptor_Device, sizeof(usb_descriptor_device) }; static ONE_DESCRIPTOR Config_Descriptor = { (uint8*)&usbConfig, 0 }; static DEVICE my_Device_Table = { .Total_Endpoint = 0, .Total_Configuration = 1 }; /* Unicode language identifier: 0x0409 is US English */ static const usb_descriptor_string usb_LangID = { .bLength = USB_DESCRIPTOR_STRING_LEN(1), .bDescriptorType = USB_DESCRIPTOR_TYPE_STRING, .bString = {0x09, 0x04}, }; static USB_DESCRIPTOR_STRING(USB_DESCRIPTOR_STRING_LEN(USB_MAX_STRING_DESCRIPTOR_LENGTH)) string_descriptor_buffer = { .bDescriptorType = USB_DESCRIPTOR_TYPE_STRING }; static ONE_DESCRIPTOR generic_string_descriptor = { (uint8*)&string_descriptor_buffer, 0 }; #define MAX_PACKET_SIZE 0x40 /* 64B, maximum for USB FS Devices */ static const DEVICE_PROP my_Device_Property = { .Init = usbInit, .Reset = usbReset, .Process_Status_IN = NOP_Process, .Process_Status_OUT = NOP_Process, .Class_Data_Setup = usbDataSetup, .Class_NoData_Setup = usbNoDataSetup, .Class_Get_Interface_Setting = usbGetInterfaceSetting, .GetDeviceDescriptor = usbGetDeviceDescriptor, .GetConfigDescriptor = usbGetConfigDescriptor, .GetStringDescriptor = usbGetStringDescriptor, .RxEP_buffer = NULL, .MaxPacketSize = MAX_PACKET_SIZE }; static const USER_STANDARD_REQUESTS my_User_Standard_Requests = { .User_GetConfiguration = NOP_Process, .User_SetConfiguration = usbSetConfiguration, .User_GetInterface = NOP_Process, .User_SetInterface = NOP_Process, .User_GetStatus = NOP_Process, .User_ClearFeature = usbClearFeature, .User_SetEndPointFeature = NOP_Process, .User_SetDeviceFeature = NOP_Process, .User_SetDeviceAddress = usbSetDeviceAddress }; static uint8 numStringDescriptors = 3; #define MAX_STRING_DESCRIPTORS 4 static ONE_DESCRIPTOR String_Descriptor[MAX_STRING_DESCRIPTORS] = { {(uint8*)&usb_LangID, USB_DESCRIPTOR_STRING_LEN(1)}, {(uint8*)DEFAULT_MANUFACTURER, 0}, // a 0 in the length field indicates that we synthesize this from an asciiz string {(uint8*)DEFAULT_PRODUCT, 0}, {NULL, 0}, }; static USBCompositePart** parts; static uint32 numParts; static DEVICE saved_Device_Table; static DEVICE_PROP saved_Device_Property; static USER_STANDARD_REQUESTS saved_User_Standard_Requests; static void (*ep_int_in[7])(void); static void (*ep_int_out[7])(void); static uint8 minimum_address; static uint8 acceptable_endpoint_number(unsigned partNum, unsigned endpointNum, uint8 address) { USBEndpointInfo* ep = &(parts[partNum]->endpoints[endpointNum]); for (unsigned i = 0 ; i <= partNum ; i++) for(unsigned j = 0 ; (i < partNum && j < parts[partNum]->numEndpoints) || (i == partNum && j < endpointNum) ; j++) { USBEndpointInfo* ep1 = &(parts[i]->endpoints[j]); if (ep1->address != address) continue; if (ep1->tx == ep->tx || ep->exclusive || ep1->exclusive || ep1->type != ep->type || ep1->doubleBuffer != ep->doubleBuffer) return 0; } return 1; } static int8 allocate_endpoint_address(unsigned partNum, unsigned endpointNum) { for (uint8 address = minimum_address ; address < 8 ; address++) if (acceptable_endpoint_number(partNum, endpointNum, address)) return address; return -1; } uint8 usb_generic_set_parts(USBCompositePart** _parts, unsigned _numParts) { parts = _parts; numParts = _numParts; unsigned numInterfaces = 0; minimum_address = 1; uint8 maxAddress = 0; uint16 usbDescriptorSize = 0; uint16 pmaOffset = USB_EP0_RX_BUFFER_ADDRESS + USB_EP0_BUFFER_SIZE; for (unsigned i = 0 ; i < 7 ; i++) { ep_int_in[i] = NOP_Process; ep_int_out[i] = NOP_Process; } usbDescriptorSize = 0; for (unsigned i = 0 ; i < _numParts ; i++ ) { USBCompositePart* part = parts[i]; part->startInterface = numInterfaces; numInterfaces += part->numInterfaces; if (usbDescriptorSize + part->descriptorSize > MAX_USB_DESCRIPTOR_DATA_SIZE) { return 0; } USBEndpointInfo* ep = part->endpoints; for (unsigned j = 0 ; j < part->numEndpoints ; j++) { int8 address = allocate_endpoint_address(i, j); if (address < 0) return 0; ep[j].pma = usb_pma_ptr(pmaOffset); uint32 size = ep[j].pmaSize; // rx has special length alignment issues if (ep[j].doubleBuffer) { if (size <= 124 || ep[j].tx) { size = (size+3)/4*4; } else { size = (size+63)/64*64; } } else { if (size <= 62 || ep[j].tx) { size = (size+1)/2*2; } else { size = (size+31)/32*32; } } pmaOffset += size; if (pmaOffset > PMA_MEMORY_SIZE) return 0; if (ep[j].callback == NULL) ep[j].callback = NOP_Process; ep[j].address = address; if (ep[j].tx) { ep_int_in[address-1] = ep[j].callback; } else { ep_int_out[address-1] = ep[j].callback; } if (maxAddress < address) maxAddress = address; } part->getPartDescriptor(usbConfig.descriptorData + usbDescriptorSize); usbDescriptorSize += part->descriptorSize; #ifdef MATCHING_ENDPOINT_RANGES minimum_address = maxAddress + 1; #endif } usbConfig.Config_Header = Base_Header; usbConfig.Config_Header.bNumInterfaces = numInterfaces; usbConfig.Config_Header.wTotalLength = usbDescriptorSize + sizeof(Base_Header); Config_Descriptor.Descriptor_Size = usbConfig.Config_Header.wTotalLength; my_Device_Table.Total_Endpoint = maxAddress + 1; return 1; } void usb_generic_set_info(uint16 idVendor, uint16 idProduct, const char* iManufacturer, const char* iProduct, const char* iSerialNumber) { if (idVendor != 0) usbGenericDescriptor_Device.idVendor = idVendor; else usbGenericDescriptor_Device.idVendor = LEAFLABS_ID_VENDOR; if (idProduct != 0) usbGenericDescriptor_Device.idProduct = idProduct; else usbGenericDescriptor_Device.idProduct = MAPLE_ID_PRODUCT; if (iManufacturer == NULL) { iManufacturer = DEFAULT_MANUFACTURER; } String_Descriptor[1].Descriptor = (uint8*)iManufacturer; String_Descriptor[1].Descriptor_Size = 0; if (iProduct == NULL) { iProduct = DEFAULT_PRODUCT; } String_Descriptor[2].Descriptor = (uint8*)iProduct; String_Descriptor[2].Descriptor_Size = 0; if (iSerialNumber == NULL) { numStringDescriptors = 3; usbGenericDescriptor_Device.iSerialNumber = 0; } else { String_Descriptor[3].Descriptor = (uint8*)iSerialNumber; String_Descriptor[3].Descriptor_Size = 0; numStringDescriptors = 4; usbGenericDescriptor_Device.iSerialNumber = 3; } } void usb_generic_enable(void) { /* Present ourselves to the host. Writing 0 to "disc" pin must * pull USB_DP pin up while leaving USB_DM pulled down by the * transceiver. See USB 2.0 spec, section 7.1.7.3. */ #ifdef GENERIC_BOOTLOADER //Reset the USB interface on generic boards - developed by <NAME> gpio_set_mode(GPIOA, 12, GPIO_OUTPUT_PP); gpio_write_bit(GPIOA, 12, 0); delay_us(disconnect_delay); gpio_set_mode(GPIOA, 12, GPIO_INPUT_FLOATING); #endif if (BOARD_USB_DISC_DEV != NULL) { gpio_set_mode(BOARD_USB_DISC_DEV, (uint8)(uint32)BOARD_USB_DISC_BIT, GPIO_OUTPUT_PP); gpio_write_bit(BOARD_USB_DISC_DEV, (uint8)(uint32)BOARD_USB_DISC_BIT, 0); } saved_Device_Table = Device_Table; saved_Device_Property = Device_Property; saved_User_Standard_Requests = User_Standard_Requests; Device_Table = my_Device_Table; Device_Property = my_Device_Property; User_Standard_Requests = my_User_Standard_Requests; /* Initialize the USB peripheral. */ usb_init_usblib(USBLIB, ep_int_in, ep_int_out); } void usb_generic_set_disconnect_delay(uint32 delay) { disconnect_delay = delay; } static void usbInit(void) { pInformation->Current_Configuration = 0; USB_BASE->CNTR = USB_CNTR_FRES; USBLIB->irq_mask = 0; USB_BASE->CNTR = USBLIB->irq_mask; USB_BASE->ISTR = 0; USBLIB->irq_mask = USB_CNTR_RESETM | USB_CNTR_SUSPM | USB_CNTR_WKUPM; USB_BASE->CNTR = USBLIB->irq_mask; USB_BASE->ISTR = 0; USBLIB->irq_mask = USB_ISR_MSK; USB_BASE->CNTR = USBLIB->irq_mask; usb_generic_enable_interrupts_ep0(); for (unsigned i = 0 ; i < numParts ; i++) if(parts[i]->usbInit != NULL) parts[i]->usbInit(); USBLIB->state = USB_UNCONNECTED; } #define BTABLE_ADDRESS 0x00 static inline uint16 pma_ptr_to_offset(uint32* p) { return (uint16)(((uint32*)p-(uint32*)USB_PMA_BASE) * 2); } static void usbReset(void) { pInformation->Current_Configuration = 0; /* current feature is current bmAttributes */ pInformation->Current_Feature = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED); USB_BASE->BTABLE = BTABLE_ADDRESS; /* setup control endpoint 0 */ usb_set_ep_type(USB_EP0, USB_EP_EP_TYPE_CONTROL); usb_set_ep_tx_stat(USB_EP0, USB_EP_STAT_TX_STALL); usb_set_ep_rx_addr(USB_EP0, USB_EP0_RX_BUFFER_ADDRESS); usb_set_ep_tx_addr(USB_EP0, USB_EP0_TX_BUFFER_ADDRESS); usb_clear_status_out(USB_EP0); usb_set_ep_rx_count(USB_EP0, USB_EP0_BUFFER_SIZE); usb_set_ep_rx_stat(USB_EP0, USB_EP_STAT_RX_VALID); for (unsigned i = 1 ; i < 8 ; i++) { usb_set_ep_rx_stat(i, USB_EP_STAT_RX_DISABLED); usb_clear_ep_dtog_rx(i); usb_set_ep_tx_stat(i, USB_EP_STAT_TX_DISABLED); usb_clear_ep_dtog_tx(i); } for (unsigned i = 0 ; i < numParts ; i++) { for (unsigned j = 0 ; j < parts[i]->numEndpoints ; j++) { USBEndpointInfo* e = &(parts[i]->endpoints[j]); uint8 address = e->address; usb_set_ep_type(address, epTypes[e->type]); usb_set_ep_kind(address, e->doubleBuffer ? USB_EP_EP_KIND_DBL_BUF : 0); uint16 pmaOffset = pma_ptr_to_offset(e->pma); if (e->tx) { usb_set_ep_tx_addr(address, pmaOffset); usb_set_ep_tx_stat(address, USB_EP_STAT_TX_NAK); if (e->doubleBuffer) { usb_set_ep_tx_buf0_addr(address, pmaOffset); usb_set_ep_tx_buf1_addr(address, pmaOffset+e->pmaSize/2); usb_set_ep_tx_buf0_count(address, e->pmaSize/2); usb_set_ep_tx_buf1_count(address, e->pmaSize/2); } } else { usb_set_ep_rx_addr(address, pmaOffset); if (! e->doubleBuffer) { usb_set_ep_rx_count(address, e->pmaSize); } usb_set_ep_rx_stat(address, USB_EP_STAT_RX_VALID); } } if (parts[i]->usbReset != NULL) parts[i]->usbReset(); } control_rx_length = 0; control_tx_length = 0; USBLIB->state = USB_ATTACHED; SetDeviceAddress(0); } static void usb_power_down(void) { USB_BASE->CNTR = USB_CNTR_FRES; USB_BASE->ISTR = 0; USB_BASE->CNTR = USB_CNTR_FRES + USB_CNTR_PDWN; } void usb_generic_disable(void) { /* Turn off the interrupt and signal disconnect (see e.g. USB 2.0 * spec, section 7.1.7.3). */ usb_generic_disable_interrupts_ep0(); if (BOARD_USB_DISC_DEV != NULL) { gpio_write_bit(BOARD_USB_DISC_DEV, (uint8)(uint32)BOARD_USB_DISC_BIT, 1); } usb_power_down(); Device_Table = saved_Device_Table; Device_Property = saved_Device_Property; User_Standard_Requests = saved_User_Standard_Requests; for (uint32 i=0; i < numParts; i++) if (parts[i]->clear) parts[i]->clear(); } static uint8* control_data_tx(uint16 length) { unsigned wOffset = pInformation->Ctrl_Info.Usb_wOffset; if (length == 0) { pInformation->Ctrl_Info.Usb_wLength = control_tx_length - wOffset; return NULL; } if (control_tx_done && pInformation->USBwLengths.w <= wOffset + pInformation->Ctrl_Info.PacketSize) *control_tx_done = USB_CONTROL_DONE; // this may be a bit premature, but it's our best try if (control_tx_buffer == NULL) return NULL; else return (uint8*)control_tx_buffer + wOffset; } void usb_generic_control_tx_setup(volatile void* buffer, uint16 length, volatile uint8* done) { control_tx_buffer = buffer; control_tx_length = length; control_tx_done = done; pInformation->Ctrl_Info.CopyData = control_data_tx; pInformation->Ctrl_Info.Usb_wOffset = 0; control_data_tx(0); } uint32 usb_generic_chunks_length(struct usb_chunk* chunk) { uint32 l=0; while (chunk != NULL) { l += chunk->dataLength; chunk = chunk->next; } return l; } static uint8* control_data_chunk_tx(uint16 length) { unsigned wOffset = pInformation->Ctrl_Info.Usb_wOffset; if (length == 0) { pInformation->Ctrl_Info.Usb_wLength = usb_generic_chunks_length(control_tx_chunk_list) - wOffset; return NULL; } if (control_tx_chunk_list == NULL) { return NULL; } else { uint32 chunks_offset = 0; uint32 buf_offset = 0; for (struct usb_chunk* chunk = control_tx_chunk_list ; chunk != NULL && chunks_offset < wOffset + length ; chunk = chunk->next ) { uint32 len = chunk->dataLength; if (len == 0) continue; if (wOffset < chunks_offset + len) { /* need to copy some data from this chunk */ uint32 start; if (wOffset <= chunks_offset) { start = 0; } else { start = wOffset - chunks_offset; } uint32 to_copy; if (wOffset + length <= chunks_offset + len) { to_copy = wOffset + length - chunks_offset - start; } else { to_copy = len - start; } memcpy(control_tx_chunk_buffer + buf_offset, chunk->data + start, to_copy); buf_offset += to_copy; } chunks_offset += len; } return (uint8*)control_tx_chunk_buffer; } } void usb_generic_control_tx_chunk_setup(struct usb_chunk* chunk) { control_tx_chunk_list = chunk; pInformation->Ctrl_Info.CopyData = control_data_chunk_tx; pInformation->Ctrl_Info.Usb_wOffset = 0; control_data_chunk_tx(0); } static uint8* control_data_rx(uint16 length) { unsigned wOffset = pInformation->Ctrl_Info.Usb_wOffset; if (length ==0) { uint16 len = pInformation->USBwLengths.w; if (len > control_rx_length) len = control_rx_length; if (wOffset < len) { pInformation->Ctrl_Info.Usb_wLength = len - wOffset; } else { pInformation->Ctrl_Info.Usb_wLength = 0; } return NULL; } if (control_rx_done && pInformation->USBwLengths.w <= wOffset + pInformation->Ctrl_Info.PacketSize) { *control_rx_done = USB_CONTROL_DONE; // this may be a bit premature, but it's our best try } if (control_rx_buffer == NULL) return NULL; else return (uint8*)control_rx_buffer + wOffset; } void usb_generic_control_rx_setup(volatile void* buffer, uint16 length, volatile uint8* done) { control_rx_buffer = buffer; control_rx_length = length; control_rx_done = done; pInformation->Ctrl_Info.CopyData = control_data_rx; pInformation->Ctrl_Info.Usb_wOffset = 0; control_data_rx(0); } void usb_generic_control_descriptor_tx(ONE_DESCRIPTOR* d) { usb_generic_control_tx_setup(d->Descriptor, d->Descriptor_Size, NULL); } static RESULT usbDataSetup(uint8 request) { if ((Type_Recipient & REQUEST_RECIPIENT) == INTERFACE_RECIPIENT) { uint8 interface = pInformation->USBwIndex0; for (unsigned i = 0 ; i < numParts ; i++) { USBCompositePart* p = parts[i]; if (p->usbDataSetup && p->startInterface <= interface && interface < p->startInterface + p->numInterfaces) { // uint8 request, uint8 interface, uint8 requestType, uint8 wValue0, uint8 wValue1, uint16 wIndex, uint16 wLength return parts[i]->usbDataSetup(request, interface - p->startInterface, pInformation->USBbmRequestType, pInformation->USBwValue0, pInformation->USBwValue1, pInformation->USBwIndex, pInformation->USBwLength); } } } return USB_UNSUPPORT; } static RESULT usbNoDataSetup(uint8 request) { if ((Type_Recipient & REQUEST_RECIPIENT) == INTERFACE_RECIPIENT) { uint8 interface = pInformation->USBwIndex0; for (unsigned i = 0 ; i < numParts ; i++) { USBCompositePart* p = parts[i]; // uint8 request, uint8 interface, uint8 requestType, uint8 wValue0, uint8 wValue1, uint16 wIndex, uint16 wLength if (p->usbNoDataSetup && p->startInterface <= interface && interface < p->startInterface + p->numInterfaces) return parts[i]->usbNoDataSetup(request, interface - p->startInterface, pInformation->USBbmRequestType, pInformation->USBwValue0, pInformation->USBwValue1, pInformation->USBwIndex); } } return USB_UNSUPPORT; } static void usbSetConfiguration(void) { if (pInformation->Current_Configuration != 0) { USBLIB->state = USB_CONFIGURED; } for (unsigned i = 0 ; i < numParts ; i++) { if (parts[i]->usbSetConfiguration != NULL) parts[i]->usbSetConfiguration(); } } static void usbClearFeature(void) { for (unsigned i = 0 ; i < numParts ; i++) { if (parts[i]->usbClearFeature != NULL) parts[i]->usbClearFeature(); } } static void usbSetDeviceAddress(void) { USBLIB->state = USB_ADDRESSED; } static uint8* usbGetDeviceDescriptor(uint16 length) { return Standard_GetDescriptorData(length, &Device_Descriptor); } static uint8* usbGetConfigDescriptor(uint16 length) { return Standard_GetDescriptorData(length, &Config_Descriptor); } static uint8* usbGetStringDescriptor(uint16 length) { uint8 wValue0 = pInformation->USBwValue0; if (wValue0 >= numStringDescriptors) { return NULL; } ONE_DESCRIPTOR* d = &String_Descriptor[wValue0]; if (d->Descriptor_Size != 0) { return Standard_GetDescriptorData(length, &String_Descriptor[wValue0]); } else { const char* s = (char*)d->Descriptor; uint32 i = 0; while(*s && i < USB_MAX_STRING_DESCRIPTOR_LENGTH) { string_descriptor_buffer.bString[i] = (uint8)*s; s++; i++; } string_descriptor_buffer.bLength = USB_DESCRIPTOR_STRING_LEN(i); generic_string_descriptor.Descriptor_Size = string_descriptor_buffer.bLength; if (length > string_descriptor_buffer.bLength) length = string_descriptor_buffer.bLength; return Standard_GetDescriptorData(length, &generic_string_descriptor); } } static RESULT usbGetInterfaceSetting(uint8 interface, uint8 alt_setting) { if (alt_setting > 1) { return USB_UNSUPPORT; } else if (interface >= usbConfig.Config_Header.bNumInterfaces) { return USB_UNSUPPORT; } return USB_SUCCESS; } void usb_copy_to_pma_ptr(volatile const uint8 *buf, uint16 len, uint32* dst) { uint16 n = len >> 1; uint16 i; for (i = 0; i < n; i++) { *(uint16*)dst = (uint16)(*buf) | *(buf + 1) << 8; buf += 2; dst++; } if (len & 1) { *dst = *buf; } } void usb_copy_from_pma_ptr(volatile uint8 *buf, uint16 len, uint32* src) { uint16 *dst = (uint16*)buf; uint16 n = len >> 1; uint16 i; for (i = 0; i < n; i++) { *dst++ = *src++; } if (len & 1) { *dst = *src & 0xFF; } } // return bytes read uint32 usb_generic_read_to_circular_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 circularBufferSize, volatile uint32* headP) { uint32 head = *headP; uint32 ep_rx_size = usb_get_ep_rx_count(ep->address); /* This copy won't overwrite unread bytes as long as there is * enough room in the USB Rx buffer for next packet */ volatile uint32 *src = ep->pma; for (uint32 i = 0; i < ep_rx_size; i++) { uint16 tmp = *src++; buf[head] = (uint8)tmp; head = (head + 1) % circularBufferSize; i++; if (i >= ep_rx_size) { break; } buf[head] = (uint8)(tmp>>8); head = (head + 1) % circularBufferSize; } *headP = head; return ep_rx_size; } // returns number of bytes read // buf should be uint16-aligned uint32 usb_generic_read_to_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 bufferSize) { uint32 ep_rx_size = usb_get_ep_rx_count(ep->address); if (ep_rx_size > bufferSize) ep_rx_size = bufferSize; usb_copy_from_pma_ptr(buf, ep_rx_size, ep->pma); return ep_rx_size; } uint32 usb_generic_send_from_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 amount) { if (amount > ep->pmaSize) amount = ep->pmaSize; usb_copy_to_pma_ptr(buf, amount, ep->pma); usb_set_ep_tx_count(ep->address, amount); usb_generic_enable_tx(ep); return amount; } // transmitting = 1 when transmitting, 0 when done but not flushed, negative when done and flushed uint32 usb_generic_send_from_circular_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 circularBufferSize, uint32 head, volatile uint32* tailP, volatile int8* transmittingP) { uint32 tail = *tailP; int32 amount = (head - tail) % circularBufferSize; if (amount < 0) { // wish we could count on % returning a non-negative answer amount += circularBufferSize; } if (amount==0) { if (*transmittingP <= 0) { *transmittingP = -1; return 0; // it was already flushed, keep Tx endpoint disabled } *transmittingP = 0; goto flush; // no more data to send } *transmittingP = 1; if (amount > ep->pmaSize) { amount = ep->pmaSize; } // copy the bytes from USB Tx buffer to PMA buffer uint32 *dst = ep->pma; for (int32 i = 0; i < amount; i++) { uint16 low = buf[tail]; tail = (tail + 1) % circularBufferSize; i++; if (i >= amount) { *dst = low; break; } *dst++ = ((uint16)buf[tail] << 8) | low; tail = (tail + 1) % circularBufferSize; } *tailP = tail; /* store volatile variable */ flush: // enable Tx endpoint usb_set_ep_tx_count(ep->address, amount); usb_generic_enable_tx(ep); return amount; } uint32 usb_generic_send_from_circular_buffer_double_buffered(USBEndpointInfo* ep, volatile uint8* buf, uint32 circularBufferSize, uint32 amount, volatile uint32* tailP) { uint32 tail = *tailP; /* load volatile variable */ uint32 dtog_tx = usb_get_ep_dtog_tx(ep->address); /* copy the bytes from USB Tx buffer to PMA buffer */ uint32 *dst; if (dtog_tx) dst = PMA_PTR_BUF1(ep); else dst = PMA_PTR_BUF0(ep); if (amount > ep->pmaSize / 2) amount = ep->pmaSize / 2; for (uint32 i = 0; i < amount; i++) { uint16 low = buf[tail]; tail = (tail + 1) % circularBufferSize; i++; if (i >= amount) { *dst = low; break; } *dst++ = ((uint16)buf[tail] << 8) | low; tail = (tail + 1) % circularBufferSize; } *tailP = tail; /* store volatile variable */ if (dtog_tx) usb_set_ep_tx_buf1_count(ep->address, amount); else usb_set_ep_tx_buf0_count(ep->address, amount); return amount; } uint16_t usb_generic_roundUpToPowerOf2(uint16_t x) { uint16_t xx; for (xx = 1 ; xx < x && xx != 0; xx *= 2) ; if (xx == 0) return x; else return xx; } <file_sep>/usb_scsi.c #include "usb_mass.h" #include "usb_mass_mal.h" #include "usb_mass_internal.h" #include "usb_scsi.h" #include <libmaple/usb.h> #include <libmaple/delay.h> /* Private headers */ #include "usb_lib_globals.h" #include "usb_reg_map.h" #include "usb_regs.h" /* usb_lib headers */ #include "usb_type.h" #include "usb_core.h" #include "usb_def.h" #define SCSI_READ_FORMAT_CAPACITY_DATA_LEN 0x0C #define SCSI_READ_FORMAT_CAPACITY10_DATA_LEN 0x08 #define SCSI_MODE_SENSE6_DATA_LEN 0x04 #define SCSI_MODE_SENSE10_DATA_LEN 0x08 #define SCSI_TXFR_IDLE 0 #define SCSI_TXFR_ONGOING 1 extern uint32_t usb_mass_sil_write(uint8_t* pBufferPointer, uint32_t wBufferSize); /* See usb_scsi_data.c */ extern uint8_t SCSI_page00InquiryData[]; extern uint8_t SCSI_standardInquiryData[]; extern uint8_t SCSI_standardInquiryData2[]; extern uint8_t SCSI_senseData[]; extern uint8_t SCSI_modeSense6Data[]; extern uint8_t SCSI_modeSense10Data[]; extern uint8_t SCSI_readFormatCapacityData[]; extern uint8_t SCSI_readFormatCapacity10Data[]; uint32_t SCSI_lba; uint32_t SCSI_blkLen; uint8_t SCSI_transferState = SCSI_TXFR_IDLE; uint32_t SCSI_blockReadCount = 0; uint32_t SCSI_blockOffset; uint32_t SCSI_counter = 0; uint8_t SCSI_dataBuffer[512]; /* 512 bytes (SDCard block size) */ uint8_t scsi_address_management(uint8_t lun, uint8_t cmd, uint32_t lba, uint32_t blockNbr); void scsi_read_memory(uint8_t lun, uint32_t memoryOffset, uint32_t transferLength); void scsi_write_memory(uint8_t lun, uint32_t memoryOffset, uint32_t transferLength); void scsi_inquiry_cmd(uint8_t lun) { uint8_t* inquiryData; uint16_t inquiryDataLength; if (usb_mass_CBW.CB[1] & 0x01) /*Evpd is set*/ { inquiryData = SCSI_page00InquiryData; inquiryDataLength = 5; } else { if (lun == 0) { inquiryData = SCSI_standardInquiryData; } else { inquiryData = SCSI_standardInquiryData2; } if (usb_mass_CBW.CB[4] <= SCSI_STANDARD_INQUIRY_DATA_LEN) { inquiryDataLength = usb_mass_CBW.CB[4]; } else { inquiryDataLength = SCSI_STANDARD_INQUIRY_DATA_LEN; } } usb_mass_transfer_data_request(inquiryData, inquiryDataLength); } void scsi_request_sense_cmd(uint8_t lun) { (void)lun; uint8_t requestSenseDataLength; if (usb_mass_CBW.CB[4] <= SCSI_REQUEST_SENSE_DATA_LEN) { requestSenseDataLength = usb_mass_CBW.CB[4]; } else { requestSenseDataLength = SCSI_REQUEST_SENSE_DATA_LEN; } usb_mass_transfer_data_request(SCSI_senseData, requestSenseDataLength); } void scsi_start_stop_unit_cmd(uint8_t lun) { (void)lun; usb_mass_bot_set_csw(BOT_CSW_CMD_PASSED, BOT_SEND_CSW_ENABLE); } void scsi_mode_sense6_cmd(uint8_t lun) { (void)lun; usb_mass_transfer_data_request(SCSI_modeSense6Data, SCSI_MODE_SENSE6_DATA_LEN); } void scsi_mode_sense10_cmd(uint8_t lun) { (void)lun; usb_mass_transfer_data_request(SCSI_modeSense10Data, SCSI_MODE_SENSE10_DATA_LEN); } void scsi_read_format_capacity_cmd(uint8_t lun) { if (usb_mass_mal_get_status(lun)) { scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_NOT_READY, SCSI_MEDIUM_NOT_PRESENT); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_ENABLE); usb_mass_bot_abort(BOT_DIR_IN); return; } SCSI_readFormatCapacityData[4] = (uint8_t) (usb_mass_drives[lun].blockCount >> 24); SCSI_readFormatCapacityData[5] = (uint8_t) (usb_mass_drives[lun].blockCount >> 16); SCSI_readFormatCapacityData[6] = (uint8_t) (usb_mass_drives[lun].blockCount >> 8); SCSI_readFormatCapacityData[7] = (uint8_t) (usb_mass_drives[lun].blockCount); SCSI_readFormatCapacityData[9] = (uint8_t) (SCSI_BLOCK_SIZE >> 16); SCSI_readFormatCapacityData[10] = (uint8_t) (SCSI_BLOCK_SIZE >> 8); SCSI_readFormatCapacityData[11] = (uint8_t) (SCSI_BLOCK_SIZE); usb_mass_transfer_data_request(SCSI_readFormatCapacityData, SCSI_READ_FORMAT_CAPACITY_DATA_LEN); } void scsi_read_capacity10_cmd(uint8_t lun) { if (usb_mass_mal_get_status(lun)) { scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_NOT_READY, SCSI_MEDIUM_NOT_PRESENT); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_ENABLE); usb_mass_bot_abort(BOT_DIR_IN); return; } SCSI_readFormatCapacity10Data[0] = (uint8_t) ((usb_mass_drives[lun].blockCount - 1) >> 24); SCSI_readFormatCapacity10Data[1] = (uint8_t) ((usb_mass_drives[lun].blockCount - 1) >> 16); SCSI_readFormatCapacity10Data[2] = (uint8_t) ((usb_mass_drives[lun].blockCount - 1) >> 8); SCSI_readFormatCapacity10Data[3] = (uint8_t) (usb_mass_drives[lun].blockCount - 1); SCSI_readFormatCapacity10Data[4] = (uint8_t) (SCSI_BLOCK_SIZE >> 24); SCSI_readFormatCapacity10Data[5] = (uint8_t) (SCSI_BLOCK_SIZE >> 16); SCSI_readFormatCapacity10Data[6] = (uint8_t) (SCSI_BLOCK_SIZE >> 8); SCSI_readFormatCapacity10Data[7] = (uint8_t) (SCSI_BLOCK_SIZE); usb_mass_transfer_data_request(SCSI_readFormatCapacity10Data, SCSI_READ_FORMAT_CAPACITY10_DATA_LEN); } void scsi_read10_cmd(uint8_t lun, uint32_t lba, uint32_t blockNbr) { if (usb_mass_botState == BOT_STATE_IDLE) { if (!(scsi_address_management(usb_mass_CBW.bLUN, SCSI_READ10, lba, blockNbr))) /*address out of range*/ { return; } if ((usb_mass_CBW.bmFlags & 0x80) != 0) { usb_mass_botState = BOT_STATE_DATA_IN; scsi_read_memory(lun, lba, blockNbr); } else { usb_mass_bot_abort(BOT_DIR_BOTH); scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_ILLEGAL_REQUEST, SCSI_INVALID_FIELED_IN_COMMAND); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_ENABLE); } return; } else if (usb_mass_botState == BOT_STATE_DATA_IN) { scsi_read_memory(lun, lba, blockNbr); } } void scsi_write10_cmd(uint8_t lun, uint32_t lba, uint32_t blockNbr) { if (usb_mass_botState == BOT_STATE_IDLE) { if (!(scsi_address_management(usb_mass_CBW.bLUN, SCSI_WRITE10, lba, blockNbr)))/*address out of range*/ { return; } if ((usb_mass_CBW.bmFlags & 0x80) == 0) { usb_mass_botState = BOT_STATE_DATA_OUT; usb_generic_enable_rx(USB_MASS_RX_ENDPOINT_INFO); } else { usb_mass_bot_abort(BOT_DIR_IN); scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_ILLEGAL_REQUEST, SCSI_INVALID_FIELED_IN_COMMAND); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_DISABLE); } return; } else if (usb_mass_botState == BOT_STATE_DATA_OUT) { scsi_write_memory(lun, lba, blockNbr); } } void scsi_test_unit_ready_cmd(uint8_t lun) { if (usb_mass_mal_get_status(lun)) { scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_NOT_READY, SCSI_MEDIUM_NOT_PRESENT); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_ENABLE); usb_mass_bot_abort(BOT_DIR_IN); return; } else { usb_mass_bot_set_csw(BOT_CSW_CMD_PASSED, BOT_SEND_CSW_ENABLE); } } void scsi_verify10_cmd(uint8_t lun) { (void)lun; if ((usb_mass_CBW.dDataLength == 0) && !(usb_mass_CBW.CB[1] & SCSI_BLKVFY))/* BLKVFY not set*/ { usb_mass_bot_set_csw(BOT_CSW_CMD_PASSED, BOT_SEND_CSW_ENABLE); } else { usb_mass_bot_abort(BOT_DIR_BOTH); scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_ILLEGAL_REQUEST, SCSI_INVALID_FIELED_IN_COMMAND); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_DISABLE); } } void scsi_format_cmd(uint8_t lun) { if (usb_mass_mal_get_status(lun)) { scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_NOT_READY, SCSI_MEDIUM_NOT_PRESENT); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_ENABLE); usb_mass_bot_abort(BOT_DIR_IN); return; } usb_mass_mal_format(lun); usb_mass_bot_set_csw(BOT_CSW_CMD_PASSED, BOT_SEND_CSW_ENABLE); } void scsi_set_sense_data(uint8_t lun, uint8_t sensKey, uint8_t asc) { (void)lun; SCSI_senseData[2] = sensKey; SCSI_senseData[12] = asc; } void scsi_invalid_cmd(uint8_t lun) { (void)lun; if (usb_mass_CBW.dDataLength == 0) { usb_mass_bot_abort(BOT_DIR_IN); } else { if ((usb_mass_CBW.bmFlags & 0x80) != 0) { usb_mass_bot_abort(BOT_DIR_IN); } else { usb_mass_bot_abort(BOT_DIR_BOTH); } } scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_ILLEGAL_REQUEST, SCSI_INVALID_COMMAND); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_DISABLE); } uint8_t scsi_address_management(uint8_t lun, uint8_t cmd, uint32_t lba, uint32_t blockNbr) { if ((lba + blockNbr) > usb_mass_drives[lun].blockCount) { if (cmd == SCSI_WRITE10) { usb_mass_bot_abort(BOT_DIR_BOTH); } usb_mass_bot_abort(BOT_DIR_IN); scsi_set_sense_data(lun, SCSI_ILLEGAL_REQUEST, SCSI_ADDRESS_OUT_OF_RANGE); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_DISABLE); return (FALSE); } if (usb_mass_CBW.dDataLength != blockNbr * SCSI_BLOCK_SIZE) { if (cmd == SCSI_WRITE10) { usb_mass_bot_abort(BOT_DIR_BOTH); } else { usb_mass_bot_abort(BOT_DIR_IN); } scsi_set_sense_data(usb_mass_CBW.bLUN, SCSI_ILLEGAL_REQUEST, SCSI_INVALID_FIELED_IN_COMMAND); usb_mass_bot_set_csw(BOT_CSW_CMD_FAILED, BOT_SEND_CSW_DISABLE); return (FALSE); } return (TRUE); } void scsi_read_memory(uint8_t lun, uint32_t startSector, uint32_t numSectors) { static uint32_t length; static uint64_t offset; if (SCSI_transferState == SCSI_TXFR_IDLE) { offset = (uint64_t)startSector * SCSI_BLOCK_SIZE; length = numSectors * SCSI_BLOCK_SIZE; SCSI_transferState = SCSI_TXFR_ONGOING; } if (SCSI_transferState == SCSI_TXFR_ONGOING) { if (SCSI_blockReadCount == 0) { usb_mass_mal_read_memory(lun, SCSI_dataBuffer, (uint32_t)(offset/SCSI_BLOCK_SIZE), 1); SCSI_blockReadCount = SCSI_BLOCK_SIZE - MAX_BULK_PACKET_SIZE; SCSI_blockOffset = MAX_BULK_PACKET_SIZE; usb_mass_sil_write(SCSI_dataBuffer, MAX_BULK_PACKET_SIZE); } else { SCSI_blockReadCount -= MAX_BULK_PACKET_SIZE; SCSI_blockOffset += MAX_BULK_PACKET_SIZE; usb_mass_sil_write(SCSI_dataBuffer + SCSI_blockOffset, MAX_BULK_PACKET_SIZE); } offset += MAX_BULK_PACKET_SIZE; length -= MAX_BULK_PACKET_SIZE; usb_mass_CSW.dDataResidue -= MAX_BULK_PACKET_SIZE; usb_mass_CSW.bStatus = BOT_CSW_CMD_PASSED; // TODO: Led_RW_ON(); } if (length == 0) { SCSI_blockReadCount = 0; SCSI_blockOffset = 0; offset = 0; usb_mass_botState = BOT_STATE_DATA_IN_LAST; SCSI_transferState = SCSI_TXFR_IDLE; // TODO: Led_RW_OFF(); } } void scsi_write_memory(uint8_t lun, uint32_t startSector, uint32_t numSectors) { static uint32_t length; static uint64_t offset; uint32_t idx; uint32_t temp = SCSI_counter + 64; if (SCSI_transferState == SCSI_TXFR_IDLE) { offset = (uint64_t)startSector * SCSI_BLOCK_SIZE; length = numSectors * SCSI_BLOCK_SIZE; SCSI_transferState = SCSI_TXFR_ONGOING; } if (SCSI_transferState == SCSI_TXFR_ONGOING) { for (idx = 0; SCSI_counter < temp; SCSI_counter++) { *((uint8_t *) SCSI_dataBuffer + SCSI_counter) = usb_mass_bulkDataBuff[idx++]; } offset += usb_mass_dataLength; length -= usb_mass_dataLength; if (!(length % SCSI_BLOCK_SIZE)) { SCSI_counter = 0; usb_mass_mal_write_memory(lun, SCSI_dataBuffer, (uint32_t)(offset/SCSI_BLOCK_SIZE) - 1, 1); } usb_mass_CSW.dDataResidue -= usb_mass_dataLength; usb_generic_enable_rx(USB_MASS_RX_ENDPOINT_INFO); /* enable the next transaction*/ // TODO // TODO: Led_RW_ON(); } if ((length == 0) || (usb_mass_botState == BOT_STATE_CSW_Send)) { SCSI_counter = 0; usb_mass_bot_set_csw(BOT_CSW_CMD_PASSED, BOT_SEND_CSW_ENABLE); SCSI_transferState = SCSI_TXFR_IDLE; // TODO: Led_RW_OFF(); } } <file_sep>/usb_generic.h #ifndef _USB_GENERIC_H #define _USB_GENERIC_H #include <libmaple/libmaple_types.h> typedef unsigned short u16; typedef unsigned char u8; #include <libmaple/usb.h> #include <libmaple/nvic.h> #include <libmaple/delay.h> #include "usb_lib_globals.h" #include "usb_reg_map.h" #define USB_CONTROL_DONE 1 #define PMA_MEMORY_SIZE 512 #define MAX_USB_DESCRIPTOR_DATA_SIZE 200 #define USB_MAX_STRING_DESCRIPTOR_LENGTH 32 #define USB_EP0_BUFFER_SIZE 0x40 #define USB_EP0_TX_BUFFER_ADDRESS 0x40 #define USB_EP0_RX_BUFFER_ADDRESS (USB_EP0_TX_BUFFER_ADDRESS+USB_EP0_BUFFER_SIZE) #ifdef __cplusplus extern "C" { #endif enum USB_ENDPOINT_TYPES { USB_GENERIC_ENDPOINT_TYPE_BULK = 0, USB_GENERIC_ENDPOINT_TYPE_CONTROL, USB_GENERIC_ENDPOINT_TYPE_ISO, USB_GENERIC_ENDPOINT_TYPE_INTERRUPT }; extern const usb_descriptor_string usb_generic_default_iManufacturer; extern const usb_descriptor_string usb_generic_default_iProduct; typedef struct USBEndpointInfo { void (*callback)(void); void* pma; uint16 pmaSize; uint8 address; uint8 type:2; uint8 doubleBuffer:1; uint8 tx:1; // 1 if TX, 0 if RX uint8 exclusive:1; // 1 if cannot use the same endpoint number for both rx and tx } USBEndpointInfo; typedef struct USBCompositePart { uint8 numInterfaces; uint8 numEndpoints; uint8 startInterface; uint16 descriptorSize; void (*getPartDescriptor)(uint8* out); void (*usbInit)(void); void (*usbReset)(void); void (*usbSetConfiguration)(void); void (*usbClearFeature)(void); void (*clear)(void); RESULT (*usbDataSetup)(uint8 request, uint8 interface, uint8 requestType, uint8 wValue0, uint8 wValue1, uint16 wIndex, uint16 wLength ); RESULT (*usbNoDataSetup)(uint8 request, uint8 interface, uint8 requestType, uint8 wValue0, uint8 wValue1, uint16 wIndex); USBEndpointInfo* endpoints; } USBCompositePart; struct usb_chunk { uint32 dataLength; const uint8* data; struct usb_chunk* next; } __packed; uint32 usb_generic_chunks_length(struct usb_chunk* chunk); static inline void usb_generic_enable_rx(USBEndpointInfo* ep) { usb_set_ep_rx_stat(ep->address, USB_EP_STAT_RX_VALID); } static inline void usb_generic_enable_tx(USBEndpointInfo* ep) { usb_set_ep_tx_stat(ep->address, USB_EP_STAT_TX_VALID); } static inline void usb_generic_stall_rx(USBEndpointInfo* ep) { usb_set_ep_rx_stat(ep->address, USB_EP_STAT_RX_STALL); } static inline void usb_generic_stall_tx(USBEndpointInfo* ep) { usb_set_ep_tx_stat(ep->address, USB_EP_STAT_TX_STALL); } static inline void usb_generic_disable_rx(USBEndpointInfo* ep) { usb_set_ep_rx_stat(ep->address, USB_EP_STAT_RX_DISABLED); } static inline void usb_generic_pause_rx(USBEndpointInfo* ep) { usb_set_ep_rx_stat(ep->address, USB_EP_STAT_RX_NAK); } static inline void usb_generic_disable_tx(USBEndpointInfo* ep) { usb_set_ep_tx_stat(ep->address, USB_EP_STAT_TX_DISABLED); } static inline void usb_generic_enable_rx_ep0(void) { usb_set_ep_rx_stat(USB_EP0, USB_EP_STAT_RX_VALID); } static inline void usb_generic_pause_rx_ep0(void) { usb_set_ep_rx_stat(USB_EP0, USB_EP_STAT_RX_NAK); } static inline void usb_generic_disable_interrupts_ep0(void) { nvic_irq_disable(NVIC_USB_LP_CAN_RX0); } static inline void usb_generic_enable_interrupts_ep0(void) { nvic_irq_enable(NVIC_USB_LP_CAN_RX0); } static inline void usb_generic_prepare_tx(USBEndpointInfo* ep, uint32 length) { usb_set_ep_tx_count(ep->address, length); } static inline void usb_generic_set_tx(USBEndpointInfo* ep, uint32 length) { usb_set_ep_tx_count(ep->address, length); usb_generic_enable_tx(ep); } // for double buffering #define PMA_PTR_BUF1(ep) ((void*)((uint8*)(ep)->pma+(ep)->pmaSize)) #define PMA_PTR_BUF0(ep) ((ep)->pma) uint32 usb_generic_send_from_circular_buffer_double_buffered(USBEndpointInfo* ep, volatile uint8* buf, uint32 circularBufferSize, uint32 amount, volatile uint32* tailP); void usb_generic_set_disconnect_delay(uint32 delay); void usb_generic_set_info(uint16 idVendor, uint16 idProduct, const char* iManufacturer, const char* iProduct, const char* iSerialNumber); uint8 usb_generic_set_parts(USBCompositePart** _parts, unsigned _numParts); void usb_generic_control_rx_setup(volatile void* buffer, uint16 length, volatile uint8* done); void usb_generic_control_tx_setup(volatile void* buffer, uint16 length, volatile uint8* done); void usb_generic_control_tx_chunk_setup(struct usb_chunk* chunk); void usb_generic_control_descriptor_tx(ONE_DESCRIPTOR* d); void usb_generic_disable(void); void usb_generic_enable(void); void usb_copy_from_pma_ptr(volatile uint8 *buf, uint16 len, uint32* pma); void usb_copy_to_pma_ptr(volatile const uint8 *buf, uint16 len, uint32* pma); uint32 usb_generic_read_to_circular_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 bufferSize, volatile uint32* headP); #define USB_GENERIC_UNLIMITED_BUFFER 0xFFFFFFFFul uint32 usb_generic_read_to_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 bufferSize); uint32 usb_generic_send_from_circular_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 bufferSize, uint32 head, volatile uint32* tailP, volatile int8* transmittingP); uint32 usb_generic_send_from_buffer(USBEndpointInfo* ep, volatile uint8* buf, uint32 amount); uint16_t usb_generic_roundUpToPowerOf2(uint16_t x); #ifdef __cplusplus } #endif #endif <file_sep>/usb_hid.h /****************************************************************************** * The MIT License * * Copyright (c) 2011 LeafLabs LLC. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file libmaple/include/libmaple/usb_device.h * @brief USB Composite with CDC ACM and HID support * * IMPORTANT: this API is unstable, and may change without notice. */ #ifndef _USB_HID_H_ #define _USB_HID_H_ #include <libmaple/libmaple_types.h> #include <libmaple/usb.h> #include "usb_generic.h" #define MAX_HID_BUFFERS 8 #define HID_BUFFER_SIZE(n,reportID) ((n)+((reportID)!=0)) #define HID_BUFFER_ALLOCATE_SIZE(n,reportID) ((HID_BUFFER_SIZE((n),(reportID))+1)/2*2) #define HID_BUFFER_MODE_NO_WAIT 1 #define HID_BUFFER_MODE_OUTPUT 2 #define HID_BUFFER_EMPTY 0 #define HID_BUFFER_UNREAD USB_CONTROL_DONE #define HID_BUFFER_READ 2 extern USBCompositePart usbHIDPart; typedef struct HIDBuffer_t { volatile uint8_t* buffer; // use HID_BUFFER_ALLOCATE_SIZE() to calculate amount of memory to allocate uint16_t bufferSize; // this should match HID_BUFFER_SIZE uint8_t reportID; uint8_t mode; uint8_t state; // HID_BUFFER_EMPTY, etc. #ifdef __cplusplus inline HIDBuffer_t(volatile uint8_t* _buffer=NULL, uint16_t _bufferSize=0, uint8_t _reportID=0, uint8_t _mode=0) { reportID = _reportID; buffer = _buffer; bufferSize = _bufferSize; mode = _mode; } #endif } HIDBuffer_t; #ifdef __cplusplus extern "C" { #endif void usb_hid_set_report_descriptor(struct usb_chunk* chunks); void usb_hid_clear_buffers(uint8_t type); uint8_t usb_hid_add_buffer(uint8_t type, volatile HIDBuffer_t* buf); void usb_hid_set_buffers(uint8_t type, volatile HIDBuffer_t* featureBuffers, int count); uint16_t usb_hid_get_data(uint8_t type, uint8_t reportID, uint8_t* out, uint8_t poll); void usb_hid_set_feature(uint8_t reportID, uint8_t* data); void usb_hid_setTXEPSize(uint32_t size); uint32 usb_hid_get_pending(void); /* * HID Requests */ typedef enum _HID_REQUESTS { GET_REPORT = 1, GET_IDLE, GET_PROTOCOL, SET_REPORT = 9, SET_IDLE, SET_PROTOCOL } HID_REQUESTS; #define HID_REPORT_TYPE_INPUT 0x01 #define HID_REPORT_TYPE_OUTPUT 0x02 #define HID_REPORT_TYPE_FEATURE 0x03 /* * HID Descriptors, etc. */ #define HID_ENDPOINT_INT 1 #define HID_DESCRIPTOR_TYPE 0x21 #define REPORT_DESCRIPTOR 0x22 typedef struct { uint8_t len; // 9 uint8_t dtype; // 0x21 uint8_t versionL; // 0x101 uint8_t versionH; // 0x101 uint8_t country; uint8_t numDesc; uint8_t desctype; // 0x22 report uint8_t descLenL; uint8_t descLenH; } HIDDescriptor; #define USB_INTERFACE_CLASS_HID 0x03 #define USB_INTERFACE_SUBCLASS_HID 0x01 /* * HID interface */ uint32 usb_hid_tx(const uint8* buf, uint32 len); uint32 usb_hid_tx_mod(const uint8* buf, uint32 len); uint32 usb_hid_data_available(void); /* in RX buffer */ #ifdef __cplusplus } #endif #endif <file_sep>/scripts/send.py from pywinusb import hid from time import sleep SIZE=1 REPORT_ID=20 def sample_handler(data): print("Raw data: {0}".format(data)) device = hid.HidDeviceFilter(vendor_id = 0x1EAF, product_id = 0x0004).get_devices()[0] print(device) device.open() device.set_raw_data_handler(sample_handler) n = 0 while True: """ print("sending") out_report=device.find_output_reports()[0] buffer=[i for i in range(SIZE+1)] buffer[0]=REPORT_ID # report id buffer[-1] = n out_report.set_raw_data(buffer) if out_report.send(): n = (n+1)&0xFF """ sleep(0.5) #sleep(0.005) <file_sep>/branchlog.sh svn log https://github.com/arpruss/USBComposite_stm32f1/branches/abstracted <file_sep>/library.properties name=USBComposite for STM32F1 version=0.95 author=Various email=<EMAIL> sentence=USB HID / MIDI / mass storage / Audio library for STM32F1 paragraph=USB HID / MIDI / mass storage / Audio library for STM32F1 url=https://github.com/arpruss/USBHID_stm32f1 architectures=STM32F1 maintainer=<EMAIL> category=Communication
0d22741dff2d9fdc07aa6708af9362922ece9a24
[ "INI", "Python", "C", "C++", "Shell" ]
13
C++
203Electronics/USBComposite_stm32f1
cdcf01784309d09d6a704b2b76862f8cf45bbd56
e709cfea334b220cda80bda2948973692b2b827d
refs/heads/master
<file_sep>#!/usr/bin/env bash echo "" if ! [[ -x "$(command -v emacs)" ]]; then echo "emacs not found. Is it installed?" >&2 exit fi rm -rf ~/.emacs.d mkdir ~/.emacs.d ln -s ~/repos/editors/init.el ~/.emacs.d/init.el mkdir ~/.emacs.d/lisp echo "Install dependencies:" # C/C++ sudo apt install xclip ./emacs_pkgs.el echo "!!!!!!!!" echo "Remember to install One Dark Pro theme for vscode" echo "!!!!!!!!" rm ~/.config/Code/User/settings.json rm ~/.config/Code/User/keybindings.json mkdir -p ~/.config/Code/User/ ln -s ~/repos/editors/vscode_settings.json ~/.config/Code/User/settings.json ln -s ~/repos/editors/vscode_keybindings.json ~/.config/Code/User/keybindings.json <file_sep># Useful Bindings |Key|Function| |---|--------| |C-c m|compile (execute Makefile)| |C-c f|Auto-complete file path| |C-c c|Auto-complete code| |C-c h|helm command prefix| |C-c h o|helm-occur| |C-c h i|helm-semantic (File outline)| |C-c s|open sr-speedbar| |C-S-c C-S-c|mc/edit-lines| |C-q|mc/mark-next-like-this| |C-c C-q|mc/mark-all-like-this|
991a281b09936c11df6a8f30f84ebcbc9bcf5664
[ "Markdown", "Shell" ]
2
Shell
andre-richter/editors
9b071ac3fe87336a6c9454446567d29ad88919a8
eef58b36096357995616b25d99c0bcd07a4babf3
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { catchError, map, tap } from 'rxjs/operators'; import { KJUR } from 'jsrsasign'; import { environment } from '../../environments/environment'; import { Game } from '../_models/game'; import { User } from '../_models/user'; import { Comment } from '../_models/comment'; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); @Injectable() export class GameService { private apiUrl = environment.url; constructor( private http: HttpClient ) { } /** POST: create a new game */ makeGame (username: string, game_date: string, des: string, min_rank: number, loc_id: number): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/new-game`; const body = { locationID: loc_id, date_of_game: game_date, description: des, creator_username: username, minimum_rank: min_rank }; return this.http.post<Response>(url, body, {observe: 'response'}).pipe( tap(res => console.log(`added game w/ description=${des}`)) ); } /** POST: rsvp to the game */ rsvp (username: string, game_id: number): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/rsvp`; return this.http.post<Response>(url, { GameID : game_id, username : username }, {observe: 'response'}).pipe( tap(res => console.log(`added rsvp to game w/ if=${game_id}`)) ); } /** DELETE: delete rsvp to the game */ deleteRSVP (username: string, game_id: number): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/delete-rsvp/${username}/${game_id}`; return this.http.delete<any>(url).pipe( tap(res => console.log(`deleted rsvp to game w/ if=${game_id}`)) ); } /** GET: return array of all games */ getAllGames (): Observable<Game[]> { const url = `${this.apiUrl}/games`; return this.http.get<Game[]>(url).pipe( tap(res => console.log(`found all games`)) ); } /** GET: return array of all games user rsvp'd to */ getRSVPGames (username: string): Observable<Game[]> { const url = `${this.apiUrl}/rsvp/user/${username}`; return this.http.get<Game[]>(url).pipe( tap(res => console.log(`found games rsvp'd to`)) ); } /** GET: return array of all rsvps a game has */ getGameRSVPs (gameid: number): Observable<User[]> { const url = `${this.apiUrl}/rsvp/game/${gameid}`; return this.http.get<User[]>(url).pipe( tap(res => console.log(`found user rsvp'd to this game`)) ); } /** GET: return specific game */ getGame (game_id: number): Observable<Game> { const url = `${this.apiUrl}/game/${game_id}`; return this.http.get<Game>(url).pipe( tap(res => console.log(`found game with id=${game_id}`)) ); } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { GameService } from '../../_services/game.service'; import { ProfileService } from '../../_services/profile.service'; import { Game } from '../../_models/game'; @Component({ selector: 'app-games-list-page', templateUrl: './games-list-page.component.html', styleUrls: ['./games-list-page.component.scss'] }) export class GamesListPageComponent implements OnInit { allGamesActive: boolean = true; allGames: Game[] = []; attendingGames: Game[] = []; constructor( private router: Router, private gameService: GameService, private profileService: ProfileService ) { } ngOnInit() { this.getAllGames(); this.getAttendingGames(); } getAllGames() { this.gameService.getAllGames().subscribe( games => { this.allGames = games; }, err => { console.log("Error getting all games"); } ); } getAttendingGames() { var currentUser = this.profileService.getCurrentUser(); this.gameService.getRSVPGames(currentUser).subscribe( games => { this.attendingGames = games; }, err => { console.log("Error getting rsvp'd games"); } ); } openNewGamePage() { this.router.navigate(['/dashboard/gameSubmit']); } allGamesToggle(){ this.allGamesActive = true; } attendingGamesToggle(){ this.allGamesActive = false; } } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // update a profile $app->put('/profile-update/[{id}]', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM users WHERE username=:id"); $pdo->bindParam("id", $args["id"]); $pdo->execute(); $info = $pdo->fetch(); $first_name = $info['first_name']; $last_name = $info['last_name']; $email = $info['email']; $year = $info['year']; $pic_url = $infor['pic_url']; $data = json_decode(file_get_contents("php://input")); //$input = $request->getParsedBody(); if (!empty($data->first_name)) { $first_name = $data->first_name; } if (!empty($data->last_name)) { $last_name = $data->last_name; } if (!empty($data->email)) { $email = $data->email; } if (!empty($data->year)) { $year = $data->year; } if (!empty($data->pic_url)) { $pic_url = $data->pic_url; } $sql = "UPDATE users SET first_name=:fn, last_name=:ln, email=:em, year=:yr,last_updated=CURRENT_TIMESTAMP, pic_url=:pic WHERE username=:id"; $sth = $this->db->prepare($sql); $sth->bindParam("id", $args['id']); $sth->bindParam("fn", $first_name); $sth->bindParam("ln", $last_name); $sth->bindParam("em", $email); $sth->bindParam("yr", $year); $sth->bindParam("pic", $pic_url); $sth->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep># Hooplife SMU Fall 2017 DB/GUI Project ## Dev Environment Instructions for running the project locally ### Setup Install dependencies, build frontend project, and get project ready for the docker containers ``` npm install cd frontend ng build --prod cd ../ npm run setup ``` ### Docker Scripts These commands are to be run in the top level 'endlist' folder. Docker and docker-compose must be installed for this to work `npm run docker-start`: Starts the docker containers. The frontend can be accessed from http://localhost:80. The backend can be accessed from http://localhost:80/backend/public. `npm run docker-stop`: Stops the docker containers. `npm run docker-prod`: Starts the docker containers in production mode. The frontend is configured to be accessed from http://endlist.fun and the backend from http://api.endlist.fun. ### Testing `npm test`: Runs tests for both the fronend and backend. `npm run test-frontend`: Runs tests for the frontend using jest. `npm run test-backend`: Runs tests for the backend using phpunit. <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ProfileService } from '../../_services/profile.service'; import { User } from '../../_models/user'; import { Comment } from '../../_models/comment'; import { UserPublicComponent } from '../../components/user-public/user-public.component'; import { UserPrivateComponent } from '../../components/user-private/user-private.component' @Component({ selector: 'app-user-page', templateUrl: './user-page.component.html', styleUrls: ['./user-page.component.css'] }) export class UserPageComponent implements OnInit { isPublic: boolean; userFound: boolean = false; user: User; comments: Comment[]; constructor( private route: ActivatedRoute, private profileService: ProfileService ) { this.isPublic = true; } ngOnInit() { this.getUser(); this.getComments(); } getUser() { const username = this.route.snapshot.paramMap.get('username'); this.profileService.getUser(username).subscribe( user => { this.user = user; var currentUser = this.profileService.getCurrentUser(); this.isPublic = (username === currentUser) ? false : true; this.userFound = true; }, err => { this.user = new User(); } ); } getComments() { const username = this.route.snapshot.paramMap.get('username'); this.profileService.getComments("user", username).subscribe( comments => { this.comments = comments; }, err => { this.comments = []; } ); } } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; $app->delete('/location-delete/[{locationID}]', function (Request $request, Response $response, array $args) { $pdo = $this->db->prepare("DELETE FROM location WHERE locationID=:locationID"); $pdo->bindParam("locationID", $args["locationID"]); $pdo->execute(); // return $this->response->withJson($response->getStatusCode()); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { AuthService } from '../../_services/auth.service'; import { Login } from '../../_models/login'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { auth: Login = new Login(); username: string; constructor( private authService: AuthService, private router: Router, private snackBar: MatSnackBar ) { } ngOnInit() { } submit() { this.username = this.auth.username; this.authService.login(this.auth).subscribe( res => { this.checkAuth(res.status); }, err => { this.snackBar.open('Login failed, please try again', '', { duration: 5000 }); } ); } checkAuth(status) { if(status == 200) { localStorage.setItem('auth', this.authService.getJWT({user: this.username})); } else { this.snackBar.open('Login failed, please try again', '', { duration: 5000 }); return; } this.router.navigate(['/dashboard']); } } <file_sep><?php if (PHP_SAPI == 'cli-server') { // To help the built-in PHP dev server, check if the request was actually // for something which should probably be served as a static file $url = parse_url($_SERVER['REQUEST_URI']); $file = __DIR__ . $url['path']; if (is_file($file)) { return false; } } require __DIR__ . '/../vendor/autoload.php'; //session_start(); // Instantiate the app $settings = require __DIR__ . '/../src/settings.php'; $app = new \Slim\App($settings); // Set up dependencies require __DIR__ . '/../src/dependencies.php'; // Register middleware require __DIR__ . '/../src/middleware.php'; // Register routes ------------------------------------------------------------- // IMPORTANT: Require dynamic routes after static ones //require __DIR__ . '/../src/routes.php'; require __DIR__ . '/../src/login.php'; require __DIR__ . '/../src/registration.php'; require __DIR__ . '/../src/games.php'; require __DIR__ . '/../src/get_profile.php'; require __DIR__ . '/../src/game_detail.php'; require __DIR__ . '/../src/delete_game.php'; require __DIR__ . '/../src/post_location.php'; require __DIR__ . '/../src/get_location.php'; require __DIR__ . '/../src/rsvp.php'; require __DIR__ . '/../src/approve_admin.php'; require __DIR__ . '/../src/approve_location.php'; require __DIR__ . '/../src/pofile-update.php'; require __DIR__ . '/../src/stats-update.php'; require __DIR__ . '/../src/change_password.php'; require __DIR__ . '/../src/comments.php'; require __DIR__ . '/../src/location-update.php'; require __DIR__ . '/../src/delete_location.php'; require __DIR__ . '/../src/email_validation.php'; // Add dynamic ones below this line --------------------------------------------i // Run app $app->run(); <file_sep>import { InMemoryDbService } from 'angular-in-memory-web-api'; export class InMemoryDataService implements InMemoryDbService { createDb() { const users = [ { firstName: 'Jenn', lastName: 'Le', username: 'Thakugan', email: '<EMAIL>', password: '<PASSWORD>', dateCreated: new Date(), comments: [], rating: 5, year: 'Junior', gamesPlayed: 0, wins: 0, losses: 0 } ]; const login = [ ] const locations = [ { name: '<NAME>', photoName: 'temp.jpg', address: 'SMU', description: 'Only midly disgusting', comments: [], rating: 3 } ] return {users, login, locations}; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { LocationService } from '../../_services/location.service'; import { ProfileService } from '../../_services/profile.service'; import { Location } from '../../_models/location'; import { Comment } from '../../_models/comment'; @Component({ selector: 'app-location-details-page', templateUrl: './location-details-page.component.html', styleUrls: ['./location-details-page.component.scss'] }) export class LocationDetailsPageComponent implements OnInit { place: Location; comments: Comment[]; displayComments: boolean = true; hasRated: boolean; hasCommented: boolean; newComment: Comment = new Comment(); constructor( private route: ActivatedRoute, private router: Router, private locationService: LocationService, private profileService: ProfileService, private snackBar: MatSnackBar ) { } ngOnInit() { this.getLocation(); this.getComments(); } getLocation() { const loc = +this.route.snapshot.paramMap.get('locID'); this.locationService.getLocation(loc).subscribe( location => { this.place = location[0]; }, err => { alert("something went wrong"); } ); } getComments() { const loc = +this.route.snapshot.paramMap.get('locID'); this.profileService.getComments("location", loc).subscribe( comments => { this.comments = comments; }, err => { this.comments = []; } ); } addComment(){ const loc = this.route.snapshot.paramMap.get('locID'); const currentUser = this.profileService.getCurrentUser(); this.profileService.createComment(currentUser, this.newComment.Comment, 'location', loc, this.newComment.rating).subscribe( res => { this.router.navigate(['/dashboard/location/' + loc]) }, err => { this.snackBar.open('Comment submition failed, please try again.', '', { duration: 5000 }); } ); } onRated(num: number){ this.newComment.rating = num; this.hasRated = true; } } <file_sep><?php header('Content-type: application/json'); use \Firebase\JWT\JWT; use Slim\Http\Request; use Slim\Http\Response; //session set up with login template implimented /** $app->get('/login',function (Request $request, Response $response, array $args) { if(session_id() == ''){ session_start(); // Starting Session } //check if there is a session with the particular user if(isset($_session['username'])){ return $response->withRedirect('/'); } }); **/ //in the begingin we were planing on using user sessions but we changed to using JWT and the front end handels that part //login as post for protecting credentials $app->post('/login', function (Request $request, Response $response, array $args){ //if(session_id() == ''){ // session_start(); // Starting Session //} if ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $username = $data->username; $password = $<PASSWORD>-><PASSWORD>; } $pdo = $this->db; $hash_password= md5($password); $stmt = $pdo->prepare('SELECT * FROM users WHERE username=:username AND password=:password'); $stmt->bindParam("username", $username); $stmt->bindParam("password", $hash_password); $stmt->execute(); $row = $stmt->rowCount(); if ($row < 1) { return $response->withStatus(404); } else { //session_start(); $payload = [ 'username' => $username, ]; $token = JWT::encode($payload, $_SERVER['SESSION_PASS']); $json = json_encode(array( "jwt" => $token )); $stmt = $pdo->prepare('UPDATE users SET last_login=CURRENT_TIMESTAMP WHERE username=:username'); $stmt->bindParam("username", $username); $stmt->execute(); return $response->withJson($json, 200); //return $response->withStatus(200); } }); <file_sep>#!/usr/bin/env bash docker-compose -f $1 stop <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // update a location $app->put('/location-update/[{id}]', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM location WHERE locationID=:id"); $pdo->bindParam("id", $args["id"]); $pdo->execute(); $info = $pdo->fetch(); $picture_url = $info['picture_url']; $address = $info['address']; $des = $info['description']; $rating = $info['rating']; $data = json_decode(file_get_contents("php://input")); //$input = $request->getParsedBody(); if (!empty($data->picture_url)) { $picture_url = $data->picture_url; } if (!empty($data->address)) { $address = $data->address; } if (!empty($data->des)) { $des = $data->des; } if (!empty($data->rating)) { $rating = $data->rating; } $sql = "UPDATE location SET picture_url=:pic, address=:address, description=:des, rating=:rating WHERE locationID=:id"; $sth = $this->db->prepare($sql); $sth->bindParam("id", $args['id']); $sth->bindParam("pic", $picture_url); $sth->bindParam("address", $address); $sth->bindParam("des", $des); $sth->bindParam("rating", $rating); $sth->execute(); return $response->withStatus(200); }); <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { catchError, map, tap } from 'rxjs/operators'; import { KJUR } from 'jsrsasign'; import { environment } from '../../environments/environment'; import { Location } from '../_models/location'; import { Comment } from '../_models/comment'; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); @Injectable() export class LocationService { private apiUrl = environment.url; constructor( private http: HttpClient ) { } /** POST: request a new location */ requestLoc (username: string, address: string, description: string, pic?: string): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/new-location`; const body = pic ? { creator_username: username, address: address, descriptions: description, picture_url: pic } : { creator_username: username, address: address, descriptions: description }; return this.http.post<Response>(url, body, {observe: 'response'}).pipe( tap(res => console.log(`added location w/ description=${description}`)) ); } /** GET: return array of all approved locations */ getApprovedLocations (): Observable<Location[]> { const url = `${this.apiUrl}/approved-location`; return this.http.get<Location[]>(url).pipe( tap(res => console.log(`found games`)) ); } /** GET: return array of all approved locations */ getUnapprovedLocations (): Observable<Location[]> { const url = `${this.apiUrl}/non-approved-location`; return this.http.get<Location[]>(url).pipe( tap(res => console.log(`found games`)) ); } /** GET: return specific location */ getLocation (id: number): Observable<Location> { const url = `${this.apiUrl}/location/${id}`; return this.http.get<Location>(url).pipe( tap(res => console.log(`found location with id=${id}`)) ); } approveLocation(admin: string, loc: number): Observable<Location> { const url = `${this.apiUrl}/locapprove/${admin}/${loc}`; return this.http.get<Location>(url).pipe( tap(res => console.log(`found games`)) ); } denyLocation(loc: number): Observable<Location> { const url = `${this.apiUrl}/location-delete/${loc}`; return this.http.delete<Location>(url).pipe( tap(res => console.log(`found games`)) ); } } <file_sep><?php use Slim\Http\Request; use Slim\Http\Response; $app->post('/new-location', function (Request $request, Response $response, array $args) { $pdo = $this->db; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $creator_username = $data->creator_username; $picture_url = $data->picture_url; $des = $data->descriptions; $address = $data->address; } if( !isset($creator_username) || !isset($address) || !isset($des) || empty($creator_username) || empty($des) || empty($address)) { //error message forbidden return $response->withStatus(403); } if (empty($picture_url)){ $picture_url ="null"; } // Check if the user exists $stmt = $pdo->prepare('SELECT * FROM users WHERE username=:creator_username'); $stmt->bindParam("creator_username", $creator_username); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if($row== 0) { //error message bad request return $response->withStatus(400); } //Check if the address already exsists $stmt = $pdo->prepare('SELECT * FROM location WHERE address=:address'); $stmt->bindParam("address", $address); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if($row) { //error message bad reqest return $response->withStatus(400); } //primary key locationid $stmt = $pdo->prepare( "INSERT INTO location ( picture_url, address, description, date_created, creator_username, approved) VALUES(:picture_url, :address, :des, CURRENT_TIMESTAMP, :creator_username, 0)" ); // Add the entry to the array once all the fields have been verified $stmt->bindParam("picture_url", $picture_url); $stmt->bindParam("address", $address); $stmt->bindParam("des", $des); $stmt->bindParam("creator_username", $creator_username); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep>#!/usr/bin/env bash docker-compose -f $1 build docker-compose -f $1 up -d --force-recreate <file_sep><?php use Slim\Http\Request; use Slim\Http\Response; //user regisration //tested and complete //email verification not fully functional //some of the codes for registration were implimented partly based another php implementation of a registration //this helped me make sure evverything was working properly and that I could cover the edge cases $app->post('/registration', function ($request,$response, array $args) { $pdo = $this->db; //$json = $request->getBody(); //$data = json_decode($json); //$username = $_POST['username']; //$first_name = $_POST['first_name']; // $last_name = $_POST['last_name']; //$email = $_POST['email']; //$plain_password = $_POST['password']; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $username = $data->username; $first_name = $data->first_name; $last_name = $data->last_name; $email = $data->email; $plain_password = $<PASSWORD>-><PASSWORD>; $year = $data->year; } //when building html form, using ajax or js to prevent non-value params // checkinig for empty fields if( !isset($username) || !isset($email)|| !isset($last_name) || !isset($year) || !isset($first_name) || !isset($plain_password) || empty($username) || empty($year) || empty($first_name) || empty($last_name) || empty($email) || empty($plain_password)) { //error message forbidden return $response->withStatus(403); } // username duplicaiton change $stmt = $pdo->prepare('SELECT * FROM users WHERE username=:username'); $stmt->bindParam("username", $username); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if($row) { //error message bad request return $response->withStatus(400); } //email duplication check $stmt = $pdo->prepare('SELECT * FROM users WHERE email=:email'); $stmt->bindParam("email", $email); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if($row) { //error message bad reqest return $response->withStatus(400); } // md5 used to hash the passwords $password = md5($plain_password); //primary key userid //forigne key groupid $stmt = $pdo->prepare( "INSERT INTO users ( username, first_name , last_name , email , password, groupid, verified, date_joined , last_updated , num_of_games_played, isAdmin, wins, losses, year) VALUES(:username, :first_name, :last_name, :email, :password, 2, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 0, 0, 0, 0, :year)" ); $stmt->bindParam("username", $username); $stmt->bindParam("first_name", $first_name); $stmt->bindParam("last_name", $last_name); $stmt->bindParam("email", $email); $stmt->bindParam("password", $<PASSWORD>); $stmt->bindParam("year", $year); $stmt->execute(); $pdo = $this->db->prepare("SELECT * FROM users WHERE username=:username"); $pdo->bindParam("username", $username); $pdo->execute(); $info = $pdo->fetch(); $uid = $info['uid']; // email_verification($email, $last_name, $first_name, $username, $uid); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { LocationService } from '../../_services/location.service'; import { Location } from '../../_models/location'; import { LocationBrowserComponent } from '../../components/location-browser/location-browser.component'; @Component({ selector: 'app-location-browse-page', templateUrl: './location-browse-page.component.html', styleUrls: ['./location-browse-page.component.scss'] }) export class LocationBrowsePageComponent implements OnInit { loadPage: boolean = true; locations: Location[]; constructor( private locationService: LocationService ) { } ngOnInit() { this.getApprovedLocations(); } getApprovedLocations() { this.locationService.getApprovedLocations().subscribe( locations => { this.locations = locations; } ); } } <file_sep><div class="games-list mt-4"> <button type="button" class="btn btn-info" [disabled]="allGamesActive" (click)="allGamesToggle()">All Games</button> <button type="button" class="btn btn-info" [disabled]="!allGamesActive" (click)="attendingGamesToggle()">Games I'm Attending</button> <button type="button" class="btn btn-outline-dark float-right" (click)="openNewGamePage()">NEW GAME</button> <hr /> <div *ngIf="allGamesActive" class="clearfix"> <div *ngFor="let game of allGames"> <div class="card w-100"> <div class="card-body"> <a [routerLink]="'/dashboard/game/' + game.GameID"><h4>{{game.description}}</h4></a> <p>Organizer: <a [routerLink]="'/dashboard/user/' + game.creator_username">{{game.creator_username}}</a></p> <!-- <p>{{game.location.address}}</p> --> <p>Minimum Rating: {{game.minimum_rank ? game.minimum_rank : 'N/A'}}</p> </div> </div> </div> </div> <div *ngIf="!allGamesActive"> <div *ngFor="let game of attendingGames"> <div class="card w-100"> <div class="card-body"> <a [routerLink]="'/dashboard/game/' + game.GameID"><h4>{{game.description}}</h4></a> <p>Organizer: <a [routerLink]="'/dashboard/user/' + game.creator_username">{{game.creator_username}}</a></p> <!-- <p>{{game.location.address}}</p> --> <p>Minimum Rating: {{game.minimum_rank ? game.minimum_rank : 'N/A'}}</p> </div> </div> </div> </div> <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { SharedModule } from '../../_modules/shared/shared.module'; import { UserPageComponent } from '../../pages/user-page/user-page.component'; import { UserPrivateComponent } from '../../components/user-private/user-private.component'; import { UserPublicComponent } from '../../components/user-public/user-public.component'; import { ApproveLocationsComponent } from '../../components/approve-locations/approve-locations.component'; @NgModule({ declarations: [ UserPrivateComponent, UserPublicComponent, UserPageComponent, ApproveLocationsComponent ], imports: [ CommonModule, HttpClientModule, FormsModule, SharedModule ], providers: [ ] }) export class ProfileModule { } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; //show a specfic rsvp for a user $app->get('/rsvp/user/[{username}]', function(Request $request, Response $response, array $args){ // $pdo = $this->db->prepare("SELECT * FROM rsvp WHERE userid=:userid"); $pdo = $this->db->prepare("SELECT * FROM games natural join rsvp WHERE username = :username"); $pdo->bindParam("username", $args["username"]); $pdo->execute(); $rsvpGame = $pdo->fetchAll(); if (!$rsvpGame) { return $response->withStatus(404); } else { return $this->response->withJson($rsvpGame); } }); //show a specfic rsvp for a user $app->get('/rsvp/game/[{GameID}]', function(Request $request, Response $response, array $args){ // $pdo = $this->db->prepare("SELECT * FROM rsvp WHERE userid=:userid"); // $pdo = $this->db->prepare("SELECT * FROM games natural join rsvp // WHERE GameID = :GameID"); $pdo = $this->db->prepare("SELECT username FROM rsvp WHERE GameID=:GameID"); $pdo->bindParam("GameID", $args["GameID"]); $pdo->execute(); $rsvpGame = $pdo->fetchAll(); if (!$rsvpGame) { return $response->withStatus(404); } else { return $this->response->withJson($rsvpGame); } }); //deletes a specifice RSVP $app->delete('/delete-rsvp/{username}/{GameID}', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("DELETE FROM rsvp WHERE GameID=:GameID AND username=:username"); $pdo->bindParam("GameID", $args["GameID"]); $pdo->bindParam("username", $args["username"]); $pdo->execute(); $count = $pdo->rowCount(); if ($count > 0) { // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } else { return $this->response->withStatus(404); } }); //get a specifiv rsvp $app->get('/rsvp/[{rsvpid}]', function(Request $request, Response $response, array $args){ // $pdo = $this->db->prepare("SELECT * FROM rsvp WHERE userid=:userid"); // $pdo = $this->db->prepare("SELECT r.*, g.* // FROM rsvp as r INNER JOIN games as g // WHERE rsvpid = :rsvpid"); $pdo = $this->db->prepare("SELECT r.GameID, g.* FROM rsvp as r natural join games as g WHERE rsvpid = :rsvpid"); $pdo->bindParam("rsvpid", $args["rsvpid"]); $pdo->execute(); $rsvpGamebyID = $pdo->fetchAll(); if (!$rsvpGamebyID) { return $response->withStatus(404); } else { return $this->response->withJson($rsvpGamebyID); } }); //post reservation $app->post('/rsvp', function(Request $request, Response $response, array $args){ // $pdo = $this->db->prepare("SELECT * FROM rsvp WHERE userid=:userid"); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $gameid = $data->GameID; $username = $data->username; } $check = $this->db->prepare("SELECT * FROM rsvp where GameID=:gameid AND username=:username"); $check->bindParam("gameid", $gameid); $check->bindParam("username", $username); $check->execute(); $row = $check->rowCount(); if ($row) { return $response->withStatus(401); } else { $pdo = $this->db->prepare("INSERT INTO rsvp(GameID, username) VALUES (:gameid, :username)"); $pdo->bindParam("username", $username); $pdo->bindParam("gameid", $gameid); $pdo->execute(); // return $response->withStatus(200);} $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } }); <file_sep>import { Component, OnInit } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { AuthService } from '../../_services/auth.service'; import { User } from '../../_models/user'; @Component({ selector: 'app-registration', templateUrl: './registration.component.html', styleUrls: ['./registration.component.scss'] }) export class RegistrationComponent implements OnInit { tempUser: User = new User(); pass: string; passConfirmation: string; constructor( private authService: AuthService, private router: Router, private snackBar: MatSnackBar ) { } ngOnInit() { } submit() { if(this.pass != this.passConfirmation) { this.snackBar.open('Passwords do not match, please try again', '', { duration: 5000 }); return; } this.authService.addUser(this.tempUser, this.pass).subscribe( res => { this.checkRegistration(res.status); }, err => { this.snackBar.open('Registration failed, please try again', '', { duration: 5000 }); } ); } checkRegistration(status) { if(status == 200) { localStorage.setItem('auth', this.authService.getJWT({user: this.tempUser.username})); } else { this.snackBar.open('Registration failed, please try again', '', { duration: 5000 }); return; } this.tempUser = new User(); this.router.navigate(['/dashboard']); } } <file_sep>FROM php:7-apache RUN apt-get update -y && apt-get install -y libpng-dev curl git libcurl4-openssl-dev npm RUN docker-php-ext-install pdo pdo_mysql gd curl RUN a2enmod rewrite RUN service apache2 restart <file_sep>export class CloudinaryResponse{ public_id?: string; version?: string; width?: number; height?: number; format?: string; created_at?: string; resource_type?: string; tags?: any[]; bytes?: number; type?: string; etag?: string; url?: string; secure_url?: string; signature?: string; original_filename?: string; }<file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // Show list of approved location $app->get('/approved-location', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM location where approved =1 ORDER BY date_created"); $pdo->execute(); $locations = $pdo->fetchAll(); return $this->response->withJson($locations); }); // Show list of un-approved location $app->get('/non-approved-location', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM location where approved =0 ORDER BY date_created"); $pdo->execute(); $locations = $pdo->fetchAll(); return $this->response->withJson($locations); }); // Show specific location $app->get('/location/{locationID}', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM location WHERE locationID=:locationID"); $pdo->bindParam("locationID", $args["locationID"]); $pdo->execute(); $location = $pdo->fetchAll(); if (!$location) { return $response->withStatus(404); } else { return $this->response->withJson($location); } }); <file_sep>FROM php:7-apache RUN apt-get update -y && apt-get install -y libpng-dev curl git libcurl4-openssl-dev nodejs RUN docker-php-ext-install pdo pdo_mysql gd curl RUN a2enmod rewrite # RUN a2enmod headers RUN service apache2 restart <file_sep>/* The authentication service includes registration and login routes. This also includes jwt operations for user authentication, working in conjunction with the authentication guard. */ import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { catchError, map, tap } from 'rxjs/operators'; import { KJUR } from 'jsrsasign'; import { environment } from '../../environments/environment'; import { User } from '../_models/user'; import { Comment } from '../_models/comment'; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); @Injectable() export class ProfileService { private apiUrl = environment.url; constructor( private http: HttpClient ) { } /** POST: create a comment */ createComment (username: string, comment: string, type: string, target: any, rating: number): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/newcomment`; return this.http.post<Response>(url, { username: username, Comment: comment, type: type, id: target, rating: rating }, {observe: 'response'}).pipe( tap(res => console.log(`added comment from user=${username}`)) ); } /** GET: find a user */ getUser (username: string): Observable<User> { const url = `${this.apiUrl}/profile/${username}`; console.log(url); return this.http.get<User>(url).pipe( tap(res => console.log(`found user w/ username=${username}`)) ); } // getUserComments (username: string): Observable<User> { // const url = `${this.apiUrl}/profile/${username}`; // console.log(url); // return this.http.get<User>(url).pipe( // tap(res => console.log(`found user w/ username=${username}`)) // ); // } /** TODO POST: change username or email */ updateUser (username: string): Observable<User> { const url = `${this.apiUrl}/profile/${username}`; console.log(url); return this.http.get<User>(url).pipe( tap(res => console.log(`found user w/ username=${username}`)) ); } getComments(type: string, target: any): Observable<Comment[]> { const url = `${this.apiUrl}/${type}/${target}/comments`; console.log(url); return this.http.get<Comment[]>(url).pipe( tap(res => console.log(`found comments`)) ); } getCurrentUser(): string { var currentUser = KJUR.jws.JWS.parse(localStorage.getItem('auth')).payloadObj.user; return currentUser; } } <file_sep>import { Component, Input, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { LocationService } from '../../_services/location.service'; import { ProfileService } from '../../_services/profile.service'; import { Location } from '../../_models/location'; @Component({ selector: 'approve-locations', templateUrl: './approve-locations.component.html', styleUrls: ['./approve-locations.component.scss'] }) export class ApproveLocationsComponent implements OnInit{ locations: Location[] = []; numOfLocations: number = 0; constructor( private locationService: LocationService, private profileService: ProfileService, private route: ActivatedRoute, private router: Router, private snackBar: MatSnackBar ){ } ngOnInit(){ this.getUnapprovedLocations(); } getUnapprovedLocations() { this.locationService.getUnapprovedLocations().subscribe( res => { this.locations = res; this.numOfLocations = this.locations.length; } ) } approveLocation(loc_id: number){ var currUser = this.profileService.getCurrentUser(); this.locationService.approveLocation(currUser, loc_id).subscribe( res => this.router.navigate(['/dashboard/user/' + currUser]), err => this.snackBar.open('Error occured, please try again', '', { duration: 5000 }) ); } denyLocation(loc_id: number){ var currUser = this.profileService.getCurrentUser(); this.locationService.denyLocation(loc_id).subscribe( res => this.router.navigate(['/dashboard/user/' + currUser]), err => this.snackBar.open('Error occured, please try again', '', { duration: 5000 }) ); } } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; $app->delete('/delete-game/{GameID}', function (Request $request, Response $response, array $args) { $pdo = $this->db->prepare("DELETE FROM games WHERE GameID=:GameID"); $pdo->bindParam("GameID", $args["GameID"]); $pdo->execute(); $count = $pdo->rowCount(); if ($count > 0) { // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } else { return $this->response->withStatus(404); } }); <file_sep>export class Location { locationID?: number; picture_url?: string; address?: string; description?: string; date_created?: Date; creator_username?: string; approved?: number; rating?: number; } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { SharedModule } from '../../_modules/shared/shared.module'; import { GameService } from '../../_services/game.service'; import { LocationDetailsPageComponent } from '../../pages/location-details-page/location-details-page.component'; import { LocationSubmitComponent } from '../../components/location-submit/location-submit.component'; import { LocationBrowserComponent } from '../../components/location-browser/location-browser.component'; import { LocationSubmitPageComponent } from '../../pages/location-submit-page/location-submit-page.component'; import { LocationBrowsePageComponent } from '../../pages/location-browse-page/location-browse-page.component'; import { GameCreateComponent } from '../../components/game-create/game-create.component'; import { GamePageComponent } from '../../pages/game-page/game-page.component'; import { GameCreatePageComponent } from '../../pages/game-create-page/game-create-page.component'; import { GamesListPageComponent } from '../../pages/games-list-page/games-list-page.component'; @NgModule({ declarations: [ LocationDetailsPageComponent, LocationSubmitComponent, LocationBrowserComponent, LocationSubmitPageComponent, LocationBrowsePageComponent, GamePageComponent, GameCreateComponent, GameCreatePageComponent, GamesListPageComponent ], imports: [ CommonModule, HttpClientModule, FormsModule, SharedModule ], providers: [ GameService ] }) export class GamesModule { } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { User } from '../../_models/user'; import { Location } from '../../_models/location'; import { Comment } from '../../_models/comment'; @Component({ selector: 'app-user-private', templateUrl: './user-private.component.html', styleUrls: ['./user-private.component.css'] }) export class UserPrivateComponent { displayComments: boolean = false; @Input() user: User; @Input() locations: Location[]; @Input() comments: Comment[]; newUsername: string; newEmail: string; constructor(){ } updateUser(){ this.user.username = this.newUsername; this.user.email = this.newEmail; } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { GameService } from '../../_services/game.service'; import { ProfileService } from '../../_services/profile.service'; import { LocationService } from '../../_services/location.service'; import { User } from '../../_models/user'; import { Game } from '../../_models/game'; import { Comment } from '../../_models/comment'; import { Location } from '../../_models/location'; @Component({ selector: 'app-game-page', templateUrl: './game-page.component.html', styleUrls: ['./game-page.component.scss'] }) export class GamePageComponent implements OnInit { user: User; game: Game; player: boolean; players: User[]; comments: Comment[]; location: Location; newComment: Comment = new Comment(); constructor( private route: ActivatedRoute, private router: Router, private gameService: GameService, private profileService: ProfileService, private locationService: LocationService, private snackBar: MatSnackBar ) { } ngOnInit() { this.getUser(); this.getGame(); this.isPlayer(); this.getPlayers(); this.getComments(); } getUser() { var currentUser = this.profileService.getCurrentUser(); this.profileService.getUser(currentUser).subscribe( user => { this.user = user; }, err => { this.user = new User(); } ); } getGame() { const gameid = +this.route.snapshot.paramMap.get('gameid'); this.gameService.getGame(gameid).subscribe( game => { this.game = game[0]; console.log(JSON.stringify(this.game)); console.log(this.game.locationID); this.getLocation(this.game.locationID); }, err => { this.game = new Game(); } ); } isPlayer() { const gameid = +this.route.snapshot.paramMap.get('gameid'); const currentUser = this.profileService.getCurrentUser(); this.gameService.getRSVPGames(currentUser).subscribe( games => { for(var game of games) { if(game.GameID == gameid) { this.player = true; return; } } this.player = false; }, err => { this.player = false; console.log('User does not have any rsvps'); } ); } getPlayers() { const gameid = +this.route.snapshot.paramMap.get('gameid'); this.gameService.getGameRSVPs(gameid).subscribe( players => { this.players = players; }, err => { this.players = []; } ); } getComments() { const gameid = +this.route.snapshot.paramMap.get('gameid'); this.profileService.getComments("game", gameid).subscribe( comments => { this.comments = comments; }, err => { this.comments = []; } ); } getLocation(id: number) { this.locationService.getLocation(id).subscribe( res => { this.location = res; }, err => { this.location = new Location(); console.log("could not find location"); } ) } addComment(){ const gameid = this.route.snapshot.paramMap.get('gameid'); this.profileService.createComment(this.user.username, this.newComment.Comment, 'game', gameid, 0).subscribe( res => { this.router.navigate(['/dashboard/game/' + gameid]) }, err => { this.snackBar.open('Comment submition failed, please try again.', '', { duration: 5000 }); } ); } handlePlayer(){ if(this.player){ this.gameService.deleteRSVP(this.user.username, this.game.GameID).subscribe( res => { this.player = false; const gameid = +this.route.snapshot.paramMap.get('gameid'); this.router.navigate([`/dashboard/game/${gameid}`]); this.snackBar.open("You have canceled your rsvp to this game", '', { duration: 5000 }); }, err => { this.snackBar.open('Could not delete rsvp, please try again', '', { duration: 5000 }); } ); } else{ this.gameService.rsvp(this.user.username, this.game.GameID).subscribe( res => { this.player = true; const gameid = +this.route.snapshot.paramMap.get('gameid'); this.router.navigate([`/dashboard/game/${gameid}`]); this.snackBar.open("You have rsvp'd to this game", '', { duration: 5000 }); }, err => { this.snackBar.open('Could not rsvp, please try again', '', { duration: 5000 }); } ); } } } <file_sep><?php header('Content-type: application/json'); require '../vendor/autoload.php'; use \Mailgun\Mailgun; use Slim\Http\Request; use Slim\Http\Response; //Email verification works but had a problem with setting up our site domain so that email sent for verification would say username@hooplife //but we were not able to figur it out intime the program //the email verification works verywell with emails that are registerd as Authorized recipients on the mailgun platform function email_verification($email, $last_name, $first_name, $username, $uid){ define('MAILGUN_PUBKEY','<KEY>' ); $link = 'http://172.16.58.3:8080/verfy/' . $uid; $mgClient = new \Mailgun\Mailgun('key-8e43115292421ce6aacc3a9660ff8ab2', new \Http\Adapter\Guzzle6\Client()); $domain = "sandboxebd7f04a98f44fce89d21ec452133e47.mailgun.org"; $send = $mgClient->sendMessage($domain, array( 'from' => 'hooplife <<EMAIL>@<EMAIL>>', 'to' => $first_name . ' ' . $last_name . ' <' . $email . '>', 'subject' => 'Hooplife Yants You Verfy Your Account', 'html' =>' <body> <p>Dear ' .$first_name. ' <br><br> <br>We are excited to have you as part of the hooplife family<br> <br>Please veryfy you email address by clicking on the following link<br> <br> '. $link .' <br> <br>With regards<br> <br>Team Hooplife<br> </p> </body> </html>', )); } // Validating a user's email $app->get('/verfy/{username}', function ($request, $response, $args) { $pdo = $this->db; // $update = $pdo->prepare('UPDATE users SET verified='1' WHERE username=:username'); // $update->bindParam("username", $username); // $update->execute(); // return $response->withStatus(200); $check = $this->db->prepare("UPDATE users SET verified='1' WHERE userid=:username "); $check->bindParam("username", $args['username']); $check->execute(); echo "Thank you for Validating you email"; // return $response->withStatus(200); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { Router, RouterLink, NavigationEnd } from '@angular/router'; import { Page } from '../../_models/page'; import { AuthService } from '../../_services/auth.service'; import { ProfileService } from '../../_services/profile.service'; @Component({ selector: 'app-navigation', templateUrl: './navigation.component.html', styleUrls: ['./navigation.component.scss'] }) export class NavigationComponent implements OnInit { pages: Page[]; constructor( private authService: AuthService, private profileService: ProfileService, private router: Router ) { this.router.routeReuseStrategy.shouldReuseRoute = function(){ return false; } this.router.events.subscribe((evt) => { if (evt instanceof NavigationEnd) { // trick the Router into believing it's last link wasn't previously loaded this.router.navigated = false; // if you need to scroll back to top, here is the right place window.scrollTo(0, 0); } }); } ngOnInit() { var currentUser = this.profileService.getCurrentUser(); this.pages = [ { "name": "profile", "url": `user/${currentUser}` }, { "name": "games", "url": "games" }, { "name": "locations", "url": "locations" } ] } logout() { this.authService.logout(); } } <file_sep>import { Component, ElementRef, Input, EventEmitter, Output, OnChanges } from '@angular/core'; import { CloudinaryResponse } from '../../_models/cloudinary-response'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from "rxjs/Rx"; @Component({ selector: 'image-upload', template: '<form><input type="file" accept="image/*" (change)="uploadFile($event)"></form>' }) export class ImageUploadComponent { @Input() public public_id: string; @Output() public uploaded: EventEmitter<boolean> = new EventEmitter<boolean>(); constructor(private http: HttpClient) {} uploadFile(fileInput: any){ this.upload(fileInput).subscribe(x => { if(!x.public_id){ this.uploaded.emit(false); } else { this.uploaded.emit(true); } }); } upload(fileInput: any): Observable<CloudinaryResponse> { let formData: FormData = new FormData(); formData.append('file', fileInput.target.files[0]); formData.append('upload_preset', 'knlspx3g'); return this.http.post<CloudinaryResponse>('https://api.cloudinary.com/v1_1/dwymiyvae/image/upload', formData, {headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')}) .catch(x => this.handleException(x)); } handleException(exception: any) {         var message = `${exception.status} : ${exception.statusText}\r\n${exception.body.error}`;         alert(message); this.uploaded.emit(false);         return Observable.throw(message);     } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { LocationService } from '../../_services/location.service'; import { ProfileService } from '../../_services/profile.service'; @Component({ selector: 'app-location-submit', templateUrl: './location-submit.component.html', styleUrls: ['./location-submit.component.scss'] }) export class LocationSubmitComponent { currUser: string; address: string; description: string; pic: string; constructor( private router: Router, private profileService: ProfileService, private locationService: LocationService, private snackBar: MatSnackBar ) {} cancel() { this.router.navigate(['/dashboard/locations']); } submit() { this.currUser = this.profileService.getCurrentUser(); this.locationService.requestLoc(this.currUser, this.address, this.description, this.pic).subscribe( res => { this.snackBar.open('Location request suceeded, it will show up in the list once approved', '', { duration: 5000 }); }, err => { this.snackBar.open('Request failed, please try again. Descriptions and addresses must be unique', '', { duration: 5000 }); } ); } } <file_sep>export class Comment { username: string; Date: Date; rating: number; Comment: string; } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { MatSnackBarModule } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { AppRoutingModule } from '../../_modules/app-routing/app-routing.module'; import { ProfileService } from '../../_services/profile.service'; import { LocationService } from '../../_services/location.service'; import { RatingComponent } from '../../components/rating/rating.component'; import { CommentComponent } from '../../components/comment/comment.component'; import { ImageUploadComponent } from '../../components/image-upload/image-upload.component'; @NgModule({ declarations: [ RatingComponent, CommentComponent, ImageUploadComponent ], imports: [ CommonModule, HttpClientModule, MatSnackBarModule, NoopAnimationsModule, AppRoutingModule ], providers: [ ProfileService, LocationService ], exports: [ RatingComponent, CommentComponent, AppRoutingModule ] }) export class SharedModule { } <file_sep>export class User { username: string; userid: number; first_name: string; last_name: string; num_of_games_played: number; email: string; date_joined: Date; last_updated: Date; last_login: Date; year: string; isAdmin: number; ranking: string; rating: number; wins: number; losses: number; pic_url: string; } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; //a user that is an admin can make another user admin $app->get('/setadmin[/{AdminUsername}[/{username}]]', function($request, $response, $args){ $check = $this->db->prepare("SELECT * FROM users where username=:AdminUsername AND isAdmin='1'"); $check->bindParam("AdminUsername", $args['AdminUsername']); $check->execute(); $row = $check->rowCount(); if (!$row) { return $response->withStatus(403); } else $check = $this->db->prepare("UPDATE users SET isAdmin='1' WHERE username=:username "); $check->bindParam("username", $args['username']); $check->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; //changed from using user seesion to JWT //comment part is commented out because I implimented it in its own route $app->get('/profile/{username}', function (Request $request, Response $response, array $args){ $db = $this->db; //Query users table for data on current user based on userID passed in //Query results will tie to $targetUser $userQuery = $db->prepare("SELECT username, userid, first_name, last_name, num_of_games_played, email, date_joined, last_updated, last_login, year, isAdmin, ranking, rating, wins, losses, pic_url FROM users WHERE username=:username"); $userQuery->bindParam("username", $args['username']); $userQuery->execute(); $targetUser = $userQuery->fetchObject(); $row = $userQuery->rowCount(); if (!$row) { return $response->withStatus(404); } //Fetch userid of current user to determine if user is viewing own page //Attach viewingOwnPage boolean to targetUser object //$sessionQuery = $db->prepare("SELECT userid FROM Sessions WHERE sessionid = :sid"); //$sessionQuery->bindParam("sid", $args['sessionId']); //$sessionQuery->execute(); //if ($targetUser->userid === $sessionQuery->fetchObject()->userid) // $targetUser->viewingOwnPage = true; //else //$targetUser->viewingOwnPage = false; //Fetch comments on the user's page //If there are comments, add them to the targetUser object // $commentsQuery = $db->prepare("SELECT Comment, Date, username, target_id, target_username, URL FROM comments WHERE target_username =:username"); // $commentsQuery->bindParam("username", $args['username']); // $commentsQuery->execute(); // $numOfComments = $commentsQuery->rowCount(); // // if ($numOfComments > 0) // $targetUser->comments = $commentsQuery->fetchAll(); // // //Format user information into json and send response $jsonResponse = json_encode($targetUser); $this->response->getBody()->write($jsonResponse); return $this->response; }); <file_sep>/* The authentication service includes registration and login routes. This also includes jwt operations for user authentication, working in conjunction with the authentication guard. */ import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { catchError, map, tap } from 'rxjs/operators'; import { KJUR } from 'jsrsasign'; import { environment } from '../../environments/environment'; import { User } from '../_models/user'; import { Login } from '../_models/login'; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); @Injectable() export class AuthService { private apiUrl = environment.url; constructor( private http: HttpClient, private router: Router ) { } /** POST: add a new user to the server */ addUser (user: User, pass: string): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/registration`; return this.http.post<Response>(url, { username: user.username, first_name: user.first_name, last_name: user.last_name, email: user.email, year: user.year, password: <PASSWORD> }, {observe: 'response'}).pipe( tap(res => console.log(`added user w/ username=${user.username}`)) ); } login(login: Login): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/login`; return this.http.post<Response>(url, { username: login.username, password: login.password }, {observe: 'response'}).pipe( tap(login => console.log(`check login`)) ); } /* TODO PUT: change password */ changePass(username: string, oldPass: string, newPass: string): Observable<HttpResponse<any>> { const url = `${this.apiUrl}/change-password/${username}`; return this.http.put<Response>(url, { old_password: <PASSWORD>, new_password: <PASSWORD> }, {observe: 'response'}).pipe( tap(login => console.log(`check login`)) ); } getJWT(payload) { var header = {alg: "HS256", typ: "JWT"}; return KJUR.jws.JWS.sign("HS256", header, payload, {utf8: "secret"}); } logout() { localStorage.removeItem('auth'); this.router.navigate(['/login']); } } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // Show list of games nearby $app->get('/games', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM games ORDER BY date_of_game"); $pdo->execute(); $games = $pdo->fetchAll(); if(!empty($games)) { return $this->response->withJson($games); } else { return $this->response->withStatus(404); } }); <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // Show specific game $app->get('/game/{id}', function(Request $request, Response $response, array $args){ $pdo = $this->db->prepare("SELECT * FROM games WHERE GameID=:id"); $pdo->bindParam("id", $args["id"]); $pdo->execute(); $game = $pdo->fetchAll(); if (!$game) { return $response->withStatus(404); } else { return $this->response->withJson($game); } }); // Submit a new game $app->post('/new-game', function(Request $request, Response $response){ $input = $request->getParsedBody(); $pdo = $this->db->prepare("INSERT INTO games (description, time_created, creator_username, date_of_game, minimum_rank, locationID) VALUES (:description, CURRENT_TIMESTAMP, :creator_username, :date_of_game, :minimum_rank, :locationID)"); // $pdo->bindParam("picture_url", $input["picture_url"]); $pdo->bindParam("locationID", $input["locationID"]); $pdo->bindParam("date_of_game", $input["date_of_game"]); $pdo->bindParam("description", $input["description"]); $pdo->bindParam("creator_username", $input["creator_username"]); $pdo->bindParam("minimum_rank", $input["minimum_rank"]); $pdo->execute(); // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); // Update game details $app->put('/game/{GameID}/edit', function(Request $request, Response $response, array $args) { $input = $request->getParsedBody(); $pdo = $this->db->prepare("UPDATE games SET picture_url=:picture_url, locationID=:locationID, description=:description, time_created=CURRENT_TIMESTAMP, date_of_game=:date_of_game, minimum_rank=:minimum_rank WHERE GameID=:GameID"); $pdo->bindParam("GameID", $args["GameID"]); $pdo->bindParam("picture_url", $input["picture_url"]); $pdo->bindParam("locationID", $input["locationID"]); $pdo->bindParam("description", $input["description"]); $pdo->bindParam("date_of_game", $input["date_of_game"]); $pdo->bindParam("minimum_rank", $input["minimum_rank"]); $pdo->execute(); // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // update a user ranking $app->put('/rank-update/[{uid}]', function(Request $request, Response $response, array $args){ $data = json_decode(file_get_contents("php://input")); $ranking = $data->ranking; // $input = $request->getParsedBody(); // $pdo->bindParam("ranking", $args["ranking"]); // $pdo->execute(); // $input['ranking'] = $args['ranking']; if( !isset($ranking) || empty($ranking)){ return $response->withStatus(403); } $pdo = $this->db->prepare('SELECT * FROM users WHERE username=:uid'); $pdo->bindParam("uid", $args['uid']); $pdo->execute(); $row = $pdo->rowCount(); if (!$row) { return $response->withStatus(404); } else { $stmt = $this->db->prepare("UPDATE users SET ranking=:ranking WHERE username=:uid"); $stmt->bindParam("uid", $args['uid']); $stmt->bindParam("ranking", $ranking); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } }); // update number of games played $app->put('/games-played-update/[{uid}]', function(Request $request, Response $response, array $args){ $data = json_decode(file_get_contents("php://input")); $num_of_games_played = $data->num_of_games_played; // $input = $request->getParsedBody(); // $pdo->bindParam("ranking", $args["ranking"]); // $pdo->execute(); // $input['ranking'] = $args['ranking']; if( !isset($num_of_games_played) || empty($num_of_games_played)){ return $response->withStatus(403); } $pdo = $this->db->prepare('SELECT * FROM users WHERE username=:uid'); $pdo->bindParam("uid", $args['uid']); $pdo->execute(); $row = $pdo->rowCount(); if (!$row) { return $response->withStatus(404); } else { $stmt = $this->db->prepare("UPDATE users SET num_of_games_played=:num_of_games_played WHERE username=:uid"); $stmt->bindParam("uid", $args['uid']); $stmt->bindParam("num_of_games_played", $num_of_games_played); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } }); // update player rating $app->put('/rating-update/{type}/{uid}', function(Request $request, Response $response, array $args){ $data = json_decode(file_get_contents("php://input")); $rating = $data->rating; // $input = $request->getParsedBody(); // $pdo->bindParam("ranking", $args["ranking"]); // $pdo->execute(); // $input['ranking'] = $args['ranking']; if( !isset($rating) || empty($rating)){ return $response->withStatus(403); } // if ($args['type'] == "location") { // $stmt = "(update location SET rating=:rating Where locationID=:uid"; // $stmt->bindParam("uid", $args['uid']); // $stmt->bindParam("rating", $rating); // $stmt->execute(); // $data = array(‘success’ => ‘true’); // return $response->withJson($data, 200); // } // else if ($args['type'] == "user") { $pdo = $this->db->prepare('SELECT * FROM users WHERE username=:uid'); $pdo->bindParam("uid", $args['uid']); $pdo->execute(); $row = $pdo->rowCount(); if (!$row) { return $response->withStatus(404); } else { $stmt = $this->db->prepare("UPDATE users SET rating=:rating WHERE username=:uid"); $stmt->bindParam("uid", $args['uid']); $stmt->bindParam("rating", $rating); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } } }); // update player win/loss $app->put('/wins-update/[{uid}]', function(Request $request, Response $response, array $args){ $data = json_decode(file_get_contents("php://input")); $wins = $data->wins; // $input = $request->getParsedBody(); // $pdo->bindParam("ranking", $args["ranking"]); // $pdo->execute(); // $input['ranking'] = $args['ranking']; if( !isset($wins) || empty($wins)){ return $response->withStatus(403); } $pdo = $this->db->prepare('SELECT * FROM users WHERE username=:uid'); $pdo->bindParam("uid", $args['uid']); $pdo->execute(); $row = $pdo->rowCount(); if (!$row) { return $response->withStatus(404); } else { $stmt = $this->db->prepare("UPDATE users SET wins=:wins WHERE username=:uid"); $stmt->bindParam("uid", $args['uid']); $stmt->bindParam("wins", $wins); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } }); // update player loss $app->put('/losses-update/[{uid}]', function(Request $request, Response $response, array $args){ $data = json_decode(file_get_contents("php://input")); $losses = $data->losses; // $input = $request->getParsedBody(); // $pdo->bindParam("ranking", $args["ranking"]); // $pdo->execute(); // $input['ranking'] = $args['ranking']; if( !isset($losses) || empty($losses)){ return $response->withStatus(403); } $pdo = $this->db->prepare('SELECT * FROM users WHERE username=:uid'); $pdo->bindParam("uid", $args['uid']); $pdo->execute(); $row = $pdo->rowCount(); if (!$row) { return $response->withStatus(404); } else { $stmt = $this->db->prepare("UPDATE users SET losses=:losses WHERE username=:uid"); $stmt->bindParam("uid", $args['uid']); $stmt->bindParam("losses", $losses); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } }); <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // change password $app->put('/change-password/[{uid}]', function(Request $request, Response $response, array $args){ $data = json_decode(file_get_contents("php://input")); $old_password = $data->old_password; $new_password = $data->new_password; // $input = $request->getParsedBody(); // $pdo->bindParam("ranking", $args["ranking"]); // $pdo->execute(); // $input['ranking'] = $args['ranking']; if( !isset($new_password) || empty($new_password) || !isset($old_password) || empty($old_password)){ return $response->withStatus(403); } $hnew_password = md5($<PASSWORD>); $hold_password = md5($<PASSWORD>); $pdo = $this->db->prepare('SELECT * FROM users WHERE username=:uid AND password=:<PASSWORD>'); $pdo->bindParam("uid", $args['uid']); $pdo->bindParam("hold_password", $hold_<PASSWORD>); $pdo->execute(); $row = $pdo->rowCount(); if (!$row) { return $response->withStatus(403); } else { $stmt = $this->db->prepare("UPDATE users SET password=:<PASSWORD>, last_updated=CURRENT_TIMESTAMP WHERE username=:uid"); $stmt->bindParam("uid", $args['uid']); $stmt->bindParam("hnew_password", $hnew_<PASSWORD>); $stmt->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } }); <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { User } from '../../_models/user' import { Comment } from '../../_models/comment'; import { ProfileService } from '../../_services/profile.service'; @Component({ selector: 'app-user-public', templateUrl: './user-public.component.html', styleUrls: ['./user-public.component.css'] }) export class UserPublicComponent{ displayComments: boolean = true; currentUser: string; hasCommented: boolean = false; hasRated: boolean = false; newComment: Comment = new Comment(); @Input() public user: User; @Input() comments: Comment[]; constructor( private route: ActivatedRoute, private router: Router, private profileService: ProfileService, private snackBar: MatSnackBar ){ } ngOnInit() { this.currentUser = this.profileService.getCurrentUser(); } addComment() { const user = this.route.snapshot.paramMap.get('username'); this.profileService.createComment(this.currentUser, this.newComment.Comment, 'user', user, this.newComment.rating).subscribe( res => { this.router.navigate(['/dashboard/user/' + user]) }, err => { this.snackBar.open('Comment submition failed, please try again.', '', { duration: 5000 }); } ); } onRated(num: number){ this.newComment.rating = num; this.hasRated = true; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { LocationSubmitComponent } from '../../components/location-submit/location-submit.component' @Component({ selector: 'app-location-submit-page', templateUrl: './location-submit-page.component.html', styleUrls: ['./location-submit-page.component.css'] }) export class LocationSubmitPageComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>export const environment = { production: true, url: 'http://172.16.17.32' }; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuard } from '../../_guards/auth.guard'; import { LoginGuard } from '../../_guards/login.guard'; import { DashboardComponent } from '../../pages/dashboard/dashboard.component'; import { LoginComponent } from '../../components/login/login.component'; import { RegistrationComponent } from '../../components/registration/registration.component'; import { LocationDetailsPageComponent } from '../../pages/location-details-page/location-details-page.component'; import { UserPageComponent } from '../../pages/user-page/user-page.component'; import { LocationSubmitPageComponent } from '../../pages/location-submit-page/location-submit-page.component'; import { LocationBrowsePageComponent } from '../../pages/location-browse-page/location-browse-page.component'; import { GamePageComponent } from '../../pages/game-page/game-page.component'; import { GameCreatePageComponent } from '../../pages/game-create-page/game-create-page.component'; import { GamesListPageComponent } from '../../pages/games-list-page/games-list-page.component'; import { ApproveLocationsComponent } from '../../components/approve-locations/approve-locations.component'; const routes: Routes = [ { path: '', redirectTo: '/dashboard/games', pathMatch: 'full' }, { path: 'registration', component: RegistrationComponent, canActivate: [LoginGuard] }, { path: 'login', component: LoginComponent, canActivate: [LoginGuard] }, { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard], children: [ { path: '', redirectTo: 'games', pathMatch: 'full' }, { path: 'games', component: GamesListPageComponent, canActivate: [AuthGuard] }, { path: 'game/:gameid', component: GamePageComponent, canActivate: [AuthGuard] }, { path: 'gameSubmit', component: GameCreatePageComponent, canActivate: [AuthGuard] }, { path: 'locations', component: LocationBrowsePageComponent, canActivate: [AuthGuard] }, { path: 'location/:locID', component: LocationDetailsPageComponent, canActivate: [AuthGuard] }, { path: 'locationSubmit', component: LocationSubmitPageComponent, canActivate: [AuthGuard] }, { path: 'user/:username', component: UserPageComponent, canActivate: [AuthGuard] }, { path: 'approve-locations', component: ApproveLocationsComponent, canActivate: [AuthGuard] }, ] }, { path: '**', component: DashboardComponent } ] @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ], providers: [ AuthGuard, LoginGuard ] }) export class AppRoutingModule { } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { SharedModule } from './_modules/shared/shared.module'; import { AuthenticationModule } from './_modules/authentication/authentication.module'; import { ProfileModule } from './_modules/profile/profile.module'; import { GamesModule } from './_modules/games/games.module'; import { AppComponent } from './app.component'; import { DashboardComponent } from './pages/dashboard/dashboard.component'; import { NavigationComponent } from './components/navigation/navigation.component'; @NgModule({ declarations: [ AppComponent, DashboardComponent, NavigationComponent ], imports: [ BrowserModule, RouterModule, HttpClientModule, FormsModule, SharedModule, AuthenticationModule, ProfileModule, GamesModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Injectable } from '@angular/core'; import { Router, CanActivate } from '@angular/router'; import { KJUR } from 'jsrsasign'; @Injectable() export class LoginGuard implements CanActivate { constructor(private router: Router) { } canActivate() { var jwt = localStorage.getItem('auth'); if (jwt) { var isValid = KJUR.jws.JWS.verify(jwt, {utf8: "secret"}, ["HS256"]); if(isValid) { this.router.navigate(['/dashboard']); return true; } } // Not logged in so it's fine to stay on the login/registration page return true; } } <file_sep>#!/usr/bin/env bash sudo docker-compose -f $1 stop sudo docker-compose -f $1 build sudo docker-compose -f $1 up -d <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Location } from '../../_models/location'; @Component({ selector: 'location-browser', templateUrl: './location-browser.component.html', styleUrls: ['./location-browser.component.scss'] }) export class LocationBrowserComponent implements OnInit { @Input() locations: Location[]; constructor( private router: Router ) { } ngOnInit() { } openSubmitLocationPage() { this.router.navigate(['/dashboard/locationSubmit']); } goToLocation(id: number) { this.router.navigate([`/dashboard/location/${id}`]); } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { Game } from '../../_models/game'; import { Location } from '../../_models/location'; import { LocationService } from '../../_services/location.service'; import { GameService } from '../../_services/game.service'; import { ProfileService } from '../../_services/profile.service'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material'; @Component({ selector: 'game-create', templateUrl: './game-create.component.html', styleUrls: ['./game-create.component.scss'] }) export class GameCreateComponent implements OnInit { locations: Location[] = []; location_id: number; game_date: Date; hour: string; minute: string; amORpm: string; minimum_rank: number; description: string; constructor( private locationService: LocationService, private gameService: GameService, private profileService: ProfileService, private router: Router, private snackBar: MatSnackBar ) {} ngOnInit() { this.locationService.getApprovedLocations().subscribe( res => { this.locations = res; }, err => { alert('what did you do'); }); } processRating(rank: number){ this.minimum_rank = rank; } createGame(){ const current_user = this.profileService.getCurrentUser(); this.gameService.makeGame( current_user, this.game_date + ' ' + this.hour + ':' + this.minute + ' ' + this.amORpm, this.description, this.minimum_rank, this.location_id ).subscribe( res => { this.router.navigate(['/dashboard/games']); }, err => { this.snackBar.open('Request failed, please try again.', '', { duration: 5000 }); } ); } } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; //approve locatinon $app->get('/locapprove[/{AdminUsername}[/{locid}]]', function($request, $response, $args){ $check = $this->db->prepare("SELECT * FROM users where username=:AdminUsername AND isAdmin='1'"); $check->bindParam("AdminUsername", $args['AdminUsername']); $check->execute(); $row = $check->rowCount(); if (!$row) { return $response->withStatus(403); } if ($row) { $check = $this->db->prepare("SELECT * FROM location where locationID=:locid"); $check->bindParam("locid", $args['locid']); $check->execute(); $row1 = $check->rowCount(); if (!$row1) { return $response->withStatus(404); } else { $check = $this->db->prepare("UPDATE location SET approved='1' WHERE locationID=:locid "); $check->bindParam("locid", $args['locid']); $check->execute(); // return $response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); } } }); <file_sep>import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; @Component({ selector: 'rating', templateUrl: './rating.component.html', styleUrls: ['./rating.component.scss'] }) export class RatingComponent { stars: number; userHasRated: boolean; clickStars: boolean; @Input() public ratingValue: number; @Output() public onRated = new EventEmitter<number>(); ngOnInit() { if(this.ratingValue === 0) { this.clickStars = true; } else { this.clickStars = false; this.stars = Math.round(this.ratingValue * 2)/2; } } public rated(num: number){ this.onRated.emit(num); this.ratingValue = num; } } <file_sep><?php header('Content-type: application/json'); use Slim\Http\Request; use Slim\Http\Response; // Show all comments for a game, location, or user $app->get('/{type}/{id}/comments', function(Request $request, Response $response, array $args){ if ($args['type'] == "game") { $sql = "SELECT username, comments.rating, Date, Comment, comments.GameID from comments JOIN games WHERE comments.GameID=games.GameID AND comments.GameID=:id ORDER BY Date"; } else if ($args['type'] == "location") { $sql = "SELECT comments.username, comments.rating, Date, Comment, comments.locationID from comments JOIN location WHERE comments.locationID=location.locationID AND comments.locationID=:id ORDER BY Date"; } else if ($args['type'] == "user") { $sql = "SELECT comments.username, comments.rating, Date, Comment, target_username FROM comments JOIN users WHERE comments.username=users.username AND comments.target_username=:id ORDER BY Date"; } else { return $this->response->withStatus(404); } $pdo = $this->db->prepare($sql); $pdo->bindParam("id", $args['id']); $pdo->execute(); $comments = $pdo->fetchAll(); return $this->response->withJson($comments); }); // Post a new comment $app->post('/newcomment', function(Request $request, Response $response, array $args){ $input = $request->getParsedBody(); if ($input['type'] == "game") { $sql = "INSERT INTO comments (username, Comment, Date, GameID, rating) VALUES (:username, :Comment, CURRENT_TIMESTAMP, :id, :rating)"; } else if ($input['type'] == "location") { $sql = "INSERT INTO comments (username, Comment, Date, locationID, rating) VALUES (:username, :Comment, CURRENT_TIMESTAMP, :id, :rating)"; } else if ($input['type'] == "user") { $sql = "INSERT INTO comments (username, Comment, Date, target_username, rating) VALUES (:username, :Comment, CURRENT_TIMESTAMP, :id, :rating)"; } else { return $this->response->withStatus(404); } $pdo = $this->db->prepare($sql); $pdo->bindParam("username", $input["username"]); $pdo->bindParam("Comment", $input["Comment"]); $pdo->bindParam("rating", $input["rating"]); // $pdo->bindParam("target_id", $input["target_id"]); $pdo->bindParam("id", $input["id"]); $pdo->execute(); // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); // Update a comment $app->put('/{type}/{id}/comments/{CommentID}/edit', function(Request $request, Response $response, array $args){ $input = $request->getParsedBody(); $sql = "UPDATE comments SET Comment=:Comment WHERE CommentID=:CommentID"; $pdo = $this->db->prepare($sql); $pdo->bindParam("Comment", $input["Comment"]); $pdo->bindParam("CommentID", $input["CommentID"]); $pdo->execute(); // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); // Delete a comment $app->delete('/{type}/{id}/delete-comment/{CommentID}', function (Request $request, Response $response, array $args) { $pdo = $this->db->prepare("DELETE FROM comments WHERE CommentID=:CommentID"); $pdo->bindParam("CommentID", $args["CommentID"]); $pdo->execute(); // return $this->response->withStatus(200); $data = array(‘success’ => ‘true’); return $response->withJson($data, 200); }); <file_sep>export class Game { GameID: number; picture_url: string; locationID: number; description: string; time_created: Date; creator_username: number; date_of_game: string; minimum_rank: number; }
c882060640717dd18cfed2ff0a19f582fd44788a
[ "HTML", "Markdown", "PHP", "TypeScript", "Dockerfile", "Shell" ]
60
TypeScript
Thakugan/hooplife
a5903a2d5ea4bc77ec2b77407afbc9479431b79d
35b1df27f27109289c52e3b4eab336bcb1c7bdaa
refs/heads/master
<repo_name>AMOS2116/pythontutorial<file_sep>/text.py print('amos ihunna')<file_sep>/variable.py print('helloworld') #variables are place holders for codes ''' variables names are case sensitive - age is not the same as AGE variables can start with letters and underscore can contain numbers ''' name = 'Augustine' #string age = 35 #int weight = 95.5 #float is_here = True #boolean fav_colors = ['white', 'blue', 'yellow'] #list details = {'name': 'Augustine', 'age': 35, 'weight': 95.5} #dictionary fruits = ('orange', 'apple', 'watermelon') #tuple print(fav_colors) print(weight, name, age) <file_sep>/conditionals.py # If/Else conditions are used to decide to do something based on a condition being true or false age_casmir = 17 age_abdul = 16 # Comparison operators(==, !=, >, <, >=, <=) - Used to compare values # Simple if if age_casmir > age_abdul: print(f'{age_casmir} is greater than {age_abdul}') # if/Else if age_casmir > age_abdul: print(f'{age_casmir} is greater than {age_abdul}') else: print(f'{age_abdul} is greater than {age_casmir}') # elif if age_casmir > age_abdul: print(f'{age_casmir} is greater than {age_abdul}') elif age_casmir == age_abdul: print(f'{age_casmir} is equal to {age_abdul}') else: print(f'{age_abdul} is greater than {age_casmir}') # Nested if if age_casmir > 10: if age_casmir <= 20: print(f'{age_casmir} is greater than 10 and less than or equl to 20') # Logical Operators ( and, or, not) - used to combine conditional statements # and if age_casmir > 10 and age_casmir <= 20: print(f'{age_casmir} is greater than 10 and less than or equl to 20') # or if age_casmir > 10 or age_casmir <= 20: print(f'{age_casmir} is greater than 10 or less than or equl to 20') # not if not(age_casmir == age_abdul): print(f'{age_casmir} is not equal to {age_abdul}') # Membership Operators( in, not in) -Membershipt operatorsare used to test if a sequence is present in an object ages = [19, 20, 20, 18, 19, 20] # in if age_casmir in ages: print(age_casmir in ages) # not in if age_casmir not in ages: print(age_casmir not in ages) # Identity operators ( is , is not) - compare the objects, not if they are equal, but if they are actually the same object, with the same memory location location # is #if age_casmir is age_abdul: #print(age_casmir is age_abdul) # is not if age_casmir is not age_abdul: print(age_casmir is not age_abdul) # +2347067162698 my phone <file_sep>/students.py from tkinter import * from tkinter import ttk import sqlite3 class StudentDB: # will hold the database connection db_conn = 0 # A Cursor is used to traverse the records of a result theCursor = 0 # will store the current student selected curr_student = 0 # set up the database def setup_db(self): # open or create a database self.db_conn = sqlite3.connect('student.db') # the cursor is able to traverse the records self.theCursor = self.db_conn.cursor() # create the table if it does not exist try: self.db_conn.execute("CREATE TABLE if it not exist Students(ID INTERGER PRIMARY KEY AUTOINCREMENT NOT NULL, FName TEXT NOT NULL, LName TEXT NOT NULL);") self.db_conn.commit() except sqlite3.OperationalError: print("Error : Table not Created") # Submit button function def stud_submit(self): # Insert students in the database self.db_conn.execute("INSERT INTO Students (FName, LName) " + "VALUES ( '" + self.fn_entry_value.get() + "', '" + self.ln_entry_value.get() + "') ") # Clear the entry box self.fn_entry.delete(0, "end") self.ln_entry.delete(0, "end") # Update the Listbox with the students List self.update_listbox() def update_listbox(self): # Delete items in the listbox self.list_box.delete(0, END) # Get the students from the database try: result = self.theCursor.execute("SELECT ID, FName, LName FROM STtudents") for row in result: stud_id = row[0] stud_fname = row[1] stud_lname = row[2] # Put the students in the list box self.list_box.insert(stud_id, stud_fname + " " + stud_lname) except sqlite3.OperationalError: print("The Table Dosnt Exist") except: print("1:Couldnt Retrieve data from database") # load listbox selected students into the selected entries(textbox) def load_student(self, event=None): # Get index selected which is the student id lb_widget = event.widget index = str(lb_widget.curselection() [0] + 1) # Store the current students index self.curr_student = index # Retrieve student List from the database try: result = self.theCursor.execute("SELECT ID, FName FROM Students WHERE ID=" + index) # you now recieve a list of the lists that hold the results for row in result: stud_id = row[0] stud_fname = row[1] stud_lname = row[2] # Set values in the entries self.fn_entry_value.set(stud_fname) self.ln_entry_value.set(stud_lname) except sql3.OperationalError: print("The Table dosnt Exist") except: print("2, Couldnt retrieve data from the database") # Update student info def update_student(self, event=None): # Update student records with change made in entry try: self.db_conn.execute("UPDATE Students SET FName='" + self.fn_entry_value.get() + "', LName='" + self.ln_entry_value.get() + "' WHERE ID=" + self.curr_student) self.db_conn.commit() except sqlite3.OperationalError: print("Database couldnt be updated") # Clear the entry boxes self.fn_entry.delete(0, "end") self.ln_entry.delete(0, "end") # Update te list box with student list self.update_listbox() def __init__(self, root): root.title('Student Database') root.geometry('270x340') root.config(bg= 'green') # Add widgtes # First Row fn_label = Label(root, text = "<NAME>") fn_label.grid(row = 0, column = 0, padx = 10, pady = 10, sticky = W) self.fn_entry_value = StringVar(root, value=" ") self.fn_entry = ttk.Entry(root, textvariable = self.fn_entry_value) self.fn_entry.grid(row = 0, column = 1, padx = 10, pady = 10, sticky = W) # Second Row ln_label = Label(root, text = 'Second Name') ln_label.grid(row = 1, column = 0, padx = 10, pady = 10, sticky = W) self.ln_entry_value = StringVar(root, value = '') self.ln_entry = ttk.Entry(root, textvariable = self.ln_entry_value) self.ln_entry.grid(row = 1, column = 1, padx = 10, pady = 10, sticky = W) # Third Row self.submit_button = ttk.Button(root, text = "Submit", command=lambda: self.stud_submit()) self.submit_button.grid(row = 2, column = 0, padx = 10, pady = 10, sticky = W) self.update_button = ttk.Button(root, text = 'Update', command = lambda: self.update_student()) self.update_button.grid(row = 2, column = 1, padx = 10, pady = 10, sticky = W) self.ln_entry_value = StringVar(root, value = '') self.ln_entry = ttk.Entry(root, textvariable = self.ln_entry_value) self.ln_entry.grid(row = 1, column = 1, padx = 10, pady = 10, sticky = W) # Fourth Row scrollbar = Scrollbar(root) self.list_box = Listbox(root) self.list_box.bind('<<Listboxselect>>', self.load_student) self.list_box.insert(1, "students will appear Here") self.list_box.grid(row = 3, column = 0, columnspan = 4, padx = 10, pady = 10, sticky = W+E) # call for the database to be created self.setup_db() # Update the student Listbox with Students List self.update_listbox() root = Tk() studDB = StudentDB(root) root.mainloop()
a4a9e32f7db521e04c6d295c256854cf35240b55
[ "Python" ]
4
Python
AMOS2116/pythontutorial
13e3ed76e27991d50b8e8927f5da865856d749dd
809e7d25a9eb6be4caef555be42f68338ae5b8f4
refs/heads/master
<file_sep>#include "ukf.h" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /** * Initializes Unscented Kalman filter * This is scaffolding, do not modify */ UKF::UKF() { // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; // initial state vector x_ = VectorXd(5); // initial covariance matrix P_ = MatrixXd(5, 5); // Process noise standard deviation longitudinal acceleration in m/s^2 std_a_ = 1.5; // Process noise standard deviation yaw acceleration in rad/s^2 std_yawdd_ = 0.5; //DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer. // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer. /** TODO: Complete the initialization. See ukf.h for other member properties. Hint: one or more values initialized above might be wildly off... */ is_initialized_ = false; //Initialize for sigma points prediction n_x_ = 5; n_aug_ = n_x_ + 2; lambda_ = 3 - n_aug_; n_sig_ = 2 * n_aug_ + 1; Xsig_pred_ = MatrixXd(n_x_, n_sig_); weights_ = VectorXd(n_sig_); weights_(0) = lambda_ / (lambda_ + n_aug_); for (int i = 1; i < n_sig_; i++) { weights_(i) = 1 / (2 * (lambda_ + n_aug_)); } //Initialize for predicted measurements R_radar_ = MatrixXd(3, 3); R_radar_ << std_radr_ * std_radr_, 0, 0, 0, std_radphi_ * std_radphi_, 0, 0, 0, std_radrd_ * std_radrd_; R_laser_ = MatrixXd(2, 2); R_laser_ << std_laspx_ * std_laspx_, 0, 0, std_laspy_ * std_laspy_; H_laser_ = MatrixXd(2, n_x_); } UKF::~UKF() {} /** * @param {MeasurementPackage} meas_package The latest measurement data of * either radar or laser. */ void UKF::ProcessMeasurement(MeasurementPackage meas_package) { /** * TODO: * Complete this function! Make sure you switch between lidar and radar * measurements. */ /***************************************************************************** * Initialization ****************************************************************************/ if (!is_initialized_) { if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { double rho = meas_package.raw_measurements_[0]; // range double phi = meas_package.raw_measurements_[1]; // angular distance double rho_dot = meas_package.raw_measurements_[2]; // rate of change of rho double px = rho * cos(phi); double py = rho * sin(phi); double vx = rho_dot * cos(phi); double vy = rho_dot * sin(phi); double v = sqrt(vx * vx + vy * vy); x_ << px, py, 0, 0, 0; // x_ << px, py, v, phi, 0; } else if (meas_package.sensor_type_ == MeasurementPackage::LASER) { double px = meas_package.raw_measurements_[0]; double py = meas_package.raw_measurements_[1]; x_ << px, py, 0, 0, 0; } P_ << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 3; time_us_ = meas_package.timestamp_; // done initializing, no need to predict or update is_initialized_ = true; return; } /***************************************************************************** * Prediction ****************************************************************************/ double delta_t = (meas_package.timestamp_ - time_us_) / 1000000.0; time_us_ = meas_package.timestamp_; Prediction(delta_t); /***************************************************************************** * Update ****************************************************************************/ if ((meas_package.sensor_type_ == MeasurementPackage::RADAR) && (use_radar_)) { UpdateRadar(meas_package); } else if ((meas_package.sensor_type_ == MeasurementPackage::LASER) && (use_laser_)) { UpdateLidar(meas_package); } } /** * Predicts sigma points, the state, and the state covariance matrix. * @param {double} delta_t the change in time (in seconds) between the last * measurement and this one. */ void UKF::Prediction(double delta_t) { /** * TODO: * Complete this function! Estimate the object's location. Modify the state * vector, x_. Predict sigma points, the state, and the state covariance matrix. */ MatrixXd Xsig_aug = GenerateSigmaPoints(); PredictSigmaPoints(Xsig_aug, delta_t); PredictMeanAndCovariance(); } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { /** * TODO: * Complete this function! Use lidar data to update the belief about the object' * position. Modify the state vector, x_, and covariance, P_. * You'll also need to calculate the lidar NIS. */ H_laser_ << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0; VectorXd z_pred = H_laser_ * x_; VectorXd y = meas_package.raw_measurements_ - z_pred; MatrixXd Ht = H_laser_.transpose(); MatrixXd S = H_laser_ * P_ * Ht + R_laser_; MatrixXd Si = S.inverse(); MatrixXd PHt = P_ * Ht; MatrixXd K = PHt * Si; x_ = x_ + (K * y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K * H_laser_) * P_; //Calculating NIS NIS_laser_ = y.transpose() * S.inverse() * y; } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { /** * TODO: * Complete this function! Use radar data to update the belief about the object's * position. Modify the state vector, x_, and covariance, P_. * You'll also need to calculate the radar NIS. */ /***************************************************************************** * Predict Radar measurement ****************************************************************************/ //measurement dimension int n_z = 3; //matrix to store sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z, n_sig_); //matrix to store predicted sigma points VectorXd z_pred = VectorXd(n_z); //covariance matrix with predicted covariances MatrixXd S = MatrixXd(n_z, n_z); PredictRadarMeasurement(n_z, &Zsig, &z_pred, &S); /***************************************************************************** * Update states ****************************************************************************/ //Matrix to store cross correlation MatrixXd Tc = MatrixXd(n_x_, n_z); Tc.fill(0.0); for (int i = 0; i < n_sig_; i++) { VectorXd diff_state = Xsig_pred_.col(i) - x_; diff_state(3) = atan2(sin(diff_state(3)), cos(diff_state(3))); VectorXd diff_meas = Zsig.col(i) - z_pred; diff_meas(1) = atan2(sin(diff_meas(1)), cos(diff_meas(1))); Tc = Tc + weights_(i) * diff_state * diff_meas.transpose(); } MatrixXd K = Tc * S.inverse(); VectorXd diff_meas = meas_package.raw_measurements_ - z_pred; diff_meas(1) = atan2(sin(diff_meas(1)), cos(diff_meas(1))); x_ = x_ + K * diff_meas; P_ = P_ - K * S * K.transpose(); //Calculating NIS NIS_radar_ = diff_meas.transpose() * S.inverse() * diff_meas; } /** * Generate sigma points: * @return Xsig_aug: Generated sigma points */ MatrixXd UKF::GenerateSigmaPoints() { VectorXd x_aug_ = VectorXd(n_aug_); x_aug_.head(5) = x_; x_aug_(5) = 0; x_aug_(6) = 0; MatrixXd P_aug_ = MatrixXd(n_aug_, n_aug_); P_aug_.fill(0.0); P_aug_.topLeftCorner(5, 5) = P_; P_aug_(5, 5) = std_a_ * std_a_; P_aug_(6, 6) = std_yawdd_ * std_yawdd_; //create sigma point matrix MatrixXd Xsig_aug = MatrixXd(n_aug_, n_sig_); //calculate square root of P MatrixXd A = P_aug_.llt().matrixL(); Xsig_aug.col(0) = x_aug_; for (int i = 0; i < n_aug_; i++) { Xsig_aug.col(i + 1) = x_aug_ + sqrt(lambda_ + n_aug_) * A.col(i); Xsig_aug.col(i + 1 + n_aug_) = x_aug_ - sqrt(lambda_ + n_aug_) * A.col(i); } return Xsig_aug; } /** * This function generated the sigma points in the measurement space * @param Xsig_aug: Generated sigma points * @param delta_t: the change in time in sections between adjacent measurements */ void UKF::PredictSigmaPoints(MatrixXd Xsig_aug, double delta_t) { //predict sigma points for (int i = 0; i < n_sig_; i++) { //extract values for better readability double p_x = Xsig_aug(0, i); double p_y = Xsig_aug(1, i); double v = Xsig_aug(2, i); double yaw = Xsig_aug(3, i); double yawd = Xsig_aug(4, i); double nu_a = Xsig_aug(5, i); double nu_yawdd = Xsig_aug(6, i); //predicted state values double px_pred, py_pred; //avoid division by zero if (fabs(yawd) > 0.001) { px_pred = p_x + v / yawd * (sin(yaw + yawd * delta_t) - sin(yaw)); py_pred = p_y + v / yawd * (cos(yaw) - cos(yaw + yawd * delta_t)); } else { px_pred = p_x + v * delta_t * cos(yaw); py_pred = p_y + v * delta_t * sin(yaw); } double v_pred = v; double yaw_pred = yaw + yawd * delta_t; double yawd_pred = yawd; //add noise px_pred = px_pred + 0.5 * nu_a * delta_t * delta_t * cos(yaw); py_pred = py_pred + 0.5 * nu_a * delta_t * delta_t * sin(yaw); v_pred = v_pred + nu_a * delta_t; yaw_pred = yaw_pred + 0.5 * nu_yawdd * delta_t * delta_t; yawd_pred = yawd_pred + nu_yawdd * delta_t; //write predicted sigma point into right column Xsig_pred_(0, i) = px_pred; Xsig_pred_(1, i) = py_pred; Xsig_pred_(2, i) = v_pred; Xsig_pred_(3, i) = yaw_pred; Xsig_pred_(4, i) = yawd_pred; } } /** * This function generate the predicted the mean and covariance in the measurement space * based on the predicted sigma points */ void UKF::PredictMeanAndCovariance() { //Predicted state mean x_.fill(0.0); for (int i = 0; i < n_sig_; i++){ x_ = x_ + weights_(i) * Xsig_pred_.col(i); } //Predicted state covariance matrix P_.fill(0.0); for (int i = 0; i < n_sig_; i++) { VectorXd x_diff = Xsig_pred_.col(i) - x_; x_diff(3) = atan2(sin(x_diff(3)), cos(x_diff(3))); P_ = P_ + weights_(i) * x_diff * x_diff.transpose(); } } /** * Self explainatory, checks the rho value before the division * @param: rho as denominator * @return adjusted rho as dennominator */ double UKF::AvoidZeroDenominator(double denominator) { if (fabs(denominator) < 0.0001) { if (denominator > 0) { denominator += 0.0001; } else { denominator -= 0.0001; } } return denominator; } /** * This function generate the predicted radar measurement at t = k+1 with measurement data from * t = k * @param: n_z is the dimension for radar measurement (rho, phi, rho_dot) * @param: Zsig is the collection of sigma points in measurement space * @param: z_out is the collection of predicted sigma points in measurement spadce at t = k+1 * with measurements from t = k * @param: S_out is the predicted measurement covariance matrix at t = k+1 * with measurements from t = k */ void UKF::PredictRadarMeasurement(int n_z, MatrixXd *Zsig_out, VectorXd* z_out, MatrixXd* S_out) { MatrixXd Zsig = MatrixXd(n_z, n_sig_); VectorXd z_pred = VectorXd(n_z); MatrixXd S = MatrixXd(n_z, n_z); //converting predicted state space to measurement space for (int i = 0; i < n_sig_; i++) { double p_x = Xsig_pred_(0,i); double p_y = Xsig_pred_(1,i); double v = Xsig_pred_(2,i); double yaw = Xsig_pred_(3,i); double v_x = cos(yaw)*v; double v_y = sin(yaw)*v; double rho = sqrt(p_x*p_x + p_y*p_y); double phi = atan2(p_y,p_x); rho = AvoidZeroDenominator(rho); double rho_dot = (p_x*v_x + p_y*v_y ) / rho; Zsig(0, i) = rho; Zsig(1, i) = phi; Zsig(2, i) = rho_dot; } // Store predicted sigma points z_pred.fill(0.0); for (int i = 0; i < n_sig_; i++){ z_pred = z_pred + weights_(i) * Zsig.col(i); } // Create predicted covariances matrix S.fill(0.0); for (int i = 0; i < n_sig_; i++){ VectorXd z_diff = Zsig.col(i) - z_pred; z_diff(1) = atan2(sin(z_diff(1)), cos(z_diff(1))); S = S + weights_(i) * z_diff * z_diff.transpose(); } //add measurement noise covariance matrix S = S + R_radar_; *Zsig_out = Zsig; *z_out = z_pred; *S_out = S; }<file_sep># Unscented Kalman Filter Project Starter Code Self-Driving Car Engineer Nanodegree Program In this project utilize an Unscented Kalman Filter to estimate the state of a moving object of interest with noisy lidar and radar measurements. Passing the project requires obtaining RMSE values that are lower that the tolerance outlined in the project rubric. ## Basic Build Instructions 1. Clone this repo. 2. Make a build directory: `mkdir build && cd build` 3. Compile: `cmake .. && make` 4. Run it: `./UnscentedKF` Previous versions use i/o from text files. The current state uses i/o from the simulator. # Rubric Points ## Result: The result is generated based on the given sample data `obj_pose-laser-radar-synthetic-input.txt`. For data set 1: | `Data Set` | `RMSE X` | `RMSE Y` | `RMSE vx` | `RMSE vy` | |------------|----------|----------|-----------|-----------| | `1` | `0.0686` | `0.0814` | `0.3291` | `0.1890` | For data set 2: | `Data Set` | `RMSE X` | `RMSE Y` | `RMSE vx` | `RMSE vy` | |------------|----------|----------|-----------|-----------| | `2` | `0.0682` | `0.0688` | `0.3691` | `0.2060` | ## Algorithms: The general process flow can be found in the function `ProcessMeasurement` from the file `ukf.cpp` The function handles first measurement as following: <pre><code>if (!is_initialized_) { if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { double rho = meas_package.raw_measurements_[0]; // range double phi = meas_package.raw_measurements_[1]; // angular distance double rho_dot = meas_package.raw_measurements_[2]; // rate of change of rho double px = rho * cos(phi); double py = rho * sin(phi); double vx = rho_dot * cos(phi); double vy = rho_dot * sin(phi); double v = sqrt(vx * vx + vy * vy); x_ << px, py, 0, 0, 0; // x_ << px, py, v, phi, 0; } else if (meas_package.sensor_type_ == MeasurementPackage::LASER) { double px = meas_package.raw_measurements_[0]; double py = meas_package.raw_measurements_[1]; x_ << px, py, 0, 0, 0; } P_ << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 3; time_us_ = meas_package.timestamp_; // done initializing, no need to predict or update is_initialized_ = true; return; } </code></pre> Then it first predict then updates as follows: <pre><code> // Predict double delta_t = (meas_package.timestamp_ - time_us_) / 1000000.0; time_us_ = meas_package.timestamp_; Prediction(delta_t); // Update if ((meas_package.sensor_type_ == MeasurementPackage::RADAR) && (use_radar_)) { UpdateRadar(meas_package); } else if ((meas_package.sensor_type_ == MeasurementPackage::LASER) && (use_laser_)) { UpdateLidar(meas_package); } </code></pre> For specific implementation of lidar and radar update, please refer to the code in `ukf.cpp` at line 172 and 205 respectively.
b93df597a371e61fd22dbfeedbba224538b971b8
[ "Markdown", "C++" ]
2
C++
MaxwellFX/CarND-Unscented-Kalman-Filter-Project
603e4f3700c5bb99b6e729383af9e8ecb787a28e
3bad5f04cf24512ebb40fe582211ec0fb572eec4
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TicketShowcaseComponent } from './pages/ticket-showcase/ticket-showcase.component'; import { TicketShowcaseRoutingModule } from './ticket-showcase-routing.module'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptor } from '../../interceptors/auth-token.interceptor'; import { TicketShowcaseModalComponent } from './components/ticket-showcase-modal/ticket-showcase-modal.component'; import { TicketCurrentComponent } from './components/ticket-current/ticket-current.component'; @NgModule({ declarations: [ TicketShowcaseComponent, TicketShowcaseModalComponent, TicketCurrentComponent ], imports: [CommonModule, TicketShowcaseRoutingModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ] }) export class TicketShowcaseModule {} <file_sep>import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { TicketData } from '../../../../interfaces/ticket-data.interface'; @Component({ selector: 'app-ticket-showcase-modal', templateUrl: './ticket-showcase-modal.component.html', styleUrls: ['./ticket-showcase-modal.component.scss'] }) export class TicketShowcaseModalComponent implements OnInit { @Input() ticketData: TicketData; @Output() ticketClose: EventEmitter<TicketData> = new EventEmitter(); constructor() {} ngOnInit(): void {} ticketCloseHandler(): void { this.ticketClose.emit(); } } <file_sep>import {Component, OnInit} from '@angular/core'; import {AuthService} from './services/auth.service'; import {map, take} from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'showcase'; constructor(private authService: AuthService) { } ngOnInit(): void { this.authService.login() .pipe(take(1)) .subscribe(authData => { const token = authData.headers.get('x-auth-token'); localStorage.setItem('x-auth-token', token); }); } } <file_sep>import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { TicketData } from '../../../../interfaces/ticket-data.interface'; @Component({ selector: 'app-ticket-current', templateUrl: './ticket-current.component.html', styleUrls: ['./ticket-current.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class TicketCurrentComponent implements OnInit { @Input() ticketData: TicketData; @Output() openTicketModal: EventEmitter<TicketData> = new EventEmitter(); constructor() {} ngOnInit(): void {} openTicketModalHandler(): void { this.openTicketModal.emit(this.ticketData); } } <file_sep>import {Component, OnInit} from '@angular/core'; import {ForTicketService} from '../../../../services/for-ticket.service'; import {map} from 'rxjs/operators'; import {Observable} from 'rxjs'; import {TicketData} from '../../../../interfaces/ticket-data.interface'; @Component({ selector: 'app-ticket-showcase', templateUrl: './ticket-showcase.component.html', styleUrls: ['./ticket-showcase.component.scss'] }) export class TicketShowcaseComponent implements OnInit { tickets$: Observable<TicketData>; ticketDataOpened: TicketData; currentTicketData: TicketData; constructor(private forTicketService: ForTicketService) { } ngOnInit(): void { this.tickets$ = this.forTicketService.getTicketsFromApi() .pipe(map(data => data[0].events.map(event => { event.poster.path = 'https://img5.goodfon.com/original/1920x1200/2/9b/frozen-red-fantasy-nature-blizzard-beautiful-anime-wood-wi-1.jpg'; return event; } ))); } openTicketModal(data: TicketData): void { this.ticketDataOpened = data; } currentTicket(data: TicketData): void { this.currentTicketData = data; } closeTicketModal(event): void { this.ticketDataOpened = null; } } <file_sep>export interface TicketData { name: { ru: string; }; duration: string; date: string; poster: { path: string; }; description: { ru: string; }; } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TicketShowcaseComponent } from './pages/ticket-showcase/ticket-showcase.component'; const routes: Routes = [ { path: 'ticket-showcase', component: TicketShowcaseComponent }, // { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class TicketShowcaseRoutingModule { }
2544a7b4da1486b261a6f9b3e3f962be7ef027f6
[ "TypeScript" ]
7
TypeScript
antonstanov/showcase
dcb13fa7f93d53d02a6b9a2b53b8bea2c8e73dcb
5126f8d18c99a2fb6ff85ab726e94ad4cdde5a59
refs/heads/master
<repo_name>SRM-Hackathon/W0lf_pack<file_sep>/app/src/main/java/com/example/reglogin/activity.java package com.example.reglogin; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import java.util.Objects; public class activity extends AppCompatActivity { EditText emailsignup ,passsignup; Button signup; TextView loginsignup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activityy); emailsignup = findViewById(R.id.email_signup); passsignup = findViewById(R.id.pass_signup); signup = findViewById(R.id.btn_signup); loginsignup = findViewById(R.id.login_reg); FirebaseAuth mAuth = FirebaseAuth.getInstance(); signup.setOnClickListener(v -> mAuth.createUserWithEmailAndPassword(emailsignup.getText().toString(), passsignup.getText().toString()) .addOnCompleteListener(task -> { if(task.isSuccessful()) { mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { Toast.makeText(activity.this, "Please check your email for verification", Toast.LENGTH_LONG).show(); emailsignup.setText(""); passsignup.setText(""); } else { Toast.makeText(activity.this,task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(activity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_LONG).show(); } })); } public void login(View view) { Intent intent = new Intent(activity.this, MainActivity.class); startActivity(intent); finish(); } } <file_sep>/settings.gradle include ':app' rootProject.name='reglogin'
38736f3962cc85df16bfb61d1da776201b2e9b13
[ "Java", "Gradle" ]
2
Java
SRM-Hackathon/W0lf_pack
f4efcf9d8cabfc4318926bad55094a1f448f13f3
bf3dc03569a19c2068c2d3696fe7b4c482929a53
refs/heads/master
<file_sep>// // SavedEvents+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/9/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(SavedEvents) public class SavedEvents: NSManagedObject { } <file_sep>// // MyNewTeachers+CoreDataProperties.swift // PHS App // // Created by <NAME> on 1/6/19. // Copyright © 2019 Portola App Development. All rights reserved. // // import Foundation import CoreData extension MyNewTeachers { @nonobjc public class func fetchRequest() -> NSFetchRequest<MyNewTeachers> { return NSFetchRequest<MyNewTeachers>(entityName: "MyNewTeachers") } @NSManaged public var first: String? @NSManaged public var last: String? @NSManaged public var subject1: String? @NSManaged public var subject2: String? @NSManaged public var isFemale: Bool @NSManaged public var schedule: NSSet? } // MARK: Generated accessors for schedule extension MyNewTeachers { @objc(addScheduleObject:) @NSManaged public func addToSchedule(_ value: MySchedule) @objc(removeScheduleObject:) @NSManaged public func removeFromSchedule(_ value: MySchedule) @objc(addSchedule:) @NSManaged public func addToSchedule(_ values: NSSet) @objc(removeSchedule:) @NSManaged public func removeFromSchedule(_ values: NSSet) } <file_sep>// // NewsDetailViewController.swift // PHS App // // Created by <NAME> on 8/30/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import SDWebImage class NewsDetailViewController: UIViewController { @IBAction func actionTapped(_ sender: Any) { let ac = UIActivityViewController(activityItems: [storyURL!], applicationActivities: []) present(ac, animated: true) } @IBAction func dismiss(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var newsTitle: UILabel! @IBOutlet weak var newsInfo: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var content: UILabel! var titleText = String() var info = String() var imageLink: URL? var news = String() var storyLink = String() var storyURL: URL? override func viewDidLoad() { super.viewDidLoad() storyURL = URL(string: storyLink) navigationBar.my_setNavigationBar() newsTitle.text = titleText.uppercased() newsInfo.text = info.uppercased() imageView.sd_setImage(with: imageLink, placeholderImage: UIImage(named: "newsPlaceholder")) let newsFix = news.replacingOccurrences(of: "<p>", with: "<br><p>") let attributedText = try! NSAttributedString(data: newsFix.data(using: .unicode, allowLossyConversion: true)!, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil) content.text = attributedText.string // let attributedString = NSMutableAttributedString(string: content.text!) // let attributes: [NSAttributedStringKey: Any] = [.font: UIFont(name: "Lato-Regular", size: CGFloat(18).relativeToWidth), .foregroundColor: UIColor.blue] // // attributedString.addAttributes(attributes, range: NSRange(location: 0, length: 1)) // content.attributedText = attributedString } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // my_glowAnimation.swift // PHS App // // Created by <NAME> on 8/22/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit extension UIView { func my_glow() { let size = layer.frame.size.height self.layer.masksToBounds = false self.layer.shadowColor = UIColor.white.cgColor self.layer.shadowOffset = CGSize(width: size * 0.24, height: size * 0.24) self.layer.shadowRadius = size * 0.35 self.layer.shadowOpacity = 0.8 } func my_glowOnTap() { UIView.animate(withDuration: 0.25, delay: 0, animations: { self.alpha = 0.4 }) { (_) in UIView.animate(withDuration: 0.4, animations: { self.alpha = 1 }) } } } <file_sep>// // RSSParser.swift // PHS App // // Created by <NAME> on 8/29/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit class NewsArticle: NSObject { var title = String() var link = String() var pubDate = Date() var author = String() var category1 = String() var category2: String? var category3: String? var content = String() var image: UIImage? var imageLink: URL? } <file_sep>// // MyClasses+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension MyClasses { @nonobjc public class func fetchRequest() -> NSFetchRequest<MyClasses> { return NSFetchRequest<MyClasses>(entityName: "MyClasses") } @NSManaged public var period1: String? @NSManaged public var period2: String? @NSManaged public var period3: String? @NSManaged public var period4: String? @NSManaged public var period5: String? @NSManaged public var period6: String? @NSManaged public var period7: String? @NSManaged public var period8: String? } <file_sep>// // JoinViewController.swift // PHS App // // Created by <NAME> on 10/2/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class JoinViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var invitedLabel: UILabel! @IBOutlet weak var information: UILabel! @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var joinButton: UIView! let joinLabel = UILabel() @IBAction func backTapped(_ sender: Any) { dismiss(animated: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) UIView.animate(withDuration: 0.3) { self.joinButton.backgroundColor = UIColor.clear } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() joinButton.layer.cornerRadius = joinButton.bounds.height / 2 joinButton.layer.borderWidth = 1.5 joinButton.layer.borderColor = UIColor.black.cgColor joinLabel.bounds = joinButton.bounds joinLabel.center = CGPoint(x: joinButton.bounds.width / 2, y: joinButton.bounds.height / 2) joinLabel.textAlignment = .center joinLabel.textColor = UIColor.black joinLabel.text = "TALK TO US!" joinLabel.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth) joinButton.addSubview(joinLabel) let joinGesture = UITapGestureRecognizer(target: self, action: #selector(joinTapped)) joinGesture.delegate = self joinButton.addGestureRecognizer(joinGesture) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. invitedLabel.font = invitedLabel.font.withSize(invitedLabel.font.pointSize.relativeToWidth) information.font = information.font.withSize(information.font.pointSize.relativeToWidth.relativeToWidth) topConstraint.constant = topConstraint.constant.relativeToWidth } @objc func joinTapped() { UIView.animate(withDuration: 0.3, animations: { self.joinButton.backgroundColor = UIColor.lightGray }) { (_) in self.joinButton.backgroundColor = UIColor.clear } guard let url = URL(string: "https://forms.gle/TSarYRRYZ6pDjXVK6") else { return } UIApplication.shared.open(url) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // MyClasses+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(MyClasses) public class MyClasses: NSManagedObject { } <file_sep># Uncomment the next line to define a global platform for your project platform :ios, '10.0' target 'PHS App' do use_frameworks! # Pods for PHS App pod 'RSBarcodes_Swift' , '~> 4.2.0' pod 'Segmentio', '~> 3.0' pod 'ExpandableCell' pod 'TextFieldEffects' pod 'JTAppleCalendar', '~> 7.1' pod 'XLActionController' pod 'XLActionController/Skype' pod "SwiftyXMLParser" pod "SDWebImage", '~> 4.0' pod "PickerView" pod 'OneSignal', '>= 2.6.2', '< 3.0' pod 'Firebase/Core' pod 'Fabric', '~> 1.7.11' pod 'Crashlytics', '~> 3.10.7' pod 'Firebase/Messaging' target 'PHS AppTests' do inherit! :search_paths # Pods for testing end target 'PHS AppUITests' do inherit! :search_paths # Pods for testing end end target 'OneSignalNotificationServiceExtension' do use_frameworks! pod 'OneSignal', '>= 2.6.2', '< 3.0' end post_install do |installer| installer.pods_project.build_configurations.each do |config| config.build_settings.delete('CODE_SIGNING_ALLOWED') config.build_settings.delete('CODE_SIGNING_REQUIRED') end end <file_sep>// // HouseRankCollectionViewCell.swift // PHS App // // Created by <NAME> on 10/3/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class HouseRankCollectionViewCell: UICollectionViewCell { @IBOutlet weak var house: UILabel! @IBOutlet weak var points: UILabel! } <file_sep>// // TeachersViewController.swift // PHS App // // Created by <NAME> on 8/13/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import Segmentio import CoreData import CoreGraphics import ExpandableCell var fetchedTeachersCount = 0 var fetchedCoachesCount = 0 func fetchTeachers() { print("CALLED FETCHED TEACEHRS") if let data = Bundle.main.path(forResource: "teachersInfo", ofType: "txt") { if let content = try? String(contentsOfFile: data) { if let jsonData = JSON(parseJSON: content).dictionaryValue["teachers"]?.arrayValue { for member in jsonData { let detail = member.dictionaryObject! let object = NewTeachers() if let first = detail["first"] as? String { object.first = first } if let last = detail["last"] as? String { object.last = last } if let subject1 = detail["subject1"] as? String { object.subject1 = subject1 } if let subject2 = detail["subject2"] as? String { object.subject2 = subject2 } else { object.subject2 = nil } if let isFemale = detail["isFemale"] as? Bool { object.isFemale = isFemale } localTeachers.append(object) } } } } localTeachers = uniq(source: localTeachers) } func generateAlphaDict() { for teacher in localTeachers { let key = "\(teacher.last[(teacher.last.startIndex)])" let upper = key.uppercased() if var teacherInfo = teachersAlphaDict[upper] { teacherInfo.append(teacher) teachersAlphaDict[upper] = teacherInfo } else { teachersAlphaDict[upper] = [teacher] } } teachersAlphaSections = [String](teachersAlphaDict.keys) teachersAlphaSections = teachersAlphaSections.sorted() } func generateSubjectsDict() { for teacher in localTeachers { if teacher.subject2 != nil { var key = teacher.subject1 var key2 = teacher.subject2! if key == "Spanish" || key == "French" || key == "Chinese" { key = "World Language" } else if key == "Principal" || key == "Assistant Principal" || key == "Administrative Assistant" || key == "Lead Counselor" || key == "Athletic Director" { adminDictionary[teacher] = key adminRows.append(teacher) key = "Administration" } if key2 == "Spanish" || key2 == "French" || key2 == "Chinese" { key2 = "World Language" } else if key2 == "Principal" || key2 == "Assistant Principal" || key2 == "Administrative Assistnat" || key2 == "Lead Counselor" || key2 == "Athletic Director" { adminDictionary[teacher] = key adminRows.append(teacher) key2 = "Administration" } let upper = key.uppercased() let upper2 = key2.uppercased() if var teacherSubject = subjectsDictionary[upper] { teacherSubject.append(teacher) subjectsDictionary[upper] = teacherSubject } else { subjectsDictionary[upper] = [teacher] } if var teacherSubject2 = subjectsDictionary[upper2] { teacherSubject2.append(teacher) subjectsDictionary[upper2] = teacherSubject2 } else { subjectsDictionary[upper2] = [teacher] } } else { var key = teacher.subject1 if key == "Spanish" || key == "French" || key == "Chinese" { key = "World Language" } else if key == "Principal" || key == "Assistant Principal" || key == "Administrative Assistant" || key == "Lead Counselor" || key == "Athletic Director" { adminDictionary[teacher] = key adminRows.append(teacher) key = "Administration" } let upper = key.uppercased() if var teacherSubject = subjectsDictionary[upper] { teacherSubject.append(teacher) subjectsDictionary[upper] = teacherSubject } else { subjectsDictionary[upper] = [teacher] } } subjectsDictionary = subjectsDictionary.filter {$0.key != "ADMINISTRATION"} subjectsRows = subjectsRows.filter { $0 != "ADMINISTRATION" } subjectsRows = [String](subjectsDictionary.keys) subjectsRows = subjectsRows.sorted() } } var savedTeachers = [Teachers]() var localTeachers = [NewTeachers]() var teachersAlphaDict = [String: [NewTeachers]]() var teachersAlphaSections = [String]() var subjectsDictionary = [String: [NewTeachers]]() var subjectsRows = [String]() var adminDictionary = [NewTeachers: String]() var adminRows = [NewTeachers]() var savedCoaches = [Coaches]() var coachesTeamDictionary = [String: [Coaches]]() var coachesRows = [String]() var myClasses = [String?]() var masterSchedule = [MySchedule]() class TeachersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate { var underConstructionView = UnderConstructionView() @IBOutlet var navigationBar: UINavigationBar! @IBAction func dismiss(_ sender: Any) { dismiss(animated: true) } @IBOutlet var editButton: UIBarButtonItem! @IBAction func editTapped(_ sender: Any) { performSegue(withIdentifier: "editClasses", sender: nil) } @IBOutlet weak var segmentioView: Segmentio! var content = [SegmentioItem]() @IBOutlet weak var allTableView: UITableView! @IBOutlet weak var subjectsTableView: ExpandableTableView! @IBOutlet weak var adminTableView: UITableView! var coachesTableView = ExpandableTableView() @IBOutlet weak var noTeachersView: UIView! var fillTeachersButton = UIView() var fillInLabel = UILabel() var myTeachers = [MyNewTeachers]() var classesToDisplay = [String?]() var displaySchedule = [MySchedule]() var allTeachersCount = Int() var allCoachesCount = Int() var displayCoaches = Bool() @IBOutlet weak var myTeachersTableView: UITableView! func reload() { self.coachesTableView.reloadData() self.allTableView.reloadData() self.subjectsTableView.reloadData() self.adminTableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() setSegmentedControl() if localTeachers.count == 0 { fetchTeachers() } configrueTableViews() if teachersAlphaDict.count == 0 { generateAlphaDict() } if subjectsDictionary.count == 0 { generateSubjectsDict() } self.view.bringSubviewToFront(self.allTableView) let scheduleFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest() do { let request = try PersistentService.context.fetch(scheduleFetchRequest) if request.count > 0 { var scheduleArray = request scheduleArray.sort { $0.period < $1.period } masterSchedule = scheduleArray for entry in scheduleArray { myClasses.append(entry.name) } classesToDisplay = myClasses.filter { $0 != "Free Period" && $0 != "Sports" && $0 != "Sport" } displaySchedule = masterSchedule.filter {$0.name != "Free Period" && $0.name != "Sports" && $0.name != "Sport" } } else { myClasses = [] classesToDisplay = [] } } catch { } let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(fillInTapped)) gestureRecognizer.delegate = self fillTeachersButton.addGestureRecognizer(gestureRecognizer) segmentioView.selectedSegmentioIndex = 0 } @objc func fillInTapped() { performSegue(withIdentifier: "fillClasses", sender: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) segmentioView.valueDidChange = { segmentio, segmentIndex in switch segmentIndex { case 0: self.view.bringSubviewToFront(self.allTableView) case 1: self.view.bringSubviewToFront(self.subjectsTableView) case 2: self.view.bringSubviewToFront(self.adminTableView) case 3: if self.displayCoaches { self.view.bringSubviewToFront(self.coachesTableView) } else { self.view.bringSubviewToFront(self.underConstructionView) } default: print("more coming") } } } func setSegmentedControl() { let position = SegmentioPosition.dynamic let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white) let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none) let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)) segmentioView.selectedSegmentioIndex = 0 let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: ( defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)), selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white), highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white) ) ,animationDuration: 0.2) let allItem = SegmentioItem(title: "ALL", image: nil) let subjectsItem = SegmentioItem(title: "SUBJECTS", image: nil) let adminItem = SegmentioItem(title: "ADMIN", image: nil) content = [allItem, subjectsItem, adminItem] segmentioView.setup(content: content, style: .onlyLabel, options: options) } func configrueTableViews() { allTableView.delegate = self allTableView.dataSource = self subjectsTableView.expandableDelegate = self subjectsTableView.register(UINib(nibName: "SubjectsExpandableTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandableTableViewCell.ID) subjectsTableView.register(UINib(nibName: "SubjectsExpandedTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandedTableViewCell.ID) adminTableView.delegate = self adminTableView.dataSource = self coachesTableView.expandableDelegate = self coachesTableView.animation = .automatic coachesTableView.register(UINib(nibName: "SubjectsExpandableTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandableTableViewCell.ID) coachesTableView.register(UINib(nibName: "SubjectsExpandedTableViewCell", bundle: nil), forCellReuseIdentifier: SubjectsExpandedTableViewCell.ID) fillTeachersButton.frame = CGRect(x: 0, y: 0, width: CGFloat(250).relativeToWidth, height: CGFloat(50).relativeToWidth) fillTeachersButton.center = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.height / 2 - CGFloat(100).relativeToWidth) fillTeachersButton.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) fillTeachersButton.layer.cornerRadius = CGFloat(25).relativeToWidth fillInLabel.bounds = CGRect(x: 0, y: 0, width: fillTeachersButton.bounds.width, height: fillTeachersButton.bounds.height) fillInLabel.center = CGPoint(x: fillTeachersButton.bounds.width / 2, y: fillTeachersButton.bounds.height / 2) fillInLabel.text = "FILL IN YOUR SCHEDULE" fillInLabel.textAlignment = .center fillInLabel.font = UIFont(name: "Lato-Bold", size: CGFloat(17).relativeToWidth) fillInLabel.textColor = UIColor.white fillTeachersButton.addSubview(fillInLabel) fillTeachersButton.my_dropShadow() myTeachersTableView.delegate = self myTeachersTableView.dataSource = self } func numberOfSections(in tableView: UITableView) -> Int { if tableView == allTableView { return teachersAlphaSections.count } else if tableView == adminTableView { return 1 } else if tableView == myTeachersTableView { return 1 } return 0 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView == allTableView { return teachersAlphaSections[section] } return nil } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView == allTableView { return CGFloat(40).relativeToWidth } return 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if tableView == allTableView { let headerView = UIView() headerView.backgroundColor = UIColor(red:0.99, green:0.95, blue:1.00, alpha:1.0) let headerLabel = UILabel(frame: CGRect(x: CGFloat(30).relativeToWidth, y: CGFloat(5).relativeToWidth, width: allTableView.bounds.size.width, height: self.tableView(tableView, heightForHeaderInSection: section))) headerLabel.font = UIFont(name: "Lato-Bold", size: CGFloat(22).relativeToWidth) headerLabel.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) headerLabel.text = self.tableView(tableView, titleForHeaderInSection: section) headerLabel.sizeToFit() headerView.addSubview(headerLabel) return headerView } return nil } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == allTableView { let teacherKey = teachersAlphaSections[section] if let teacherValues = teachersAlphaDict[teacherKey] { return teacherValues.count } } else if tableView == adminTableView { return adminRows.count } else if tableView == myTeachersTableView { return displaySchedule.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("AllTableViewControllerCellTableViewCell", owner: self, options: nil)?.first as! AllTableViewControllerCellTableViewCell if tableView == allTableView { let teacherKey = teachersAlphaSections[indexPath.section] if let teacherValues = teachersAlphaDict[teacherKey.uppercased()] { let teacher = teacherValues[indexPath.row] cell.first = teacher.first cell.last = teacher.last cell.gender = teacher.isFemale cell.name.text = "\(teacher.first.uppercased()) \(teacher.last.uppercased())" cell.name.font = cell.name.font.withSize(CGFloat(16).relativeToWidth) if teacher.subject2 != nil { cell.subject.text = "\(teacher.subject1.uppercased()) & \(teacher.subject2!.uppercased())" } else { cell.subject.text = "\(teacher.subject1.uppercased())" } cell.subject.font = cell.subject.font.withSize(CGFloat(16).relativeToWidth.relativeToWidth) cell.initialsLabel.text = "\(Array(teacher.first)[0])\(Array(teacher.last)[0])" cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(19).relativeToWidth) return cell } } else if tableView == adminTableView { let admin = adminRows[indexPath.row] var role = String() if admin.subject1 == "Principal" || admin.subject1 == "Assistant Principal" || admin.subject1 == "Lead Counselor" || admin.subject1 == "Athletic Director" || admin.subject1 == "Administrative Assistant" { role = admin.subject1.uppercased() } else { role = (admin.subject2?.uppercased())! } cell.first = admin.first cell.last = admin.last cell.gender = admin.isFemale cell.name.text = "\(admin.first.uppercased()) \(admin.last.uppercased())" cell.name.font = cell.name.font.withSize(CGFloat(16).relativeToWidth) cell.initialsLabel.text = "\(Array(admin.first)[0])\(Array(admin.last)[0])" cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(19).relativeToWidth) cell.subject.text = role return cell } else if tableView == myTeachersTableView { let myCell = Bundle.main.loadNibNamed("MyTeachersTableViewCell", owner: self, options: nil)?.first as! MyTeachersTableViewCell if displaySchedule.count != 0 { let schedule = displaySchedule[indexPath.row] myCell.first = schedule.teacher!.first! myCell.last = schedule.teacher!.last! myCell.gender = schedule.teacher!.isFemale myCell.initialsLabel.text = "\(Array(myCell.first)[0])\(Array(myCell.last)[0])" myCell.teacherLabel.text = "\(myCell.first.uppercased()) \(myCell.last.uppercased())" myCell.periodLabel.text = "PERIOD \(schedule.period)" myCell.classLabel.text = schedule.name! } return myCell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView == myTeachersTableView { return CGFloat(80) } return CGFloat(70).relativeToWidth } func sectionIndexTitles(for tableView: UITableView) -> [String]? { if tableView == allTableView { allTableView.sectionIndexColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) return teachersAlphaSections } return nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "fillClasses" { if let vc = segue.destination as? PickClassesViewController { vc.isFreshLaunch = false vc.isPrevButtonHidden = true } } else if segue.identifier == "editClasses" { if let vc = segue.destination as? PickClassesViewController { vc.isPageEditing = true vc.isFreshLaunch = false vc.isPrevButtonHidden = true vc.mySelectedTeachers = self.myTeachers vc.periods = myClasses } } } @IBAction func skipFromSecondScreen(segue: UIStoryboardSegue) { if segue.identifier == "skipFromSecondScreen" { print("skipped from second page") } } @IBAction func newInfoSaved(segue: UIStoryboardSegue) { if segue.identifier == "newInfoSaved" { if let vc = segue.source as? PickTeachersViewController { for i in 0...7 { let newSchedule = MySchedule(context: PersistentService.context) newSchedule.name = vc.classes[i] newSchedule.period = Int16(i + 1) let newTeacher = MyNewTeachers(context: PersistentService.context) let currentTeacher = vc.myTeachers[i] newTeacher.first = currentTeacher?.first newTeacher.last = currentTeacher?.last newTeacher.subject1 = currentTeacher?.subject1 newTeacher.subject2 = currentTeacher?.subject2 newTeacher.isFemale = currentTeacher?.isFemale ?? false newSchedule.teacher = newTeacher PersistentService.saveContext() } } fetchAndReload(withClasses: true) navigationBar.topItem?.rightBarButtonItem = editButton } } @IBAction func unwindToTeacherPage(segue: UIStoryboardSegue) { if segue.identifier == "unwindToTeacherPage" { if let vc = segue.source as? PickTeachersViewController { let scheduleFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest() let teacherFetchRequest: NSFetchRequest<MyNewTeachers> = MyNewTeachers.fetchRequest() do { let request = try PersistentService.context.fetch(scheduleFetchRequest) let teacherRequest = try PersistentService.context.fetch(teacherFetchRequest) var requestSort = request requestSort.sort {$0.period < $1.period} for i in 0...requestSort.count - 1 { print(requestSort[i].name) } for i in 0...teacherRequest.count - 1 { print(teacherRequest[i].first) } var tracker = 0 for i in 0...7 { let object = requestSort[i] object.setValue(vc.classes[i], forKey: "name") object.setValue(Int16(i + 1), forKey: "period") if vc.classes[i] == "Sports" || vc.classes[i] == "Free Period" { object.setValue(nil, forKey: "teacher") } else { if tracker > teacherRequest.count - 1 { let newTeacher = MyNewTeachers(context: PersistentService.context) let currentTeacher = vc.myTeachers[i] newTeacher.first = currentTeacher?.first newTeacher.last = currentTeacher?.last newTeacher.subject1 = currentTeacher?.subject1 newTeacher.subject2 = currentTeacher?.subject2 newTeacher.isFemale = currentTeacher?.isFemale ?? false object.setValue(newTeacher, forKey: "teacher") } else { let newTeacher = teacherRequest[tracker] let currentTeacher = vc.myTeachers[i] newTeacher.setValue(currentTeacher?.first, forKey: "first") newTeacher.setValue(currentTeacher?.last, forKey: "last") newTeacher.setValue(currentTeacher?.subject1, forKey: "subject1") newTeacher.setValue(currentTeacher?.subject2, forKey: "subject2") newTeacher.setValue(currentTeacher?.isFemale, forKey: "isFemale") object.setValue(newTeacher, forKey: "teacher") } tracker += 1 } PersistentService.saveContext() } } catch { } } fetchAndReload(withClasses: true) navigationBar.topItem?.rightBarButtonItem = editButton } } func fetchAndReload(withClasses: Bool) { let scheduleFetch: NSFetchRequest<MySchedule> = MySchedule.fetchRequest() do { let request = try PersistentService.context.fetch(scheduleFetch) masterSchedule = request masterSchedule.sort { $0.period < $1.period } } catch { } displaySchedule = masterSchedule.filter {$0.name != "Free Period" && $0.name != "Sports" && $0.name != "Sport" } view.bringSubviewToFront(myTeachersTableView) for item in displaySchedule { myTeachers.append(item.teacher!) } myTeachersTableView.reloadData() } } extension TeachersViewController: ExpandableDelegate { func numberOfSections(in expandableTableView: ExpandableTableView) -> Int { return 1 } func expandableTableView(_ expandableTableView: ExpandableTableView, numberOfRowsInSection section: Int) -> Int { if expandableTableView == subjectsTableView { return subjectsRows.count } else if expandableTableView == coachesTableView { return coachesRows.count } return 1 } func expandableTableView(_ expandableTableView: ExpandableTableView, expandedCellsForRowAt indexPath: IndexPath) -> [UITableViewCell]? { if expandableTableView == subjectsTableView { let department = subjectsRows[indexPath.row] var expandedArray = [SubjectsExpandedTableViewCell]() if let teachers = subjectsDictionary[department] { for teacher in teachers { let cell = subjectsTableView.dequeueReusableCell(withIdentifier: SubjectsExpandedTableViewCell.ID) as! SubjectsExpandedTableViewCell cell.first = teacher.first cell.last = teacher.last cell.gender = teacher.isFemale cell.email = nil cell.nameLabel.text = "\(teacher.first.uppercased()) \(teacher.last.uppercased())" cell.nameLabel.font = cell.nameLabel.font.withSize(CGFloat(16).relativeToWidth) cell.initialsLabel.text = "\(Array(teacher.first)[0])\(Array(teacher.last)[0])" cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(16).relativeToWidth) expandedArray.append(cell) } return expandedArray } else { return nil } } else if expandableTableView == coachesTableView { let team = coachesRows[indexPath.row] var expandedArray = [SubjectsExpandedTableViewCell]() if let coaches = coachesTeamDictionary[team] { for coach in coaches { let cell = subjectsTableView.dequeueReusableCell(withIdentifier: SubjectsExpandedTableViewCell.ID) as! SubjectsExpandedTableViewCell cell.first = coach.first ?? " " cell.last = coach.last ?? " " cell.email = coach.email cell.gender = coach.gender cell.nameLabel.text = "\(coach.first?.uppercased() ?? "") \(coach.last?.uppercased() ?? "")" cell.nameLabel.font = cell.nameLabel.font.withSize(CGFloat(16).relativeToWidth) cell.initialsLabel.text = "\(Array(coach.first!)[0])\(Array(coach.last!)[0])" cell.initialsLabel.font = cell.initialsLabel.font.withSize(CGFloat(16).relativeToWidth) expandedArray.append(cell) } return expandedArray } else { return nil } } return nil } func expandableTableView(_ expandableTableView: ExpandableTableView, heightsForExpandedRowAt indexPath: IndexPath) -> [CGFloat]? { var heightArray = [CGFloat]() if expandableTableView == subjectsTableView { if let teachers = self.expandableTableView(expandableTableView, expandedCellsForRowAt: indexPath){ for _ in teachers { heightArray.append(CGFloat(65).relativeToWidth) } return heightArray } else { return nil } } else if expandableTableView == coachesTableView { if let coaches = self.expandableTableView(expandableTableView, expandedCellsForRowAt: indexPath) { for _ in coaches { heightArray.append(CGFloat(65).relativeToWidth) } return heightArray } else { return nil } } return nil } func expandableTableView(_ expandableTableView: ExpandableTableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(50).relativeToWidth } func expandableTableView(_ expandableTableView: ExpandableTableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = subjectsTableView.dequeueReusableCell(withIdentifier: SubjectsExpandableTableViewCell.ID) as! SubjectsExpandableTableViewCell if expandableTableView == subjectsTableView { cell.subjectLabel.text = subjectsRows[indexPath.row] cell.subjectLabel.font = cell.subjectLabel.font.withSize(CGFloat(20).relativeToWidth) return cell } else if expandableTableView == coachesTableView { cell.subjectLabel.text = coachesRows[indexPath.row] cell.subjectLabel.font = cell.subjectLabel.font.withSize(CGFloat(20).relativeToWidth) return cell } return cell } func expandableTableView(_ expandableTableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return true } } <file_sep>// // GameScheduleTableViewCell.swift // PHS App // // Created by <NAME> on 8/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import EventKit import EventKitUI import UserNotifications class GameScheduleTableViewCell: UITableViewCell { @IBOutlet weak var gameResultView: UIView! @IBOutlet weak var homeScore: UILabel! @IBOutlet weak var awayScore: UILabel! @IBOutlet weak var awayTeam: UILabel! @IBOutlet weak var homeTeam: UILabel! @IBOutlet weak var gameScheduleView: UIView! @IBOutlet weak var awayTeamSchedule: UILabel! @IBOutlet weak var bell: UIImageView! @IBOutlet weak var bellOutline: UIImageView! @IBOutlet weak var calendar: UIImageView! @IBOutlet weak var date: UILabel! @IBOutlet weak var weekday: UILabel! @IBOutlet weak var time: UILabel! @IBOutlet weak var isAway: UILabel! var notification = false var sport = String() var gameTime = Date() var otherTeam = String() let store = EKEventStore() var identifier = String() override func awakeFromNib() { super.awakeFromNib() bell.alpha = 0 let labels: [UILabel] = [homeScore, awayScore, awayTeam, homeTeam, awayTeamSchedule, date, weekday, time, isAway] for label in labels { label.font = label.font.withSize(label.font.pointSize.relativeToWidth) } bellOutline.isUserInteractionEnabled = true calendar.isUserInteractionEnabled = true let bellGesture = UITapGestureRecognizer(target: self, action: #selector(bellTapped)) bellGesture.delegate = self bellOutline.addGestureRecognizer(bellGesture) let calendarGesture = UITapGestureRecognizer(target: self, action: #selector(calendarTapped)) calendarGesture.delegate = self calendar.addGestureRecognizer(calendarGesture) } @objc func bellTapped() { notification = !notification if self.notification { UIView.animate(withDuration: 0.3) { self.bell.alpha = 1 } self.scheduleLocal() } else { UIView.animate(withDuration: 0.3) { self.bell.alpha = 0 } UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier]) } } @objc func calendarTapped() { let endTime = Calendar.current.date(byAdding: .hour, value: 1, to: gameTime)! createEventinTheCalendar(with: "\(sport) vs \(otherTeam)", forDate: gameTime, toDate: endTime) } func createEventinTheCalendar(with title: String, forDate eventStartDate: Date, toDate eventEndDate: Date) { store.requestAccess(to: .event) { (success, error) in if error == nil { let event = EKEvent.init(eventStore: self.store) event.title = title event.calendar = self.store.defaultCalendarForNewEvents event.startDate = eventStartDate event.endDate = eventEndDate let alarm = EKAlarm.init(absoluteDate: Date.init(timeInterval: -3600, since: event.startDate)) event.addAlarm(alarm) do { try self.store.save(event, span: .thisEvent) let ac = UIAlertController(title: "Saved Successfully", message: "We have saved this game to your calendar.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.parentViewController?.present(ac, animated: true) } catch { let ac = UIAlertController (title: "Could not save evnent", message: "There was an error saving your event, go to settings to double-check calendar usage permission.?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in }) } } ac.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) ac.addAction(cancelAction) self.parentViewController?.present(ac, animated: true, completion: nil) } } else { //we have error in getting access to device calnedar self.setAlertController(title: "Could not save evnent", message: "There was an error saving your event, go to settings to double-check calendar usage permission.", preferredStyle: .alert, actionTitle: "OK") } } } func scheduleLocal() { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in if granted { print(self.gameTime) let dateComponents = Calendar.current.dateComponents([.minute, .hour, .day, .month, .year], from: self.gameTime) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) // let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let content = UNMutableNotificationContent() content.title = "\(self.sport) vs \(self.otherTeam)" content.body = "\(self.sport)'s will play \(self.otherTeam) soon, go to the game and show your support!" content.sound = UNNotificationSound.default let request = UNNotificationRequest(identifier: self.identifier, content: content, trigger: trigger) center.add(request) } else { let ac = UIAlertController (title: "No Permission", message: "We do not have permission to send you notifications, would you like to change that in settings?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in }) } } ac.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) ac.addAction(cancelAction) self.parentViewController?.present(ac, animated: true, completion: nil) } } } func setAlertController(title: String, message: String?, preferredStyle: UIAlertController.Style, actionTitle: String) { let ac = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) ac.addAction(UIAlertAction(title: actionTitle, style: .default, handler: nil)) self.parentViewController?.present(ac, animated: true) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // DayType+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/10/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(DayType) public class DayType: NSManagedObject { } <file_sep>// // UpcomingGamesCollectionViewCell.swift // PHS App // // Created by <NAME> on 8/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class UpcomingGamesCollectionViewCell: UICollectionViewCell { @IBOutlet weak var team: UILabel! @IBOutlet weak var location: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var purpleCircle: UIView! @IBOutlet weak var P: UILabel! @IBOutlet weak var grayCircle: UIView! @IBOutlet weak var awayInitial: UILabel! @IBOutlet weak var PortolaLabel: UILabel! @IBOutlet weak var awayLabel: UILabel! } <file_sep>// // FirstScanViewController.swift // PHS App // // Created by <NAME> on 8/19/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import RSBarcodes_Swift import AVFoundation class FirstScanViewController: RSCodeReaderViewController { @IBOutlet weak var frameView: UIView! @IBAction func buttonTapped(_ sender: Any) { longID = nil performSegue(withIdentifier: "backToID", sender: nil) } var longID: String? var shouldReturn = true override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == AVAuthorizationStatus.authorized { //continue } else { AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in if granted == true { } else { let ac = UIAlertController (title: "No Camera Usage Permission", message: "You have denied the app's camera usage, please go to settings to double-check camera usage permission.?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in }) } } ac.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (_) in self.dismiss(animated: true) }) ac.addAction(cancelAction) self.present(ac, animated: true, completion: nil) } }) } } override func viewDidLoad() { super.viewDidLoad() frameView.backgroundColor = UIColor.white.withAlphaComponent(0) frameView.layer.borderColor = UIColor.white.cgColor frameView.layer.borderWidth = 2 self.focusMarkLayer.strokeColor = UIColor.yellow.cgColor self.cornersLayer.strokeColor = UIColor.yellow.cgColor self.barcodesHandler = { barcodes in let barcode = barcodes.first! if self.shouldReturn { self.longID = barcode.stringValue! DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: { self.performSegue(withIdentifier: "backToID", sender: nil) }) } self.shouldReturn = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // HouseCollectionViewCell.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class HouseCollectionViewCell: UICollectionViewCell { var label = UILabel() var roundedRect = UIView() } <file_sep>// // my_notificationPrompt.swift // PHS App // // Created by <NAME> on 8/29/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func my_notificationPrompt(type: Int) -> String { switch type { case 0: return "nothing" case 1: //pep assembly odd return "There is a pep assembly tomorrow. School starts at 8:00 and ends at 3:30." case 2: //pep assembly even return "There is a pep assembly tomorrow. School starts at 8:00 and ends at 3:30." case 3: //extended lunch odd return "There is an extended lunch tomorrow, lunch will be 49 minutes long from 11:33 to 12:22." case 4: //extended lunch even return "There is an extended lunch tomorrow, lunch will be 49 minutes long from 11:33 to 12:22." case 5: //finals type 1 return "Tomorrow is Finals, you will have 1st, 3rd and 7th period. School will start at 8:00 and end at 12:29." case 6: //finals type 2 return "Tomorrow is Finals, you will have 2st, 4th and 8th period. School will start at 8:00 and end at 12:29." case 7: //finals two periods return "Tomorrow is Finals, you will have 5th and 6th period. School will start at 8:00 and end at 11:00." case 8: //minimum 1-8 return "Tomorrow is minimum day, you will have period 1-8. School will start at 8:00 and end at 12:28." case 9: //conferences odd return "Tomorrow is minimum day, you will have odd periods. School will start at 8:00 and end at 12:28." case 10: //conferences even return "Tomorrow is minimum day, you will have even periods. School will start at 8:00 and end at 12:28." case 11: //PSAT 9 return "Tomorrow is freshmen PSAT. Freshmen will start testing at 8:00 and Sophomores & Juniors will start at 11:20. You will have odd periods." case 12: //PE testing return "Tomorrow is freshmen PE Testing. Freshmen will start testing at 8:30 and Sophomores & Juniors will start at 11:20. You will have odd periods." case 13: //first 2 days of school return "passed" case 14: // hour of code return "Tomorrow is hour of code. You will have advisement instead of office hours." case 15: //Passion Day return "Tomorrow is passion day. School will start at 8:00and end at 2:31." case 16: //Pre Testing return "Tomorrow is pre-testing schedule. School will start at 8:30, you will have period 1, 2, 3, 5 and 7." case 17: //Testing return "Tomorrow is sophomores and juniors testing. School will start at 8:00 for sophomores and juniors, and 11:30 for freshmen." case 18: //CAASPP odd return "Tomorrow is juniors CAASPP testing. School will start at 8:00 for juniors and 11:20 for freshmen and sophomores. You will have odd periods." case 19: //CAASPP even return "Tomorrow is juniors CAASPP testing. School will start at 8:00 for juniors and 11:20 for freshmen and sophomores. You will have even periods." case 20: //NO SCHOOL return "No school tomorrow! Enjoy your day off!" case 21: //fine arts assembly return "Tomorrow is fine arts assembly. School will start at 8:00 and end at 3:30." case 22: //monday schedule return "Tomorrow we will have Monday schedule." case 23: //tuesday schedule return "Tomorrow we will have Tuesday schedule." case 24: //wednesday schedule return "Tomorrow we will have Wednesday schedule." case 25: //thursday schedule return "Tomorrow we will have Thursday schedule." case 26: //friday schedule return "Tomorrow we will have Friday schedule." default: return "nothing" } } <file_sep>// // my_numOfMinDuringSchool.swift // PHS App // // Created by <NAME> on 8/4/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func numOfMinAtSchool(type: Int) -> Int? { let schedule = my_getSchedule(type: type, date: nil) if type == 20 { return nil } else { if Calendar.current.component(.weekday, from: Date()) == 1 || Calendar.current.component(.weekday, from: Date()) == 7 { return nil } else { let start = schedule!.first! let end = schedule!.last! if let interval = Calendar.current.dateComponents([.minute], from: start, to: end).minute { return interval } else { return nil } } } } <file_sep>// // my_getWeekdayString.swift // PHS App // // Created by <NAME> on 7/29/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func getWeekdayString(date: Date, isUpper: Bool) -> String { let weekday = Calendar.current.component(.weekday, from: date) if isUpper { switch weekday { case 1: return "SUNDAY" case 2: return "MONDAY" case 3: return "TUESDAY" case 4: return "WEDNESDAY" case 5: return "THURSDAY" case 6: return "FRIDAY" case 7: return "SATURDAY" default: return "COMING UP" } } else { switch weekday { case 1: return "Sunday" case 2: return "Monday" case 3: return "Tuesday" case 4: return "Wednesday" case 5: return "Thursday" case 6: return "Friday" case 7: return "Satueday" default: return "Coming Up" } } } <file_sep>// // AthleticsCollectionViewCell.swift // PHS App // // Created by <NAME> on 8/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class AthleticsCollectionViewCell: UICollectionViewCell { @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var iconLabel: UILabel! } <file_sep>// // AllTableViewControllerCellTableViewCell.swift // PHS App // // Created by <NAME> on 8/16/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreGraphics import MessageUI class AllTableViewControllerCellTableViewCell: UITableViewCell, MFMailComposeViewControllerDelegate { @IBOutlet weak var initialsLabel: UILabel! @IBOutlet weak var name: UILabel! @IBOutlet weak var subject: UILabel! @IBOutlet weak var email: UIImageView! @IBOutlet weak var circleImageView: UIImageView! var first = String() var last = String() var gender = Bool() override func awakeFromNib() { super.awakeFromNib() let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(emailTapped)) gestureRecognizer.delegate = self email.addGestureRecognizer(gestureRecognizer) let renderer = UIGraphicsImageRenderer(size: CGSize(width: self.frame.height * 0.9, height: self.frame.height * 0.9)) let img = renderer.image { ctx in ctx.cgContext.setFillColor(UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor) ctx.cgContext.setStrokeColor(UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor) ctx.cgContext.setLineWidth(1) let rectangle = CGRect(x: 1, y: 1, width: self.frame.height * 0.8, height: self.frame.height * 0.8) ctx.cgContext.addEllipse(in: rectangle) ctx.cgContext.drawPath(using: .fillStroke) } circleImageView.image = img circleImageView.my_dropShadow() initialsLabel.my_dropShadow() } @objc func emailTapped() { let trimmedLast = last.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: " ", with: "") let address = "\(first)\(trimmedLast)@<EMAIL>" sendEmail(address: address, isFemale: gender, lastName: last) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func sendEmail(address: String, isFemale: Bool, lastName: String) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients([address]) var title = String() if isFemale { title = "Ms." } else { title = "Mr." } mail.setMessageBody("<p>Hello, \(title) \(lastName), <br><br><br> <br>Sincerely,</p>", isHTML: true) self.parentViewController?.present(mail, animated: true) } else { } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { self.parentViewController?.dismiss(animated: true) } } <file_sep>// // my_schoolTime.swift // PHS App // // Created by <NAME> on 10/22/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension Date { func timeOfSchoolDay() -> relativeTime? { if self.isSchoolDay() { let type = getDayType(date: self) let startTime = my_getSchedule(type: type, date: self)!.first! let endTime = my_getSchedule(type: type, date: self)!.last! if self.localTime() < startTime { return .before } else if self.localTime() > endTime { return .after } else { return .during } } else { return nil } } } <file_sep>// // my_getStartEndTimeFromToday.swift // PHS App // // Created by <NAME> on 7/31/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func my_getStartEndTimeFromToday(type: Int, dayType: dayType, date: Date?) -> [Date] { switch type { case 0: return defaultDaysStartEnd(dayType: dayType, date: date) case 1, 2, 3, 4, 11, 13, 14, 17, 18, 19, 21: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30)] case 5, 6: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 12, minute: 29)] case 7: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 11, minute: 00)] case 8, 9, 10: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 12, minute: 28)] case 15: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 12, minute: 10)] case 12, 16: return [DateFromTime(hour: 8, minute: 30), DateFromTime(hour: 15, minute: 30)] case 20: return [Date()] case 22, 24, 25, 27: //8 am start regular return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30) ] case 23, 26, 28: //8:30 am start regular return [DateFromTime(hour: 8, minute: 30), DateFromTime(hour: 15, minute: 30) ] case 29: return [DateFromTime(hour: 10, minute: 30), DateFromTime(hour: 15, minute: 30)] default: return defaultDaysStartEnd(dayType: dayType, date: date) } } func defaultDaysStartEnd(dayType: dayType, date: Date?) -> [Date] { var weekday = Int() switch dayType { case .today: weekday = Calendar.current.component(.weekday, from: Date()) case .tomorrow: weekday = Calendar.current.component(.weekday, from: Date()) + 1 case .nextMonday: weekday = 0 case .custom: weekday = Calendar.current.component(.weekday, from: date!) } switch weekday { case 1, 2, 7, 4, 5: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30)] case 3, 6: return [DateFromTime(hour: 8, minute: 30), DateFromTime(hour: 15, minute: 30)] default: return [DateFromTime(hour: 8, minute: 0), DateFromTime(hour: 15, minute: 30)] } } func DateFromTime(hour: Int, minute: Int) -> Date { var dateComponents = DateComponents() dateComponents.timeZone = Calendar.current.timeZone dateComponents.year = Calendar.current.component(.year, from: Date().noon) dateComponents.month = Calendar.current.component(.month, from: Date().noon) dateComponents.day = Calendar.current.component(.day, from: Date().noon) dateComponents.hour = hour + UTCDifference() dateComponents.minute = minute let userCalendar = Calendar.current if let milDate = userCalendar.date(from: dateComponents)?.timeIntervalSince1970 { return Date(timeIntervalSince1970: milDate) } return Date() } <file_sep>// // Today+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/8/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension Today { @nonobjc public class func createFetchRequest() -> NSFetchRequest<Today> { return NSFetchRequest<Today>(entityName: "Today") } @NSManaged public var todayType: Int32 @NSManaged public var tomorrowType: Int32 @NSManaged public var nextMondayType: Int32 @NSManaged public var day: Int32 } <file_sep>// // GradeCollectionViewCell.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class GradeCollectionViewCell: UICollectionViewCell { var label = UILabel() var circle = UIView() } <file_sep>// // File.swift // PHS App // // Created by <NAME> on 8/4/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit extension UIView { func viewFadeIn() { UIView.animate(withDuration: 0.5) { self.alpha = 1 } } func viewFadeOut() { UIView.animate(withDuration: 0.5) { self.alpha = 0 } } } <file_sep>// // PickClassesViewController.swift // PHS App // // Created by <NAME> on 8/19/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreData class PickClassesViewController: UIViewController { @IBOutlet weak var prevButton: UIButton! @IBAction func prevTapped(_ sender: Any) { let _ = navigationController?.popViewController(animated: true) } @IBOutlet weak var yourClasses: UILabel! @IBOutlet weak var p1Label: UILabel! @IBOutlet weak var p2Label: UILabel! @IBOutlet weak var p3Label: UILabel! @IBOutlet weak var p4Label: UILabel! @IBOutlet weak var p5Label: UILabel! @IBOutlet weak var p6Label: UILabel! @IBOutlet weak var p7Label: UILabel! @IBOutlet weak var p8Label: UILabel! @IBOutlet weak var p1Button: UIButton! @IBOutlet weak var p2Button: UIButton! @IBOutlet weak var p3Button: UIButton! @IBOutlet weak var p4Button: UIButton! @IBOutlet weak var p5Button: UIButton! @IBOutlet weak var p6Button: UIButton! @IBOutlet weak var p7Button: UIButton! @IBOutlet weak var p8Button: UIButton! @IBOutlet weak var p1ClassLabel: UILabel! @IBOutlet weak var p2ClassLabel: UILabel! @IBOutlet weak var p3ClassLabel: UILabel! @IBOutlet weak var p4ClassLabel: UILabel! @IBOutlet weak var p5ClassLabel: UILabel! @IBOutlet weak var p6ClassLabel: UILabel! @IBOutlet weak var p7ClassLabel: UILabel! @IBOutlet weak var p8ClassLabel: UILabel! @IBAction func p1ButtonTapped(_ sender: Any) { period = 1 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p2ButtonTapped(_ sender: Any) { period = 2 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p3ButtonTapped(_ sender: Any) { period = 3 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p4ButtonTapped(_ sender: Any) { period = 4 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p5ButtonTapped(_ sender: Any) { period = 5 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p6ButtonTapped(_ sender: Any) { period = 6 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p7ButtonTapped(_ sender: Any) { period = 7 performSegue(withIdentifier: "pickClass", sender: nil) } @IBAction func p8ButtonTapped(_ sender: Any) { period = 8 performSegue(withIdentifier: "pickClass", sender: nil) } @IBOutlet weak var skipButton: UIButton! @IBOutlet weak var nextButton: UIButton! @IBAction func skipTapped(_ sender: Any) { if isFreshLaunch { let ac = UIAlertController(title: "Skip this page?", message: "Entering your classes can make the app experiences more personalized.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { (_) in for label in self.classLabels { label.text = "SELECT CLASS" } self.performSegue(withIdentifier: "classSkipped", sender: nil) })) ac.addAction(UIAlertAction(title: "Stay", style: .cancel)) present(ac, animated: true) } else { dismiss(animated: true) } } @IBAction func nextTapped(_ sender: Any) { if periods.contains(nil) { let ac = UIAlertController(title: "Missing Classes", message: "Make sure you fill in all your classes before continuing.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) } else { if isFreshLaunch { self.performSegue(withIdentifier: "nextToTeacher", sender: nil) } else { if isPageEditing { self.performSegue(withIdentifier: "editToTeacher", sender: nil) } else { self.performSegue(withIdentifier: "classToTeacher", sender: nil) } } } } var isFreshLaunch = true var isPrevButtonHidden = false var isPageEditing = false var mySelectedTeachers = [MyNewTeachers]() var myClasses = [String?]() var buttons = [UIButton]() var labels = [UILabel]() var classLabels = [UILabel]() var periods = [String?]() override var prefersHomeIndicatorAutoHidden: Bool { return true } func autoResizeUI() { prevButton.titleLabel!.font = prevButton.titleLabel!.font.withSize(CGFloat(15).relativeToWidth) yourClasses.font = yourClasses.font.withSize(CGFloat(25).relativeToWidth) for label in labels { label.font = label.font.withSize(CGFloat(25).relativeToWidth) } for label in classLabels { label.font = label.font.withSize(CGFloat(24).relativeToWidth) } } var period = Int() func createArrays() { buttons.append(p1Button) buttons.append(p2Button) buttons.append(p3Button) buttons.append(p4Button) buttons.append(p5Button) buttons.append(p6Button) buttons.append(p7Button) buttons.append(p8Button) labels.append(p1Label) labels.append(p2Label) labels.append(p3Label) labels.append(p4Label) labels.append(p5Label) labels.append(p6Label) labels.append(p7Label) labels.append(p8Label) classLabels.append(p1ClassLabel) classLabels.append(p2ClassLabel) classLabels.append(p3ClassLabel) classLabels.append(p4ClassLabel) classLabels.append(p5ClassLabel) classLabels.append(p6ClassLabel) classLabels.append(p7ClassLabel) classLabels.append(p8ClassLabel) if !isPageEditing { for _ in 0...7 { periods.append(nil) } } } override func viewDidLoad() { super.viewDidLoad() createArrays() autoResizeUI() if isPrevButtonHidden { prevButton.isHidden = true } else { prevButton.isHidden = false } if isPageEditing { let scheduleFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest() do { var request = try PersistentService.context.fetch(scheduleFetchRequest) request.sort {$0.period < $1.period} print(request.count, "READ HERE") for i in 0...7 { classLabels[i].text = request[i].name?.uppercased() } } catch { } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if !isFreshLaunch { skipButton.setTitle("CANCEL", for: .normal) } } @IBAction func unwindToClass(segue: UIStoryboardSegue) { if segue.identifier == "backToClass" { let source = segue.source as? PickerViewController if source!.selectedItem != nil { let label = classLabels[period - 1] label.text = source!.selectedItem?.uppercased() periods[period - 1] = source!.selectedItem } } else if segue.identifier == "detailBackToClass" { let source = segue.source as? DetailPickerViewController if source!.selectedItem != nil { let label = classLabels[period - 1] label.text = source!.selectedItem?.uppercased() periods[period - 1] = source!.selectedItem } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "skipToTeacher" { if let vc = segue.destination as? PickTeachersViewController { for _ in 0...7 { vc.classes.append(nil) } } } else if segue.identifier == "nextToTeacher" { if let vc = segue.destination as? PickTeachersViewController { vc.classes = periods } } else if segue.identifier == "classToTeacher" { if let vc = segue.destination as? PickTeachersViewController { vc.classes = periods vc.isFreshLaunch = false vc.isSecondScreen = true } } else if segue.identifier == "editToTeacher" { if let vc = segue.destination as? PickTeachersViewController { vc.classes = periods vc.isPageEditing = true vc.isFreshLaunch = false vc.isSecondScreen = true } } } } <file_sep>// // my_isSchoolDay.swift // PHS App // // Created by <NAME> on 8/4/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension Date { func isSchoolDay() -> Bool { let type = getDayType(date: self) if type == 20 { return false } else { if Calendar.current.component(.weekday, from: self) == 7 || Calendar.current.component(.weekday, from: self) == 1 { return false } else { return true } } } } <file_sep>// // my_getStartEndPeriodLabel.swift // PHS App // // Created by <NAME> on 8/1/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func my_getStartEndPeriodLabel(type: Int) -> [Int]? { switch type { case 0: return defaultDaysStartEndPeriodLabel() case 1: //pep assembly odd return [1, 9, 9, 11, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 2: //pep assembly even return [2, 9, 9, 11, 13, 4, 4, 12, 6, 6, 13, 8, 8] case 3: //extended lunch odd return [1, 10, 10, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 4, 14: //extended lunch even and hour of code return [2, 9, 9, 13, 4, 4, 12, 6, 6, 13, 8, 8] case 5: //finals type 1 return [1, 3, 3, 7, 7] case 6: //finals type 2 return [5, 6, 6, 8, 8] case 7: //finals two periods return [2, 4, 4] case 8: //minimum 1-8 return [1, 2, 2, 3, 3, 4, 4, 13, 5, 5, 6, 6, 7, 7, 8, 8] case 9: //conferences odd return [1, 3, 3, 13, 5, 5, 7, 7] case 10: //conferences even return [2, 4, 4, 13, 6, 6, 8, 8] case 11: //PSAT 9 return [15, 10, 2, 2, 4, 4, 12, 6, 6, 8, 8] case 12: //PE testing return [16, 10, 1, 1, 3, 3, 12, 5, 5, 7, 7] case 13: //first 2 days of school return [9, 1, 1, 2, 2, 3, 3, 13, 4, 4, 5, 5, 12, 6, 6, 7, 7, 8, 8] case 15: //Passion Day return [9, 19, 19, 13, 20, 20, 21, 21] case 16: //Pre Testing return [1, 9, 9, 13, 2, 2, 3, 3, 12, 5, 5, 7, 7] case 17: //Testing return [23, 10, 4, 4, 12, 6, 6, 8, 8] case 18: //CAASPP odd return [24, 13, 10, 10, 1, 1, 3, 3, 12, 5, 5, 7, 7] case 19: //CAASPP even return [24, 13, 10, 10, 2, 2, 4, 4, 12, 6, 6, 8, 8] case 20: //NO SCHOOL return nil case 21: //fine arts assembly return [2, 13, 14, 14, 12, 6, 6, 13, 8, 8] case 22: //monday schedule return [1, 2, 2, 3, 3, 13, 4, 4, 5, 5, 12, 6, 6, 7, 7, 8, 8] case 23: //tuesday schedule return [1, 9, 9, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 24: //wednesday schedule return [2, 10, 13, 4, 4, 12, 6, 6, 13, 8, 8] case 25: //thursday schedule return [1, 10, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 26: //friday schedule return [2, 9, 9, 13, 4, 4, 12, 6, 6, 13, 8, 8] case 27: //Thursday advisement return [1, 9, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 28: //Friday OH return [2, 10, 10, 13, 4, 4, 12, 6, 6, 13, 8, 8] case 29: return [1, 3, 3, 12, 5, 5, 7, 7] default: return defaultDaysStartEndPeriodLabel() } } func defaultDaysStartEndPeriodLabel() -> [Int]? { switch Calendar.current.component(.weekday, from: Date()) { case 1, 7: return nil case 2: return [1, 2, 2, 3, 3, 13, 4, 4, 5, 5, 12, 6, 6, 7, 7, 8, 8] case 3: return [1, 9, 9, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 4: return [2, 10, 13, 4, 4, 12, 6, 6, 13, 8, 8] case 5: return [1, 10, 13, 3, 3, 12, 5, 5, 13, 7, 7] case 6: return [2, 9, 9, 13, 4, 4, 12, 6, 6, 13, 8, 8] default: return nil } } <file_sep>// // MyNewTeachers+CoreDataClass.swift // PHS App // // Created by <NAME> on 1/6/19. // Copyright © 2019 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(MyNewTeachers) public class MyNewTeachers: NSManagedObject { //test commit } <file_sep>// // NameInputViewController.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import TextFieldEffects import CoreData class NameInputViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var skipButton: UIButton! @IBOutlet weak var yourName: UILabel! @IBOutlet weak var yourGrade: UILabel! @IBOutlet weak var yourHouse: UILabel! @IBOutlet weak var gradeCollectionView: UICollectionView! @IBOutlet weak var houseCollectionView: UICollectionView! @IBOutlet weak var firstName: HoshiTextField! @IBOutlet weak var lastName: HoshiTextField! @IBAction func nextTapped(_ sender: Any) { if first != nil && last != nil && grade != nil && house != nil { if isFreshLaunch { performSegue(withIdentifier: "nextToID", sender: nil) } else { if isPageEditing { performSegue(withIdentifier: "editingToID", sender: nil) } else { performSegue(withIdentifier: "nameToID", sender: nil) } } } else { let ac = UIAlertController(title: "Missing Fields", message: "Some fields are empty, make sure they are filled in in order to continue.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) } } @IBAction func skipTapped(_ sender: Any) { if isFreshLaunch { let ac = UIAlertController(title: "Skip this page?", message: "Entering general information about yourself can make the app experience more personalized.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { _ in self.performSegue(withIdentifier: "skipToID", sender: nil) })) ac.addAction(UIAlertAction(title: "Stay", style: .cancel)) present(ac, animated: true) } else { dismiss(animated: true) } } var first: String? var last: String? var grade: Int? var house: String? var longID: String? var shortID: String? var gradeArray = [9, 10, 11, 12] var houseArray = ["Hercules", "Orion", "Pegasus", "Poseidon"] var isFreshLaunch = true var isPageEditing = false override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "nextToID" { let vc = segue.destination as! IDInputViewController vc.first = first vc.last = last vc.house = house vc.grade = grade } else if segue.identifier == "skipToID" { let vc = segue.destination as! IDInputViewController vc.first = nil vc.last = nil vc.house = nil vc.grade = nil } else if segue.identifier == "nameToID" { let vc = segue.destination as! IDInputViewController vc.first = first vc.last = last vc.house = house vc.grade = grade vc.isFreshLaunch = false } else if segue.identifier == "editingToID" { let vc = segue.destination as! IDInputViewController vc.first = first vc.last = last vc.house = house vc.grade = grade vc.shortID = Int(shortID!) vc.longID = Int(longID!) vc.isFreshLaunch = false vc.isPageEditing = true } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == gradeCollectionView { return 4 } else if collectionView == houseCollectionView { return 4 } return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if collectionView == gradeCollectionView { return CGSize(width: CGFloat(55).relativeToWidth, height: CGFloat(55).relativeToWidth) } else if collectionView == houseCollectionView { return CGSize(width: UIScreen.main.bounds.width / 3, height: CGFloat(60).relativeToWidth) } return CGSize(width: 0, height: 0) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == gradeCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "grade", for: indexPath) as!GradeCollectionViewCell cell.label.text = "\(gradeArray[indexPath.item])" cell.label.textAlignment = .center cell.label.bounds = CGRect(x: 0, y: 0, width: CGFloat(55).relativeToWidth, height: CGFloat(55).relativeToWidth) cell.label.textColor = UIColor.white cell.label.font = UIFont(name: "Lato-Light", size: CGFloat(24).relativeToWidth) cell.label.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2) cell.circle.bounds = CGRect(x: 0, y: 0, width: CGFloat(55).relativeToWidth, height: CGFloat(55).relativeToWidth) cell.circle.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2) cell.circle.clipsToBounds = true cell.circle.layer.cornerRadius = cell.circle.frame.width / 2 cell.circle.layer.borderColor = UIColor.white.cgColor cell.circle.layer.borderWidth = 1.5 cell.circle.layer.backgroundColor = UIColor.white.withAlphaComponent(0).cgColor cell.addSubview(cell.circle) cell.addSubview(cell.label) print(indexPath.item) return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "house", for: indexPath) as! HouseCollectionViewCell cell.label.text = houseArray[indexPath.item].uppercased() cell.label.textAlignment = .center cell.label.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width / 3, height: CGFloat(55).relativeToWidth) cell.label.textColor = UIColor.white cell.label.font = UIFont(name: "Lato-Light", size: CGFloat(20).relativeToWidth) cell.label.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2) cell.roundedRect.bounds = CGRect(x: 0, y: 0, width: CGFloat(120).relativeToWidth, height: CGFloat(50).relativeToWidth) cell.roundedRect.center = CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2) cell.roundedRect.clipsToBounds = true cell.roundedRect.layer.cornerRadius = cell.roundedRect.frame.height / 2 cell.roundedRect.layer.borderColor = UIColor.white.cgColor cell.roundedRect.layer.borderWidth = 1.5 cell.roundedRect.layer.backgroundColor = UIColor.white.withAlphaComponent(0).cgColor cell.addSubview(cell.roundedRect) cell.addSubview(cell.label) return cell } } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { let cell = collectionView.cellForItem(at: indexPath)! if cell.isSelected { collectionView.deselectItem(at: indexPath, animated: true) self.collectionView(collectionView, didDeselectItemAt: indexPath) if collectionView == gradeCollectionView { grade = nil } else if collectionView == houseCollectionView { house = nil } return false } else { return true } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if collectionView == gradeCollectionView { let cell = collectionView.cellForItem(at: indexPath)! grade = gradeArray[indexPath.item] if let item = cell as? GradeCollectionViewCell { UIView.animate(withDuration: 0.3) { item.label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) item.circle.backgroundColor = UIColor.white.withAlphaComponent(1) } } } else { let cell = collectionView.cellForItem(at: indexPath)! house = houseArray[indexPath.item] if let item = cell as? HouseCollectionViewCell { UIView.animate(withDuration: 0.3) { item.label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) item.roundedRect.backgroundColor = UIColor.white.withAlphaComponent(1) } } } } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if collectionView == gradeCollectionView { let cell = collectionView.cellForItem(at: indexPath) if let item = cell as? GradeCollectionViewCell { UIView.animate(withDuration: 0.3) { item.label.textColor = UIColor.white item.circle.backgroundColor = UIColor.white.withAlphaComponent(0) } } } else { let cell = collectionView.cellForItem(at: indexPath) if let item = cell as? HouseCollectionViewCell { UIView.animate(withDuration: 0.3) { item.label.textColor = UIColor.white item.roundedRect.backgroundColor = UIColor.white.withAlphaComponent(0) } } } } func textFieldDidEndEditing(_ textField: UITextField) { if textField == firstName { if textField.text == "" { first = nil } else { first = textField.text firstName.resignFirstResponder() } } else if textField == lastName { if textField.text == "" { last = nil } else { last = textField.text firstName.resignFirstResponder() } } } func textFieldDidBeginEditing(_ textField: UITextField) { self.view.gestureRecognizers?.first!.isEnabled = true if textField == lastName { first = firstName.text } else if textField == firstName { last = lastName.text } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == firstName { first = textField.text firstName.resignFirstResponder() self.view.gestureRecognizers?.first!.isEnabled = false } else if textField == lastName { last = textField.text lastName.resignFirstResponder() self.view.gestureRecognizers?.first!.isEnabled = false } return true } override var prefersHomeIndicatorAutoHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() firstName.delegate = self lastName.delegate = self gradeCollectionView.delegate = self houseCollectionView.delegate = self gradeCollectionView.dataSource = self houseCollectionView.dataSource = self gradeCollectionView.backgroundColor = UIColor.white.withAlphaComponent(0) houseCollectionView.backgroundColor = UIColor.white.withAlphaComponent(0) gradeCollectionView.allowsMultipleSelection = false houseCollectionView.allowsMultipleSelection = false yourHouse.font = yourHouse.font.withSize(CGFloat(25).relativeToWidth) yourName.font = yourHouse.font.withSize(CGFloat(25).relativeToWidth) yourGrade.font = yourHouse.font.withSize(CGFloat(25).relativeToWidth) let gradeLayout = self.gradeCollectionView.collectionViewLayout as! UICollectionViewFlowLayout gradeLayout.minimumInteritemSpacing = CGFloat(20).relativeToWidth gradeLayout.sectionInset = UIEdgeInsets.init(top: 0, left: CGFloat(30).relativeToWidth, bottom: 0, right: CGFloat(30).relativeToWidth) let houseLayout = self.houseCollectionView.collectionViewLayout as! UICollectionViewFlowLayout houseLayout.minimumInteritemSpacing = CGFloat(20).relativeToWidth houseLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 35, bottom: 0, right: 35) houseLayout.minimumLineSpacing = CGFloat(20).relativeToWidth let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(screenTapped)) gestureRecognizer.delegate = self view.addGestureRecognizer(gestureRecognizer) gestureRecognizer.isEnabled = false if CheckInternet.Connection() { DispatchQueue.global(qos: .background).async { if localTeachers.count == 0 { fetchTeachers() } DispatchQueue.main.async { let fetchRequest: NSFetchRequest<Teachers> = Teachers.fetchRequest() let sort = NSSortDescriptor(key: "last", ascending: true) fetchRequest.sortDescriptors = [sort] do { let newRequest = try PersistentService.context.fetch(fetchRequest) savedTeachers = newRequest if teachersAlphaDict.count == 0 { generateAlphaDict() } if subjectsDictionary.count == 0 { generateSubjectsDict() } } catch { } } } } else { let ac = UIAlertController(title: "No Internet Connection", message: "Trouble loading certain data, make sure you are connected to the Internet. You may still continue the set-up process.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if !isFreshLaunch { if isPageEditing { firstName.text = first lastName.text = last gradeCollectionView.selectItem(at: [0, grade! - 9], animated: true, scrollPosition: []) self.collectionView(self.gradeCollectionView, didSelectItemAt: [0, grade! - 9]) var houseArrayIndex = Int() for i in 0...houseArray.count - 1 { if houseArray[i] == house { houseArrayIndex = i break } } houseCollectionView.selectItem(at: [0, houseArrayIndex], animated: true, scrollPosition: []) self.collectionView(self.houseCollectionView, didSelectItemAt: [0, houseArrayIndex]) } } } @objc func screenTapped() { if firstName.isEditing || lastName.isEditing { if firstName.text != nil { first = firstName.text! firstName.resignFirstResponder() self.view.gestureRecognizers?.first!.isEnabled = false } else { firstName = nil firstName.resignFirstResponder() self.view.gestureRecognizers?.first!.isEnabled = false } if lastName.text != nil { last = lastName.text! lastName.resignFirstResponder() self.view.gestureRecognizers?.first!.isEnabled = false } else { lastName = nil lastName.resignFirstResponder() self.view.gestureRecognizers?.first!.isEnabled = false } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if isFreshLaunch == false { skipButton.setTitle("CANCEL", for: .normal) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // User+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension User { @nonobjc public class func fetchRequest() -> NSFetchRequest<User> { return NSFetchRequest<User>(entityName: "User") } @NSManaged public var first: String? @NSManaged public var last: String? @NSManaged public var grade: Int16 @NSManaged public var house: String? @NSManaged public var shortID: Int32 @NSManaged public var longID: Int32 } <file_sep>// // Games.swift // PHS App // // Created by <NAME> on 8/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class Games: NSObject { var sport = String() var other: String? var isAway = Bool() var time = Date() var homeScore: Int? var awayScore: Int? } <file_sep>// // TeacherPickerViewController.swift // PHS App // // Created by <NAME> on 8/19/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import PickerView class TeacherPickerViewController: UIViewController { enum ItemsType : Int { case label, customView } enum PresentationType { case numbers(Int, Int), names(Int, Int) } @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var pickerView: PickerView! @IBAction func cancelTapped(_ sender: Any) { dismiss(animated: true) } @IBAction func doneTapped(_ sender: Any) { if currentSelectedValue != nil { selectedItem = currentSelectedValue! performSegue(withIdentifier: "backToTeacher", sender: nil) } } var selectedSubject = String() var teacherObjects = [NewTeachers]() var presentationType = PresentationType.numbers(0, 0) var selectedItem: NewTeachers? var currentSelectedValue: NewTeachers? var updateSelectedValue: ((_ newSelectedValue: String) -> Void)? var itemsType: PickerViewController.ItemsType = .label override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() configurePicker() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) } fileprivate func configurePicker() { pickerView.delegate = self pickerView.dataSource = self pickerView.scrollingStyle = .default pickerView.selectionStyle = .none if let currentSelected = currentSelectedValue, let indexOfCurrentSelectedValue = teacherObjects.index(of: currentSelected) { pickerView.currentSelectedRow = indexOfCurrentSelectedValue } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension TeacherPickerViewController: PickerViewDelegate { func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat { return 50.0 } func pickerView(_ pickerView: PickerView, styleForLabel label: UILabel, highlighted: Bool) { label.textAlignment = .center if (highlighted) { label.font = UIFont(name: "Lato-Light", size: CGFloat(28).relativeToWidth) label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) } else { label.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth) label.textColor = UIColor.lightGray.withAlphaComponent(0.75) } } func pickerView(_ pickerView: PickerView, didSelectRow row: Int, index: Int) { currentSelectedValue = self.teacherObjects[index] } } extension TeacherPickerViewController: PickerViewDataSource { func pickerView(_ pickerView: PickerView, titleForRow row: Int) -> String { return "" } func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int { return teacherObjects.count } func pickerView(_ pickerView: PickerView, titleForRow row: Int, index: Int) -> String { return "\(teacherObjects[index].first) \(teacherObjects[index].last)" } } <file_sep>// // CalendarCollectionViewCell.swift // PHS App // // Created by <NAME> on 8/21/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import JTAppleCalendar class CalendarCollectionViewCell: JTAppleCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var selectedView: UIView! @IBOutlet weak var dotView: UIView! override func awakeFromNib() { super.awakeFromNib() } } <file_sep>// // my_numberToLabel.swift // PHS App // // Created by <NAME> on 8/2/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import CoreData func myClassArray() -> [String?] { var classes = [String]() let classFetchRequest: NSFetchRequest<MySchedule> = MySchedule.fetchRequest() do { var request = try PersistentService.context.fetch(classFetchRequest) if request.count > 0 { request.sort {$0.period < $1.period} for i in 0...7 { classes.append(request[i].name!) } } else { classes = [] } } catch { } return classes } extension Int { func getPeriodLabel() -> String { switch self { case 1: if myClassArray().count == 0 { return "PERIOD 1" } else { return myClassArray()[0]?.uppercased() ?? "PERIOD 1" } case 2: if myClassArray().count == 0 { return "PERIOD 2" } else { return myClassArray()[1]?.uppercased() ?? "PERIOD 2" } case 3: if myClassArray().count == 0 { return "PERIOD 3" } else { return myClassArray()[2]?.uppercased() ?? "PERIOD 3" } case 4: if myClassArray().count == 0 { return "PERIOD 4" } else { return myClassArray()[3]?.uppercased() ?? "PERIOD 4" } case 5: if myClassArray().count == 0 { return "PERIOD 5" } else { return myClassArray()[4]?.uppercased() ?? "PERIOD 5" } case 6: if myClassArray().count == 0 { return "PERIOD 6" } else { return myClassArray()[5]?.uppercased() ?? "PERIOD 6" } case 7: if myClassArray().count == 0 { return "PERIOD 7" } else { return myClassArray()[6]?.uppercased() ?? "PERIOD 7" } case 8: if myClassArray().count == 0 { return "PERIOD 8" } else { return myClassArray()[7]?.uppercased() ?? "PERIOD 8" } case 9: return "ADVISEMENT" case 10: return "OFFICE HOURS" case 11: return "PEP ASSEMBLY" case 12: return "LUNCH" case 13: return "BREAK" case 14: return "ASSEMBLY / PERIOD 4" case 15: return "PSAT" case 16: return "PE TESTING 9" case 17: return "ADVISEMENT / THEATE" case 18: return "THEATRE / ADVISEMENT" case 19: return "SESSION 1" case 20: return "SESSION 2" case 21: return "SESSION 3" case 22: return "SESSION 4" case 23: return "10-11 TESTING" case 24: return "JUNIORS TESTING" default: return "" } } } //1-8: PERIOD 1-8 //9: Advisement //10: Office Hours //11: Pep Assembly //12: Lunch //13: Break //14: Assembly / PERIOD 4 //15: PSAT 9 //16: PE Testing 9 //17: Advisement / Theatre //18: Theatre / Advisement //19: SESSION 1 //20: SESSION 2 //21: SESSION 3 //22: SESSION 4 //23: 10-11 Testing //24: 11 Testing <file_sep>// // UnderConstructionViewController.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreGraphics import MessageUI class UnderConstructionViewController: UIView { @IBOutlet weak var underConstructionLabel: UILabel! @IBOutlet weak var bottomLabel: UILabel! var buttonView = UIView() var buttonLabel = UILabel() /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // HomeViewController.swift // PHS App // // Created by <NAME> on 7/22/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreGraphics import UserNotifications enum dayType { case today case tomorrow case nextMonday case custom } var specialDays = [SpecialDays]() var today = Int() var tomorrow = Int() var nextMonday = Int() func getDayType(date: Date) -> Int { var isSpecial = false for days in specialDays { if days.date.noon == date.noon { isSpecial = true return Int(days.type) } } if isSpecial == false { return 0 } } func loadSpecialDays() { if let data = Bundle.main.path(forResource: "specialDays", ofType: "txt") { if let content = try? String(contentsOfFile: data) { if let jsonData = JSON(parseJSON: content).dictionaryValue["specialDays"]?.arrayValue { for days in jsonData { let detail = days.dictionaryObject! let object = SpecialDays() if let date = detail["date"] as? String { let formatter = DateFormatter() formatter.dateFormat = "yyyy/M/dd" formatter.timeZone = Calendar.current.timeZone formatter.locale = Calendar.current.locale object.date = formatter.date(from: date)! } if let type = detail["case"] as? Int { object.type = type } specialDays.append(object) } } } } } class HomeViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var showMoreButton: UIButton! @IBAction func buttonTapped(_ sender: Any) { UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notif) in }) UNUserNotificationCenter.current().getDeliveredNotifications { (notifDel) in } } @IBOutlet weak var timeLeftLabel: UILabel! @IBOutlet weak var endsLabel: UILabel! @IBOutlet weak var minutesLabel: UILabel! var weekdayLabelView = UIView() var barImage = UIView() var weekdayDots = UIView() var progressBar = UIView() var todayClassLabel = UIView() var day = Calendar.current.component(.day, from: Date()) var minute = Calendar.current.component(.minute, from: Date()) var timeOfDay: relativeTime? var schoolEvents = [SchoolEvents]() let joinButton = UIView() let joinLabel = UILabel() var deviceAnchor6 = Int() var deviceMax = Int() var eventTimes = [String]() var eventTitles = [String]() var isAppOpenedByUser = false var isAppConnected = false var fetchedNumber = Int() var savedEvents = [SavedEvents]() var timer: Timer? = nil @IBOutlet weak var eventTime1: UILabel! @IBOutlet weak var eventTitle1: UILabel! @IBOutlet weak var eventTime2: UILabel! @IBOutlet weak var eventTitle2: UILabel! @IBOutlet weak var eventTime3: UILabel! @IBOutlet weak var eventTitle3: UILabel! @IBOutlet weak var gradient: UIImageView! @IBOutlet weak var background: UIImageView! var labels = [UILabel]() var views = [UIView]() var eventLabels = [UILabel]() let lastDay = Date(timeIntervalSince1970: 1559977200) let firstDay2019 = Date(timeIntervalSince1970: 1566457200) var dateDifference = Int() @objc func timeTapped() { timeLeftLabel.my_glowOnTap() minutesLabel.my_glowOnTap() endsLabel.my_glowOnTap() } @objc func event1Tapped() { eventTitle1.my_glowOnTap() eventTime1.my_glowOnTap() } @objc func event2Tapped() { eventTitle2.my_glowOnTap() eventTime2.my_glowOnTap() } @objc func event3Tapped() { eventTitle3.my_glowOnTap() eventTime3.my_glowOnTap() } func startTimer() { if timer == nil { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) } } func stopTimer() { if timer != nil { timer?.invalidate() timer = nil } } func initialize() { deviceAnchor6 = Int(self.view.bounds.maxX / 6) deviceMax = Int(self.view.bounds.maxX) timeLeftLabel.my_dropShadow() endsLabel.my_dropShadow() minutesLabel.my_dropShadow() labels = [endsLabel, minutesLabel, timeLeftLabel, eventTime1, eventTime2, eventTime3, eventTitle1, eventTitle2, eventTitle3] views = [weekdayLabelView, weekdayDots, progressBar, barImage, todayClassLabel] eventLabels = [eventTime1, eventTime2, eventTime3, eventTitle1, eventTitle2, eventTitle3] for label in labels { label.alpha = 0 label.font = label.font.withSize(label.font.pointSize.relativeToWidth) } for view in views { view.alpha = 0 } for label in eventLabels { label.text = " " } let timeGesture = UITapGestureRecognizer(target: self, action: #selector(timeTapped)) let event1Gesture = UITapGestureRecognizer(target: self, action: #selector(event1Tapped)) let event2Gesture = UITapGestureRecognizer(target: self, action: #selector(event2Tapped)) let event3Gesture = UITapGestureRecognizer(target: self, action: #selector(event3Tapped)) timeGesture.delegate = self event1Gesture.delegate = self event2Gesture.delegate = self event3Gesture.delegate = self timeLeftLabel.addGestureRecognizer(timeGesture) eventTime1.addGestureRecognizer(event1Gesture) eventTitle1.addGestureRecognizer(event1Gesture) eventTime2.addGestureRecognizer(event2Gesture) eventTitle2.addGestureRecognizer(event2Gesture) eventTime3.addGestureRecognizer(event3Gesture) eventTitle3.addGestureRecognizer(event3Gesture) showMoreButton.titleLabel!.font = showMoreButton.titleLabel!.font.withSize(showMoreButton.titleLabel!.font.pointSize.relativeToWidth.relativeToWidth) showMoreButton.imageEdgeInsets.left = showMoreButton.imageEdgeInsets.left.relativeToWidth.relativeToWidth showMoreButton.isHidden = true } func fadeInViews(isAppOpened: Bool, completion: () -> ()) { DispatchQueue.main.async { self.timeOfDay = Date().timeOfSchoolDay() self.fetchEvents() self.configureWeekdays() if Date() >= Date.init(timeIntervalSince1970: 1552806000) { // self.configureWeekdayDots() } self.configureProgressBar() self.configureBar() self.configureBarLabel(type: today) self.configureTimeLeftLabel() } completion() } func startAnimation() { DispatchQueue.main.async { UIView.animate(withDuration: 0.3, delay: 0.1, animations: { self.weekdayLabelView.alpha = 1 self.weekdayDots.alpha = 1 self.joinButton.alpha = 1 }) UIView.animate(withDuration: 0.3, delay: 0.1, animations: { self.progressBar.alpha = 1 self.barImage.alpha = 1 self.todayClassLabel.alpha = 1 }) UIView.animate(withDuration: 0.3, delay: 0.1, animations: { self.eventTime1.alpha = 1 self.eventTitle1.alpha = 1 }) UIView.animate(withDuration: 0.3, delay: 0.1, animations: { self.eventTime2.alpha = 1 self.eventTitle2.alpha = 1 }) UIView.animate(withDuration: 0.3, delay: 0.1, animations: { self.eventTime3.alpha = 1 self.eventTitle3.alpha = 1 }) UIView.animate(withDuration: 0.3, delay: 0.1, animations: { self.showMoreButton.alpha = 1 }) } } func userDefaults() { //first launch // let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore") // if !launchedBefore { // UserDefaults.standard.set(true, forKey: "launchedBefore") // self.performSegue(withIdentifier: "welcome", sender: nil) // } //local notification patch let ifNotifUpdated = UserDefaults.standard.bool(forKey: "updateNotification") if !ifNotifUpdated { UserDefaults.standard.set(true, forKey: "notificationScheduled") UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (request) in if request.count > 0 { UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } }) } //teacher local migration notification // let isTeacherUpdated = UserDefaults.standard.bool(forKey: "updateTeacher") // if !isTeacherUpdated { // UserDefaults.standard.set(true, forKey: "updateTeacher") // let ac = UIAlertController(title: "Fill in your Schedule", message: "Over break, we have rebuilt the teachers page in order to optimize battery usage. As a result, we had to erase your saved classes and teachers. Head over to the teachers page to fill out your schedule again for a more personal experience.", preferredStyle: .alert) // ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) // present(ac, animated: true) // } } func launchIntegral() { UIApplication.shared.open(URL(string: "https://apps.apple.com/us/app/integral-digital-backpack/id1480096639")!, options: [:], completionHandler: nil) } override func viewDidLoad() { super.viewDidLoad() tabBarController?.tabBar.isHidden = true //lay out UI initialize() //set-up isAppConnected = CheckInternet.Connection() loadSpecialDays() scheduleNotifications() getTodayType() DispatchQueue.global(qos: .background).async { //User Defaults self.userDefaults() self.fadeInViews(isAppOpened: self.isAppOpenedByUser, completion: { self.startAnimation() }) } //initilize timer startTimer() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) //change status bar color //continue application if Date().isSchoolDay() { if Date().getRelativeTime() == relativeTime.during { fetchTimeLeft() } } self.joinButton.backgroundColor = UIColor.clear self.joinLabel.textColor = UIColor.white } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) //stop the timer } func scheduleLocal(on date: Date, with type: Int) { let notificationDate = Calendar.current.date(byAdding: .day, value: -1, to: date)! let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in if granted { if date.isLongBreak == false { var dateComponents = DateComponents() dateComponents.year = Calendar.current.component(.year, from: notificationDate) dateComponents.month = Calendar.current.component(.month, from: notificationDate) dateComponents.day = Calendar.current.component(.day, from: notificationDate) dateComponents.hour = 20 dateComponents.minute = 0 let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) let content = UNMutableNotificationContent() content.title = "Schedule Reminder" content.body = my_notificationPrompt(type: type) content.sound = UNNotificationSound.default let request = UNNotificationRequest(identifier: "\(date.noon)\(type)", content: content, trigger: trigger) center.add(request) } } else { } } } func getTodayType() { today = 0 tomorrow = 0 nextMonday = 0 for days in specialDays { if Date().noon == days.date.noon { today = days.type } if Date().tomorrow == days.date.noon { tomorrow = days.type } if Date().nextMonday().noon == days.date.noon { nextMonday = days.type } } } func scheduleNotifications() { var reducedSpecialDays = [SpecialDays]() reducedSpecialDays = specialDays.filter { $0.date > Date() } for days in reducedSpecialDays { scheduleLocal(on: days.date, with: days.type) } } @objc func update() { /* if isAppConnected == false { if CheckInternet.Connection() { updateWhenFirstConnected() isAppConnected = true } }*/ if Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .during { fetchTimeLeft() } else { //update only at midnight if Calendar.current.component(.day, from: Date()) != day { if Date() > lastDay && Date() < firstDay2019 { dateDifference = Calendar.current.dateComponents([.day], from: firstDay2019, to: Date()).day ?? 0 loadTimeLeftLabel(text: String(dateDifference), size: CGFloat(140)) } else { updateAtMidNight() day = Calendar.current.component(.day, from: Date()) } } else { if Date() > lastDay && Date() < firstDay2019 { //nothing happens } else { if timeOfDay != Date().getRelativeTime() { timeOfDay = Date().timeOfSchoolDay() if (Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .after) { dateDifference = Calendar.current.dateComponents([.day], from: Date(), to: firstDay2019).day ?? 0 loadTimeLeftLabel(text: String(dateDifference), size: CGFloat(140)) loadMinutesLabel(text: "DAYS") loadEndsLabel(text: "SCHOOL STARTS IN") } else { self.configureTimeLeftLabel() } } else { if minute != Calendar.current.component(.minute, from: Date()) { if Date().isSchoolDay() { if timeOfDay == .during { loadProgressingBar(isInitial: false) } } if Date().isSchoolDay() { if timeOfDay == .during { fetchTimeLeft() } } minute = Calendar.current.component(.minute, from: Date()) } } } } } } func updateWhenFirstConnected() { fetchEvents() } func updateAtMidNight() { eventTimes.removeAll() eventTitles.removeAll() savedEvents.removeAll() getTodayType() timeOfDay = Date().timeOfSchoolDay() configureTimeLeftLabel() for subview in weekdayDots.subviews { subview.removeFromSuperview() } if Date() >= Date.init(timeIntervalSince1970: 1552806000) { configureWeekdayDots() } progressBar.removeFromSuperview() configureProgressBar() progressBar.viewFadeIn() view.bringSubviewToFront(barImage) for subviews in todayClassLabel.subviews { subviews.removeFromSuperview() } configureBarLabel(type: today) fetchEvents() } @objc func joinTapped() { // UIView.animate(withDuration: 0.3) { // // } // UIView.animate(withDuration: 0.3, animations: { // self.joinButton.backgroundColor = UIColor.white // self.joinLabel.textColor = UIColor(red: 0.702, green: 0.667, blue: 0.843, alpha: 1.00) // }) { (_) in // UIView.animate(withDuration: 0.2, delay: 0.5, animations: { // self.joinButton.backgroundColor = UIColor.clear // self.joinLabel.textColor = UIColor.white // }, completion: nil) // } // if let vc = storyboard?.instantiateViewController(withIdentifier: "join") as? JoinViewController { // present(vc, animated: true) // } // UIApplication.shared.open(URL(string: "https://apps.apple.com/us/app/integral-digital-backpack/id1480096639")!, options: [:], completionHandler: nil) } func configureWeekdays() { joinButton.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width / 1.5, height: self.view.bounds.width / 6) joinButton.center = CGPoint(x: self.view.bounds.midX, y: self.minutesLabel.center.y + CGFloat(70).relativeToWidth) joinButton.layer.borderColor = UIColor.white.cgColor joinButton.layer.borderWidth = 2 joinButton.layer.cornerRadius = joinButton.bounds.height / 2 joinButton.clipsToBounds = true view.addSubview(joinButton) joinLabel.bounds = joinButton.bounds joinLabel.center = CGPoint(x: joinButton.bounds.width / 2, y: joinButton.bounds.height / 2) joinLabel.textAlignment = .center joinLabel.textColor = UIColor.white joinLabel.attributedText = NSAttributedString(string: "DOWNLOAD INTEGRAL", attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue]) joinLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(18).relativeToWidth) joinButton.addSubview(joinLabel) let joinGesture = UITapGestureRecognizer(target: self, action: #selector(joinTapped)) joinGesture.delegate = self joinButton.addGestureRecognizer(joinGesture) joinButton.alpha = 0 // else { // for i in 0...4 { // let weekdayLabels = ["M", "T", "W", "T", "F"] // let weekdayLabel = UILabel() // weekdayLabel.frame = CGRect(x: 0, y: 0, width: 21, height: 21) // weekdayLabel.center = CGPoint(x: deviceAnchor6 + deviceAnchor6 * i, y: Int(self.view.bounds.midY) - Int(CGFloat(30).relativeToWidth)) // weekdayLabel.textAlignment = .center // weekdayLabel.text = weekdayLabels[i] // weekdayLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(17).relativeToWidth) // weekdayLabel.textColor = UIColor.white // weekdayLabel.my_dropShadow() // weekdayLabelView.addSubview(weekdayLabel) // // } // view.addSubview(weekdayLabelView) // } } func configureWeekdayDots() { for i in 0 ... 4 { drawDots(withFill: false, loopNumber: i) } let weekToday = Calendar.current.component(.weekday, from: Date()) if weekToday == 1 { view.addSubview(weekdayDots) } else if weekToday == 6 || weekToday == 7 { for i in 0...4 { drawDots(withFill: true, loopNumber: i) view.addSubview(weekdayDots) } } else { for i in 0...(weekToday - 2) { drawDots(withFill: true, loopNumber: i) view.addSubview(weekdayDots) } } } func drawDots(withFill: Bool, loopNumber: Int) { let renderer = UIGraphicsImageRenderer(size: CGSize(width: 30, height: 30)) let img = renderer.image { ctx in if withFill { ctx.cgContext.setFillColor(UIColor.white.cgColor) } ctx.cgContext.setStrokeColor(UIColor.white.cgColor) ctx.cgContext.setLineWidth(2) let rectangle = CGRect(x: 2.5, y: 2.5, width: 25, height: 25) ctx.cgContext.addEllipse(in: rectangle) if withFill { ctx.cgContext.drawPath(using: .fillStroke) } else { ctx.cgContext.drawPath(using: .stroke) } } let image = UIImageView(image: img) image.center = CGPoint(x: deviceAnchor6 + deviceAnchor6 * loopNumber, y: Int(self.view.bounds.height * 0.41)) image.my_dropShadow() weekdayDots.addSubview(image) } func configureBar() { let renderer = UIGraphicsImageRenderer(size: CGSize(width: Int(CGFloat(270).barRelativeToWidth), height: Int(CGFloat(30).barRelativeToWidth))) let img = renderer.image { ctx in ctx.cgContext.setStrokeColor(UIColor.white.cgColor) ctx.cgContext.setLineWidth(2) let rectangle = CGRect(x: 2, y: 5, width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth)) let roundedNumber = Int(CGFloat(20).barRelativeToWidth) / 2 let rounded = CGPath.init(roundedRect: rectangle, cornerWidth: CGFloat(roundedNumber), cornerHeight: CGFloat(roundedNumber), transform: nil) ctx.cgContext.addPath(rounded) ctx.cgContext.drawPath(using: .stroke) } let image = UIImageView(image: img) image.center = CGPoint(x: Int(self.view.bounds.midX), y: Int(self.view.bounds.midY) + Int(CGFloat(20).barRelativeToWidth)) image.my_dropShadow() barImage.addSubview(image) view.addSubview(barImage) view.bringSubviewToFront(barImage) } func configureProgressBar() { let midPointX = Int(self.view.bounds.midX) let midPointY = Int(self.view.bounds.midY) let barStartingPoint = Int(midPointX - Int(CGFloat(123).barRelativeToWidth)) let progressBarY = midPointY + Int(CGFloat(20).barRelativeToWidth) progressBar.clipsToBounds = true progressBar.layer.cornerRadius = CGFloat(10).barRelativeToWidth progressBar.alpha = 0 if Date().isSchoolDay() { switch timeOfDay! { case .before: progressBar.center = CGPoint(x: barStartingPoint, y: progressBarY) progressBar.bounds.size = CGSize(width: Int(CGFloat(20).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth)) progressBar.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth)))) view.addSubview(progressBar) case .during: loadProgressingBar(isInitial: true) case .after: progressBar.center = CGPoint(x: midPointX, y: progressBarY) progressBar.bounds.size = CGSize(width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth)) progressBar.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: Int(CGFloat(266).barRelativeToWidth), height: Int(CGFloat(20).barRelativeToWidth)))) view.addSubview(progressBar) } } } func loadProgressingBar(isInitial: Bool) { var numerator = CGFloat() let denominator = CGFloat(numOfMinAtSchool(type: today)!) var percentage = CGFloat() let midPointX = Int(self.view.bounds.midX) let midPointY = Int(self.view.bounds.midY) let barStartingPoint = Int(midPointX - Int(CGFloat(123).barRelativeToWidth)) let bound = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: CGFloat(266).barRelativeToWidth, height: CGFloat(20).barRelativeToWidth)) progressBar.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: bound) if isInitial { numerator = CGFloat(Date().localTime().minFromSchoolStart()) percentage = numerator / denominator progressBar.center = CGPoint(x: (barStartingPoint) + Int(CGFloat(123).barRelativeToWidth * percentage), y: midPointY + Int(CGFloat(20).barRelativeToWidth)) progressBar.bounds.size = CGSize(width: CGFloat(20) + (CGFloat(246).barRelativeToWidth * percentage), height: CGFloat(20).barRelativeToWidth) view.addSubview(progressBar) view.bringSubviewToFront(barImage) } else { numerator = CGFloat(Date().localTime().minFromSchoolStart()) percentage = numerator / denominator UIView.animate(withDuration: 1.5) { self.progressBar.center = CGPoint(x: (barStartingPoint) + Int(CGFloat(123).barRelativeToWidth * percentage), y: midPointY + Int(CGFloat(20).barRelativeToWidth)) self.progressBar.bounds.size = CGSize(width: CGFloat(20).barRelativeToWidth + (CGFloat(246).barRelativeToWidth * percentage), height: CGFloat(20).barRelativeToWidth) } } } func configureBarLabel(type: Int) { var classLabels = my_getPeriodsFromToday(type: type) let startingPosition = (deviceMax - Int(CGFloat(250).barRelativeToWidth)) / 2 let endingPosition = startingPosition + Int(CGFloat(250).barRelativeToWidth) var distance = Int() if classLabels.count > 1 { distance = (endingPosition - startingPosition) / ( classLabels.count - 1 ) for i in 0...( classLabels.count - 1 ) { let classLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 20)) classLabel.center = CGPoint(x: startingPosition + distance * i, y: Int(self.view.bounds.midY) + Int(CGFloat(50).barRelativeToWidth)) classLabel.textAlignment = .center classLabel.text = classLabels[i] classLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(19).relativeToWidth) classLabel.textColor = UIColor.white classLabel.my_dropShadow() todayClassLabel.addSubview(classLabel) view.addSubview(todayClassLabel) } } else { distance = endingPosition - startingPosition let classLabel = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat(distance), height: 30)) classLabel.center = CGPoint(x: (startingPosition + endingPosition) / 2, y: Int(self.view.bounds.midY) + Int(CGFloat(50).barRelativeToWidth)) classLabel.textAlignment = .center classLabel.text = classLabels[0] classLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(19).relativeToWidth) classLabel.textColor = UIColor.white classLabel.my_dropShadow() todayClassLabel.addSubview(classLabel) view.addSubview(todayClassLabel) } } @objc func fetchEvents() { self.configureEvents() // if CheckInternet.Connection() { // var date = Date() // var time = String() // var eventTitle = String() // var notification = Bool() // if let data = try? String(contentsOf: URL(string: "https://portola.epicteam.app/api/events")!) { // let jsonData = JSON(parseJSON: data).dictionaryValue["events"]! // // let array = jsonData.arrayValue // for events in array { // let dictionary = events.dictionaryObject! // if let dateGet = dictionary["date"] as? String { // // // let formatter = DateFormatter() // formatter.timeZone = Calendar.current.timeZone // formatter.locale = Calendar.current.locale // formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" // let UTCDate = formatter.date(from: dateGet) ?? Date.distantPast // let currentDate = Calendar.current.date(byAdding: .hour, value: -UTCDifference(), to: UTCDate) ?? Date.distantPast // date = currentDate // // } else { // date = Date.distantPast // } // if let timeGet = dictionary["time"] as? String { // time = timeGet // } else { // time = "N/A" // } // if let eventTitleGet = dictionary["title"] as? String { // eventTitle = eventTitleGet // } else { // eventTitle = "N/A" // } // if let notificationGet = dictionary["notify"] as? Bool { // notification = notificationGet // } // // let currentEvent = SchoolEvents() // currentEvent.date = date // currentEvent.time = time // currentEvent.title = eventTitle // currentEvent.notification = notification // schoolEvents.append(currentEvent) // // } // } // } else { // let ac = UIAlertController(title: "No Internet Connection", message: "Could not load any upcoming events because there is no Internet connection.", preferredStyle: .alert) // ac.addAction(UIAlertAction(title: "OK", style: .cancel)) // present(ac, animated: true) // } // // DispatchQueue.main.async { // self.configureEvents() // } } func configureEvents() { // if schoolEvents.count > 0 { // schoolEvents = schoolEvents.filter { // $0.date.noon >= Date().noon // // } // schoolEvents = schoolEvents.sorted(by: {$0.date < $1.date}) // for events in schoolEvents { // if let dayAway = my_daysAwayFromToday(date: events.date.noon) { // if dayAway == 0 { // eventTimes.append("TODAY, \(events.time.uppercased())") // } else if dayAway == 1 { // eventTimes.append("TOMORROW, \(events.time.uppercased())") // } else if dayAway < 7 { // let weekday = getWeekdayString(date: events.date, isUpper: true) // eventTimes.append("\(weekday), \(events.time.uppercased())") // } else { // let day = Calendar.current.component(.day, from: events.date) // let month = Calendar.current.component(.month, from: events.date) // let dateString = "\(month)/\(day)" // eventTimes.append("\(dateString), \(events.time.uppercased())") // } // } // eventTitles.append(events.title) // } // // // switch schoolEvents.count { // case 1: // self.eventTime1.text = eventTimes[0] // // self.eventTitle1.text = eventTitles[0] // // case 2: // self.eventTime1.text = eventTimes[0] // self.eventTime2.text = eventTimes[1] // self.eventTitle1.text = eventTitles[0] // self.eventTitle2.text = eventTitles[1] // // default: // self.eventTime1.text = eventTimes[0] // self.eventTime2.text = eventTimes[1] // self.eventTime3.text = eventTimes[2] // self.eventTitle1.text = eventTitles[0] // self.eventTitle2.text = eventTitles[1] // self.eventTitle3.text = eventTitles[2] // } // // // // } else { // // // } self.eventTime2.text = "INTEGRAL, AVAILABLE NOW" eventTime2.font = UIFont(name: "Lato-Light", size: CGFloat(24).relativeToWidth) } @objc func configureNextSchoolDayStart() { DispatchQueue.main.async { self.loadEndsLabel(text: "SCHOOL STARTS") } let startingDate = Date().noon var interval = 1 var dayType = 20 while dayType == 20 { let onDate = Calendar.current.date(byAdding: .day, value: interval, to: startingDate)! if onDate.isWeekend() { dayType = 20 } else { dayType = getDayType(date: onDate) } interval += 1 if dayType != 20 { //found a non-20 day let currentDate = onDate.noon let firstDayStartTime = uniq(source: my_getSchedule(type: dayType, date: currentDate)!).first! let time = timeStringFromDate(date: firstDayStartTime) DispatchQueue.main.async { self.loadTimeLeftLabel(text: time, size: CGFloat(140)) } if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day == 1 { DispatchQueue.main.async { self.loadMinutesLabel(text: "TOMORROW") } } else if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day! < 7 { DispatchQueue.main.async { self.loadMinutesLabel(text: getWeekdayString(date: currentDate, isUpper: true)) } } else { let formatter = DateFormatter() formatter.dateFormat = "M/d" let schoolStartsString = formatter.string(from: currentDate) DispatchQueue.main.async { self.loadMinutesLabel(text: "ON \(schoolStartsString)") } } } } } func loadTimeLeftLabel(text: String, size: CGFloat) { DispatchQueue.main.async { self.timeLeftLabel.text = text self.timeLeftLabel.font = UIFont(name: "Heebo-Light", size: size.relativeToWidth) self.timeLeftLabel.fadeIn() } } func loadEndsLabel(text: String) { DispatchQueue.main.async { self.endsLabel.text = text self.endsLabel.fadeIn() } } func loadMinutesLabel(text: String) { DispatchQueue.main.async { self.minutesLabel.text = text self.minutesLabel.fadeIn() } } @objc func configureTimeLeftLabel() { if Date() > lastDay && Date() < firstDay2019 || (Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .after) { loadEndsLabel(text: "SCHOOL STARTS IN") loadMinutesLabel(text: "DAYS") dateDifference = Calendar.current.dateComponents([.day], from: Date(), to: firstDay2019).day ?? 0 loadTimeLeftLabel(text: String(dateDifference), size: CGFloat(140)) } else { // print(Calendar.current.component(.day, from: Date())) print(Calendar.current.component(.day, from: lastDay)) if Date().isSchoolDay() { switch timeOfDay! { case .before: let startTime = uniq(source: my_getSchedule(type: today, date: nil)!).first! loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140)) loadEndsLabel(text: "SCHOOL STARTS") loadMinutesLabel(text: "TODAY") case .during: fetchTimeLeft() case .after: if tomorrow == 20 { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } else { if Calendar.current.component(.weekday, from: Date()) == 6 { if nextMonday == 20 { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } else { let startTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first! loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140)) loadEndsLabel(text: "SCHOOL STARTS") loadMinutesLabel(text: "MONDAY") } } else { let startTime = uniq(source: my_getSchedule(type: tomorrow, date: Date().tomorrow)!).first! loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140)) loadEndsLabel(text: "SCHOOL STARTS") loadMinutesLabel(text: "TOMORROW") } } } } else { if Date().isWeekend() { if nextMonday == 20 { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } else { let mondayStartTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first! loadTimeLeftLabel(text: timeStringFromDate(date: mondayStartTime), size: 140) loadEndsLabel(text: "SCHOOL STARTS") switch Calendar.current.component(.weekday, from: Date()) { case 7: loadMinutesLabel(text: "MONDAY") case 1: loadMinutesLabel(text: "TOMORROW") default: loadMinutesLabel(text: "MONDAY") } } } else { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } } } } @objc func fetchTimeLeft() { var label = String() var end = String() if let newSchedule = my_getSchedule(type: today, date: nil) { let schedule = uniq(source: newSchedule) for i in 0...schedule.count - 1 { if schedule[i] >= Date().localTime() { if Calendar.current.component(.day, from: Date()) + 1 == Calendar.current.component(.day, from: lastDay) && Date().getRelativeTime() == .during { if let seconds = Calendar.current.dateComponents([.second], from: Date().localTime(), to: schedule.last!).second { if seconds >= 10000 { loadTimeLeftLabel(text: String(seconds), size: 90) loadMinutesLabel(text: "SECONDS") } else if seconds >= 1000 { loadTimeLeftLabel(text: String(seconds), size: 120) loadMinutesLabel(text: "SECONDS") } else { loadTimeLeftLabel(text: String(seconds), size: 160) loadMinutesLabel(text: "SECONDS") } loadEndsLabel(text: "SCHOOL YEAR ENDS IN") } } else { if let minutes = Calendar.current.dateComponents([.minute], from: Date().localTime(), to: schedule[i]).minute { if minutes == 0 { loadTimeLeftLabel(text: "<1", size: 160) loadMinutesLabel(text: "MINUTE") } else if minutes == 1 { loadTimeLeftLabel(text: String(minutes), size: 160) loadMinutesLabel(text: "MINUTE") } else { loadTimeLeftLabel(text: String(minutes), size: 160) loadMinutesLabel(text: "MINUTES") } if let rawLabel = my_getStartEndPeriodLabel(type: today) { let rawLabelNumber = rawLabel[i - 1] label = rawLabelNumber.getPeriodLabel() if let startEndLabel = my_getStartEndLabel(type: today) { let isStart = startEndLabel[i - 1] end = isStart.startEndLabelFromBool() loadEndsLabel(text: "\(label) \(end) IN") break } } } } } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // AthleticsViewController.swift // PHS App // // Created by <NAME> on 8/17/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import Segmentio class AthleticsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBAction func dismiss(_ sender: Any) { dismiss(animated: true) } @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var segmentioView: Segmentio! var content = [SegmentioItem]() let allIcons = ["Baseball", "Boys Basketball", "Track", "Football", "Girls Golf", "Girls Lacrosse", "Boys Soccer", "Softball", "Girls Tennis", "Swim", "Cross Country", "Girls Volleyball", "Boys Water Polo","Wrestling", "Girls Basketball", "Boys Golf", "Boys Lacrosse", "Girls Soccer", "Boys Tennis", "Girls Water Polo", "Boys Volleyball"] let allImages: [UIImage] = [ UIImage(named: "Baseball")!, UIImage(named: "Basketball")!, UIImage(named: "Track")!, UIImage(named: "Football")!, UIImage(named: "Golf")!, UIImage(named: "Lacrosse")!, UIImage(named: "Soccer")!, UIImage(named: "Softball")!, UIImage(named: "Tennis")!, UIImage(named: "Swim")!, UIImage(named: "CrossCountry")!, UIImage(named: "Volleyball")!, UIImage(named: "Water Polo")!, UIImage(named: "Wrestling")!, UIImage(named: "Basketball")!, UIImage(named: "Golf")!, UIImage(named: "Lacrosse")!, UIImage(named: "Soccer")!, UIImage(named: "Tennis")!, UIImage(named: "Water Polo")!, UIImage(named: "Volleyball")! ] let fallIndex: [Int] = [3, 4, 8, 10, 11, 12] let winterIndex: [Int] = [1, 6, 17, 14, 13, 19] let springIndex: [Int] = [0, 2, 5, 7, 9, 15, 16, 18, 20] var fallIcons = [String]() var winterIcons = [String]() var springIcons = [String]() var fallImages = [UIImage]() var winterImages = [UIImage]() var springImages = [UIImage]() var onDisplay = [String]() var displayedImages = [UIImage]() var sportToPass = String() override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() setSegmentedControl() collectionView.delegate = self collectionView.dataSource = self segmentioView.selectedSegmentioIndex = 0 onDisplay = allIcons displayedImages = allImages for index in fallIndex { fallIcons.append(allIcons[index]) fallImages.append(allImages[index]) } for index in winterIndex { winterIcons.append(allIcons[index]) winterImages.append(allImages[index]) } for index in springIndex { springIcons.append(allIcons[index]) springImages.append(allImages[index]) } let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 5 layout.itemSize = CGSize(width: self.view.bounds.width / 2, height: self.view.bounds.width / 2) collectionView.allowsMultipleSelection = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) for cell in collectionView.indexPathsForSelectedItems ?? [] { collectionView.deselectItem(at: cell, animated: true) let deselectedCell = collectionView.cellForItem(at: cell) deselectedCell?.backgroundColor = UIColor.white } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) segmentioView.valueDidChange = { segmentio, segmentIndex in switch segmentIndex { case 0: self.onDisplay = self.allIcons self.displayedImages = self.allImages case 1: self.onDisplay = self.fallIcons self.displayedImages = self.fallImages case 2: self.onDisplay = self.winterIcons self.displayedImages = self.winterImages case 3: self.onDisplay = self.springIcons self.displayedImages = self.springImages default: self.onDisplay = self.allIcons self.displayedImages = self.allImages } self.collectionView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setSegmentedControl() { view.addSubview(segmentioView) let position = SegmentioPosition.dynamic let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white) let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none) let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)) segmentioView.selectedSegmentioIndex = 0 let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: ( defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)), selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white), highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white) ) ,animationDuration: 0.2) let allItem = SegmentioItem(title: "ALL", image: nil) let fallItem = SegmentioItem(title: "FALL", image: nil) let winterItem = SegmentioItem(title: "WINTER", image: nil) let springItem = SegmentioItem(title: "SPRING", image: nil) content = [allItem, fallItem, winterItem, springItem] segmentioView.setup(content: content, style: .onlyLabel, options: options) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sports", for: indexPath) as! AthleticsCollectionViewCell cell.iconImage.image = displayedImages[indexPath.item] cell.iconLabel.text = onDisplay[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.width / 2) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return onDisplay.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3) let item = cell as! AthleticsCollectionViewCell sportToPass = item.iconLabel.text! performSegue(withIdentifier: "athleticDetail", sender: nil) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.backgroundColor = UIColor.white } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "athleticDetail" { let vc = segue.destination as! AthleticsDetailViewController vc.sport = sportToPass } } } <file_sep>// // TodayViewController.swift // PHSWidget // // Created by <NAME> on 10/16/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import NotificationCenter enum dayType { case today case tomorrow case nextMonday case custom } func getDayType(date: Date) -> Int { var isSpecial = false for days in specialDays { if days.date.noon == date.noon { isSpecial = true return Int(days.type) } } if isSpecial == false { return 0 } } var today = Int() var tomorrow = Int() var nextMonday = Int() var specialDays = [SpecialDays]() class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var endsLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var minutesLabel: UILabel! var day = Calendar.current.component(.day, from: Date()) var minute = Calendar.current.component(.minute, from: Date()) var timeOfDay: relativeTime? override func viewDidLoad() { super.viewDidLoad() self.timeOfDay = Date().timeOfSchoolDay() loadSpecialDays() getTodayType() configureTimeLeftLabel() Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) if Date().isSchoolDay() { if Date().timeOfSchoolDay() == relativeTime.during { fetchTimeLeft() } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) } func loadSpecialDays() { if let data = Bundle.main.path(forResource: "specialDays", ofType: "txt") { if let content = try? String(contentsOfFile: data) { if let jsonData = JSON(parseJSON: content).dictionaryValue["specialDays"]?.arrayValue { for days in jsonData { let detail = days.dictionaryObject! let object = SpecialDays() if let date = detail["date"] as? String { let formatter = DateFormatter() formatter.dateFormat = "yyyy/M/dd" formatter.timeZone = Calendar.current.timeZone formatter.locale = Calendar.current.locale object.date = formatter.date(from: date)! } if let type = detail["case"] as? Int { object.type = type } specialDays.append(object) } } } } else { print("no") } } func getTodayType() { today = 0 tomorrow = 0 nextMonday = 0 for days in specialDays { if Date().noon == days.date.noon { today = days.type } if Date().tomorrow == days.date.noon { tomorrow = days.type } if Date().nextMonday().noon == days.date.noon { nextMonday = days.type } } } @objc func update() { if Calendar.current.component(.day, from: Date()) != day { getTodayType() timeOfDay = Date().timeOfSchoolDay() configureTimeLeftLabel() day = Calendar.current.component(.day, from: Date()) } else { if timeOfDay != Date().timeOfSchoolDay() { timeOfDay = Date().timeOfSchoolDay() self.configureTimeLeftLabel() } else { if minute != Calendar.current.component(.minute, from: Date()) { if Date().isSchoolDay() { if timeOfDay == .during { fetchTimeLeft() } } minute = Calendar.current.component(.minute, from: Date()) } } } } @objc func configureTimeLeftLabel() { if Date().isSchoolDay() { switch timeOfDay! { case .before: let startTime = uniq(source: my_getSchedule(type: today, date: nil)!).first! loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140)) loadEndsLabel(text: "SCHOOL STARTS") loadMinutesLabel(text: "TODAY") case .during: fetchTimeLeft() case .after: if tomorrow == 20 { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } else { if Calendar.current.component(.weekday, from: Date()) == 6 { if nextMonday == 20 { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } else { let startTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first! loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140)) loadEndsLabel(text: "SCHOOL STARTS") loadMinutesLabel(text: "MONDAY") } } else { let startTime = uniq(source: my_getSchedule(type: tomorrow, date: Date().tomorrow)!).first! loadTimeLeftLabel(text: timeStringFromDate(date: startTime), size: CGFloat(140)) loadEndsLabel(text: "SCHOOL STARTS") loadMinutesLabel(text: "TOMORROW") } } } } else { if Date().isWeekend() { if nextMonday == 20 { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } else { let mondayStartTime = uniq(source: my_getSchedule(type: nextMonday, date: Date().nextMonday())!).first! loadTimeLeftLabel(text: timeStringFromDate(date: mondayStartTime), size: 140) loadEndsLabel(text: "SCHOOL STARTS") switch Calendar.current.component(.weekday, from: Date()) { case 7: loadMinutesLabel(text: "MONDAY") case 1: loadMinutesLabel(text: "TOMORROW") default: loadMinutesLabel(text: "MONDAY") } } } else { performSelector(inBackground: #selector(configureNextSchoolDayStart), with: nil) } } } @objc func fetchTimeLeft() { var label = String() var end = String() if let newSchedule = my_getSchedule(type: today, date: nil) { let schedule = uniq(source: newSchedule) for i in 0...schedule.count - 1 { if schedule[i] >= Date().localTime() { if let minutes = Calendar.current.dateComponents([.minute], from: Date().localTime(), to: schedule[i]).minute { if minutes == 0 { loadTimeLeftLabel(text: "<1", size: 160) loadMinutesLabel(text: "MINUTE") } else if minutes == 1 { loadTimeLeftLabel(text: String(minutes), size: 160) loadMinutesLabel(text: "MINUTE") } else { loadTimeLeftLabel(text: String(minutes), size: 160) loadMinutesLabel(text: "MINUTES") } if let rawLabel = my_getStartEndPeriodLabel(type: today) { let rawLabelNumber = rawLabel[i - 1] label = rawLabelNumber.getPeriodLabel() if let startEndLabel = my_getStartEndLabel(type: today) { let isStart = startEndLabel[i - 1] end = isStart.startEndLabelFromBool() loadEndsLabel(text: "\(label) \(end) IN") break } } } } } } } @objc func configureNextSchoolDayStart() { DispatchQueue.main.async { self.loadEndsLabel(text: "SCHOOL STARTS") } let startingDate = Date().noon var interval = 1 var dayType = 20 while dayType == 20 { let onDate = Calendar.current.date(byAdding: .day, value: interval, to: startingDate)! if onDate.isWeekend() { dayType = 20 } else { dayType = getDayType(date: onDate) } interval += 1 if dayType != 20 { //found a non-20 day let currentDate = onDate.noon let firstDayStartTime = uniq(source: my_getSchedule(type: dayType, date: currentDate)!).first! let time = timeStringFromDate(date: firstDayStartTime) DispatchQueue.main.async { self.loadTimeLeftLabel(text: time, size: CGFloat(140)) } if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day == 1 { DispatchQueue.main.async { self.loadMinutesLabel(text: "TOMORROW") } } else if Calendar.current.dateComponents([.day], from: startingDate, to: currentDate).day! < 7 { DispatchQueue.main.async { self.loadMinutesLabel(text: getWeekdayString(date: currentDate, isUpper: true)) } } else { let formatter = DateFormatter() formatter.dateFormat = "M/d" let schoolStartsString = formatter.string(from: currentDate) DispatchQueue.main.async { self.loadMinutesLabel(text: "ON \(schoolStartsString)") } } } } } func loadTimeLeftLabel(text: String, size: CGFloat) { DispatchQueue.main.async { self.timeLabel.text = text } } func loadEndsLabel(text: String) { DispatchQueue.main.async { self.endsLabel.text = text } } func loadMinutesLabel(text: String) { DispatchQueue.main.async { self.minutesLabel.text = text } } func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.newData) } } <file_sep>// // my_UTC.swift // PHS App // // Created by <NAME> on 8/6/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension Date { func UTC() -> Date { if let date = Calendar.current.date(byAdding: .hour, value: UTCDifference(), to: self) { return date } else { return Date() } } } <file_sep>// // my_dropShadow.swift // PHS App // // Created by <NAME> on 7/22/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit extension UIView { func my_dropShadow() { let size = layer.frame.size.height self.layer.masksToBounds = false self.layer.shadowColor = UIColor.gray.cgColor self.layer.shadowOffset = CGSize(width: size * 0.04, height: size * 0.04) self.layer.shadowRadius = size * 0.05 self.layer.shadowOpacity = 0.8 } } <file_sep>// // DayType+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/10/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension DayType { @nonobjc public class func fetchRequest() -> NSFetchRequest<DayType> { return NSFetchRequest<DayType>(entityName: "DayType") } @NSManaged public var type: Int16 @NSManaged public var date: Date } <file_sep>// // Houses.swift // PHS App // // Created by <NAME> on 10/3/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class Houses: NSObject { var points = Int() var name = String() } <file_sep>// // my_daysAwayFromToday.swift // PHS App // // Created by <NAME> on 7/29/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func my_daysAwayFromToday(date: Date) -> Int? { let today = Date().noon let dateGet = date.noon if let interval = Calendar.current.dateComponents([.day], from: today, to: dateGet).day { return interval } else { return nil } } <file_sep>// // my_setNavigationBar.swift // PHS App // // Created by <NAME> on 7/25/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit extension UINavigationBar { func my_setNavigationBar() { self.setBackgroundImage(UIImage(), for: .default) self.shadowImage = UIImage() self.isTranslucent = true } static func createNavigationBar() -> UINavigationBar { let navigationBar = UINavigationBar() navigationBar.my_setNavigationBar() return navigationBar } } <file_sep>// // HomeScrollViewController.swift // PHS App // // Created by <NAME> on 9/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class HomeScrollViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, UIScrollViewDelegate { var pageContainer = UIPageViewController(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation(rawValue: 0)!, options: nil) @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var distanceConstant: NSLayoutConstraint! fileprivate lazy var pages: [UIViewController] = { return [ storyboard!.instantiateViewController(withIdentifier: "home"), storyboard!.instantiateViewController(withIdentifier: "bellSchedule") ] }() var currentPage = 0 override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // if self.distanceConstant.constant >= self.distanceConstant.constant.barRelativeToWidth { // self.distanceConstant.constant = self.distanceConstant.constant.relativeToWidth // } else { // self.distanceConstant.constant = self.distanceConstant.constant + CGFloat(20) // } } override func viewDidLoad() { super.viewDidLoad() pageContainer.delegate = self pageContainer.dataSource = self if let firstVC = pages.first { pageContainer.setViewControllers([firstVC], direction: .forward, animated: true, completion: nil) } view.addSubview(pageContainer.view) view.bringSubviewToFront(pageControl) for subview in pageContainer.view.subviews { if let scrollView = subview as? UIScrollView { scrollView.delegate = self break } } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if (currentPage == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width) { scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0); } else if (currentPage == pages.count - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width) { scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0); } } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if (currentPage == 0 && scrollView.contentOffset.x <= scrollView.bounds.size.width) { targetContentOffset.pointee = CGPoint(x: scrollView.bounds.size.width, y: 0); } else if (currentPage == pages.count - 1 && scrollView.contentOffset.x >= scrollView.bounds.size.width) { targetContentOffset.pointee = CGPoint(x: scrollView.bounds.size.width, y: 0); } } // func presentationCount(for pageViewController: UIPageViewController) -> Int { // return pages.count // } // // func presentationIndex(for pageViewController: UIPageViewController) -> Int { // return currentPage // } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if (!completed) { return } if let currentViewController = pageContainer.viewControllers!.first { if let currentIndex = pages.index(of: currentViewController) { currentPage = currentIndex } } pageControl.currentPage = currentPage } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = pages.index(of: viewController) else {return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else {return nil } guard pages.count > previousIndex else {return nil} return pages[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = pages.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 guard nextIndex < pages.count else { return nil } guard pages.count > nextIndex else { return nil} return pages[nextIndex] } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // my_removeDuplicates.swift // PHS App // // Created by <NAME> on 9/12/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit func uniq<S: Sequence, T: Hashable>(source: S) -> [T] where S.Iterator.Element == T { var buffer = [T]() var added = Set<T>() for elem in source { if !added.contains(elem) { buffer.append(elem) added.insert(elem) } } return buffer } <file_sep>// // my_minutesFromSchoolStart.swift // PHS App // // Created by <NAME> on 8/4/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension Date { func minFromSchoolStart() -> Int { if today == 20 || !self.isSchoolDay() { return 1 } else { let now = self let todaySchedule = my_getSchedule(type: today, date: self) let start = todaySchedule!.first! let interval = Calendar.current.dateComponents([.minute], from: start, to: now).minute return interval! } } } <file_sep>// // CalendarViewController.swift // PHS App // // Created by <NAME> on 8/13/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import JTAppleCalendar class CalendarViewController: UIViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate { @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var calendarView: JTAppleCalendarView! @IBOutlet weak var monthLabel: UILabel! @IBOutlet weak var calendarHolder: UIView! @IBOutlet weak var leftArrow: UIImageView! @IBOutlet weak var rightArrow: UIImageView! @IBOutlet weak var noSchoolLabel: UILabel! @IBAction func dismiss(_ sender: Any) { dismiss(animated: true) } @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var dateDetail: UIView! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var weekdayLabel: UILabel! @IBOutlet weak var periodLabel: UILabel! @IBOutlet weak var startEndLabel: UILabel! let formatter = DateFormatter() var specialDates = [Date]() var dateRange = [Date]() func initializeCalendar() { calendarHolder.layer.shadowColor = UIColor.gray.cgColor calendarHolder.layer.shadowRadius = 4 calendarHolder.layer.shadowOpacity = 0.35 calendarHolder.layer.shadowOffset = CGSize(width: 5, height: 5) calendarView.calendarDelegate = self calendarView.calendarDataSource = self calendarView.minimumInteritemSpacing = 0 calendarView.minimumLineSpacing = 0 calendarView.allowsMultipleSelection = false calendarView.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) calendarView.visibleDates { (visibleDates) in let date = visibleDates.monthDates.first!.date self.formatter.dateFormat = "MMMM" self.monthLabel.text = self.formatter.string(from: date).uppercased() } dateDetail.layer.shadowColor = UIColor.gray.cgColor dateDetail.layer.shadowRadius = 4 dateDetail.layer.shadowOpacity = 0.35 dateDetail.layer.shadowOffset = CGSize(width: 5, height: 5) } override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() backgroundView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.15) initializeCalendar() for objects in specialDays { specialDates.append(objects.date.noon) } let leftGesture = UITapGestureRecognizer(target: self, action: #selector(leftTapped)) leftGesture.delegate = self leftArrow.addGestureRecognizer(leftGesture) let rightGesture = UITapGestureRecognizer(target: self, action: #selector(rightTapped)) rightGesture.delegate = self rightArrow.addGestureRecognizer(rightGesture) formatter.dateFormat = "yyyy MM dd" formatter.timeZone = Calendar.current.timeZone formatter.locale = Calendar.current.locale let startDate = formatter.date(from: "2019 08 01")! let endDate = formatter.date(from: "2020 08 31")! dateRange = calendarView.generateDateRange(from: startDate, to: endDate) configureDayDetail(withDate: Date().noon) calendarView.scrollToDate(Date(), animateScroll: false) } func configureDayDetail(withDate date: Date) { periodLabel.isHidden = false startEndLabel.isHidden = false noSchoolLabel.isHidden = true var dayType = getDayType(date: date) if dayType == 0 { dayType = Calendar.current.component(.weekday, from: date) + 20 } dateLabel.text = "\(Calendar.current.component(.month, from: date))/\(Calendar.current.component(.day, from: date))" weekdayLabel.text = getWeekdayString(date: date, isUpper: true) if date.isSchoolDay() { let periods = my_getPeriodsFromToday(type: dayType) periodLabel.text = periods.joined(separator: ", ") let schedule = my_getSchedule(type: dayType, date: nil) let start = schedule!.first! let end = schedule!.last! let hourStart = Calendar.current.component(.hour, from: start) let minuteStart = Calendar.current.component(.minute, from: start) let hourEnd = Calendar.current.component(.hour, from: end) let minuteEnd = Calendar.current.component(.minute, from: end) var startComponents = DateComponents() startComponents.year = Calendar.current.component(.year, from: date) startComponents.month = Calendar.current.component(.month, from: date) startComponents.day = Calendar.current.component(.day, from: date) startComponents.hour = hourStart - UTCDifference() startComponents.minute = minuteStart var endComponents = DateComponents() endComponents.year = Calendar.current.component(.year, from: date) endComponents.month = Calendar.current.component(.month, from: date) endComponents.day = Calendar.current.component(.day, from: date) endComponents.hour = hourEnd - UTCDifference() endComponents.minute = minuteEnd let formatter = DateFormatter() formatter.timeZone = Calendar.current.timeZone formatter.dateFormat = "h:mm a" let newStart = Calendar.current.date(from: startComponents)! let newEnd = Calendar.current.date(from: endComponents)! print(newStart, newEnd) startEndLabel.text = "\(formatter.string(from: newStart)) - \(formatter.string(from: newEnd))" } else { periodLabel.isHidden = true startEndLabel.isHidden = true noSchoolLabel.isHidden = false } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if calendarView.visibleDates().indates.count > 0 { if calendarView.visibleDates().indates.first!.date < dateRange.first! { leftArrow.isHidden = true } else { leftArrow.isHidden = false } } else { if calendarView.visibleDates().monthDates.first!.date < dateRange.first! { leftArrow.isHidden = true } else { leftArrow.isHidden = false } } } @objc func leftTapped() { let scrollDate = calendarView.visibleDates().indates.first!.date calendarView.scrollToDate(scrollDate) } @objc func rightTapped() { let scrollDate = calendarView.visibleDates().outdates.first!.date print(scrollDate) calendarView.scrollToDate(scrollDate) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension CalendarViewController: JTAppleCalendarViewDelegate, JTAppleCalendarViewDataSource { func handleCellConfiguration(view: JTAppleCell?, cellState: CellState) { guard let validCell = view as? CalendarCollectionViewCell else {return} if cellState.date.noon == Date().noon { validCell.selectedView.isHidden = false validCell.dateLabel.textColor = UIColor.white } else { if validCell.isSelected { validCell.dateLabel.textColor = UIColor.white validCell.selectedView.isHidden = false } else { if cellState.dateBelongsTo == .thisMonth { validCell.dateLabel.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) } else { validCell.dateLabel.textColor = UIColor.lightGray.withAlphaComponent(0.5) } validCell.selectedView.isHidden = true } } } func configureDots(view: JTAppleCell?, cellState: CellState) { guard let validCell = view as? CalendarCollectionViewCell else {return} if !specialDates.contains(cellState.date.noon) { validCell.dotView.isHidden = true } else { validCell.dotView.isHidden = false if cellState.dateBelongsTo == .thisMonth { validCell.dotView.backgroundColor = validCell.dotView.backgroundColor } else { validCell.dotView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) } } } func configureDotsWhenScroll(view: JTAppleCalendarView?, visibleDates: DateSegmentInfo) { for days in visibleDates.monthDates { guard let cell = view?.cellForItem(at: days.indexPath) as? CalendarCollectionViewCell else {return} if cell.dotView.isHidden == false { cell.dotView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) } } for days in visibleDates.indates + visibleDates.outdates { guard let cell = view?.cellForItem(at: days.indexPath) as? CalendarCollectionViewCell else {return} if cell.dotView.isHidden == false { cell.dotView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) } } } func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) { let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! CalendarCollectionViewCell cell.dateLabel.text = cellState.text handleCellConfiguration(view: cell, cellState: cellState) configureDots(view: cell, cellState: cellState) } func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell { let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! CalendarCollectionViewCell cell.dateLabel.text = cellState.text handleCellConfiguration(view: cell, cellState: cellState) configureDots(view: cell, cellState: cellState) return cell } func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleCell?, cellState: CellState) { handleCellConfiguration(view: cell, cellState: cellState) configureDayDetail(withDate: date) } func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleCell?, cellState: CellState) { handleCellConfiguration(view: cell, cellState: cellState) } func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) { let date = visibleDates.monthDates.first!.date formatter.dateFormat = "MMMM" monthLabel.text = formatter.string(from: date).uppercased() configureDotsWhenScroll(view: calendar, visibleDates: visibleDates) if visibleDates.indates.count > 0 { if visibleDates.indates.first!.date < dateRange.first! { leftArrow.isHidden = true } else { leftArrow.isHidden = false } } else { if visibleDates.monthDates.first!.date < dateRange.first! { leftArrow.isHidden = true } else { leftArrow.isHidden = false } } if visibleDates.outdates.first!.date > dateRange.last! { rightArrow.isHidden = true } else { rightArrow.isHidden = false } } func calendarDidScroll(_ calendar: JTAppleCalendarView) { calendarView.deselectAllDates() } func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters { formatter.dateFormat = "yyyy MM dd" formatter.timeZone = Calendar.current.timeZone formatter.locale = Calendar.current.locale let startDate = formatter.date(from: "2019 08 01")! let endDate = formatter.date(from: "2020 08 31")! let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate) return parameters } } <file_sep>// // UnderConstructionView.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import MessageUI class UnderConstructionView: UIView, UIGestureRecognizerDelegate, MFMailComposeViewControllerDelegate { @IBOutlet var contentView: UnderConstructionView! @IBOutlet weak var underConstructionLabel: UILabel! @IBOutlet weak var bottomLabel: UILabel! var buttonView = UIView() var buttonLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { Bundle.main.loadNibNamed("UnderConstructionView", owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] underConstructionLabel.font = underConstructionLabel.font.withSize(CGFloat(24).relativeToWidth) buttonView.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width * 0.45, height: CGFloat(40).relativeToWidth) buttonView.center = CGPoint(x: UIScreen.main.bounds.midX, y: bottomLabel.frame.maxY + CGFloat(35).relativeToWidth) buttonView.clipsToBounds = true buttonView.layer.cornerRadius = buttonView.frame.height / 2 buttonView.layer.borderWidth = 1 buttonView.layer.borderColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor buttonLabel.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width * 0.45, height: CGFloat(40).relativeToWidth) buttonLabel.center = CGPoint(x: UIScreen.main.bounds.width * 0.45 * 0.5, y: CGFloat(40).relativeToWidth / 2) buttonLabel.text = "JOIN US" buttonLabel.textAlignment = .center buttonLabel.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth) buttonLabel.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) buttonView.addSubview(buttonLabel) buttonView.bringSubviewToFront(buttonLabel) self.addSubview(buttonView) buttonView.isUserInteractionEnabled = true let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(joinUsTapped)) gestureRecognizer.delegate = self buttonView.addGestureRecognizer(gestureRecognizer) } @objc func joinUsTapped() { buttonView.backgroundColor = UIColor(red:0.82, green:0.82, blue:0.82, alpha: 0.6) let address = "<EMAIL>" if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients([address]) mail.setSubject("Interested in Joining Portola App Team") self.parentViewController?.present(mail, animated: true) } else { } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { buttonView.backgroundColor = UIColor.white self.parentViewController?.dismiss(animated: true) } } <file_sep>// // my_getPeriodsFromToday.swift // PHS App // // Created by <NAME> on 7/31/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func my_getPeriodsFromToday(type: Int) -> [String] { switch type { case 0: return defaultDays() case 1: //pep assembly odd return ["1", "A", "PA", "3", "5", "7"] case 2: //pep assembly even return ["2", "A", "PA", "4", "6", "8"] case 3: //extended lunch odd return ["1", "OH", "3", "L", "5", "7"] case 4: //extended lunch even return ["2", "A", "4", "L", "6", "8"] case 5: //finals type 1 return ["1", "3", "7"] case 6: //finals type 2 return ["5", "6", "8"] case 7: //finals two periods return ["2", "4"] case 8: //minimum 1-8 return ["1", "2", "3", "4", "5", "6", "7", "8"] case 9: //minimum odd return ["1", "3", "5", "7"] case 10: //minimum even return ["2", "4", "6", "8"] case 11: //PSAT 9 return ["PSAT 9", "OH", "2", "4", "6", "8"] case 12: //PE testing return ["PE 9", "OH", "1", "3", "5", "7"] case 13: //first 2 days of school return ["A", "1", "2", "3", "4", "5", "6", "7", "8"] case 14: //Hour of Code return ["2", "A", "4", "6", "8"] case 15: //Passion Day return ["A", "S1", "S2", "S3"] case 16: //Pre Testing return ["1", "A", "2", "3", "5", "7"] case 17: //Testing2018/ return ["TEST", "OH", "4", "6", "8"] case 18: //CAASPP ODD return ["TEST","11", "OH", "1", "3", "5", "7"] case 19: //CAASPP EVEN return ["TEST", "11", "OH", "2", "4", "6", "8"] case 20: //NO SCHOOL return ["NO SCHOOL TODAY"] case 21: //fine arts assembly return ["2", "A/4", "A/4", "6", "8"] case 22: //monday schedule return ["1", "2", "3", "4", "5", "6", "7", "8"] case 23: //tuesday schedule return ["1", "A", "3", "5", "7"] case 24: //wednesday schedule return ["2", "OH", "4", "6", "8"] case 25: //thursday schedule return ["1", "OH", "3", "5", "7"] case 26: //friday schedule return ["2", "A", "4", "6", "8"] case 27: //thursday advisement return ["1", "A", "3", "5", "7"] case 28: //friday OH return ["2", "OH", "4", "6", "8"] case 29: //Super late start return ["2", "4", "6", "8"] default: return defaultDays() } } func defaultDays() -> [String] { switch Calendar.current.component(.weekday, from: Date()) { case 1, 7: return ["NO SCHOOL TODAY"] case 2: return ["1", "2", "3", "B", "4", "5", "L", "6", "7", "8"] case 3: return ["1", "A", "3", "5", "7"] case 4: return ["2", "OH", "4", "6", "8"] case 5: return ["1", "OH", "3", "5", "7"] case 6: return ["2", "A", "4", "6", "8"] default: return ["Error"] } } <file_sep># Portolapp The iOS Version of the Portolapp, an app to make students' lives easier at Portola High School. <h2>Features</h2> Automatic school scheduling Class start and end reminders Push notifications for administration School calendar and bell checks for each day Digital identification cards with scannable barcodes Athletics reminders, locations, and times, as well as scores and overall league records School newspaper publications <h2>Building</h2> This is a project based in Swift, meaning that you must install Xcode running on MacOS X, and initialize Cocoapods.\ After pulling from the repository, run ``` pod install ``` in the command line of your choice to install needed dependencies. After fixing any errors, run the app on the iOS simulator. <file_sep>// // User+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(User) public class User: NSManagedObject { } <file_sep>// // PickTeachersViewController.swift // PHS App // // Created by <NAME> on 8/19/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreData class PickTeachersViewController: UIViewController { @IBOutlet weak var yourTeachers: UILabel! @IBOutlet weak var prevButton: UIButton! @IBAction func prevTapped(_ sender: Any) { if isFreshLaunch { let _ = navigationController?.popViewController(animated: true) } else { if isSecondScreen { dismiss(animated: true) } } } @IBOutlet weak var p1label: UILabel! @IBOutlet weak var p2Label: UILabel! @IBOutlet weak var p3Label: UILabel! @IBOutlet weak var p4Label: UILabel! @IBOutlet weak var p5Label: UILabel! @IBOutlet weak var p6Label: UILabel! @IBOutlet weak var p7Label: UILabel! @IBOutlet weak var p8Label: UILabel! @IBOutlet weak var p1Class: UILabel! @IBOutlet weak var p2Class: UILabel! @IBOutlet weak var p3Class: UILabel! @IBOutlet weak var p4Class: UILabel! @IBOutlet weak var p5Class: UILabel! @IBOutlet weak var p6Class: UILabel! @IBOutlet weak var p7Class: UILabel! @IBOutlet weak var p8Class: UILabel! @IBOutlet weak var p1TeacherLabel: UILabel! @IBOutlet weak var p2TeacherLabel: UILabel! @IBOutlet weak var p3TeacherLabel: UILabel! @IBOutlet weak var p4TeacherLabel: UILabel! @IBOutlet weak var p5TeacherLabel: UILabel! @IBOutlet weak var p6TeacherLabel: UILabel! @IBOutlet weak var p7TeacherLabel: UILabel! @IBOutlet weak var p8TeacherLabel: UILabel! @IBAction func p1Tapped(_ sender: Any) { period = 1 buttonTapped(period: 1) } @IBAction func p2Tapped(_ sender: Any) { period = 2 buttonTapped(period: 2) } @IBAction func p3Tapped(_ sender: Any) { period = 3 buttonTapped(period: 3) } @IBAction func p4Tapped(_ sender: Any) { period = 4 buttonTapped(period: 4) } @IBAction func p5Tapped(_ sender: Any) { period = 5 buttonTapped(period: 5) } @IBAction func p6Tapped(_ sender: Any) { period = 6 buttonTapped(period: 6) } @IBAction func p7Tapped(_ sender: Any) { period = 7 buttonTapped(period: 7) } @IBAction func p8Tapped(_ sender: Any) { period = 8 buttonTapped(period: 8) } @IBOutlet weak var p1Button: UIButton! @IBOutlet weak var p2Button: UIButton! @IBOutlet weak var p3Button: UIButton! @IBOutlet weak var p4Button: UIButton! @IBOutlet weak var p5Button: UIButton! @IBOutlet weak var p6Button: UIButton! @IBOutlet weak var p7Button: UIButton! @IBOutlet weak var p8Button: UIButton! @IBOutlet weak var skipButton: UIButton! var isPrevButtonHidden = false @IBAction func skipTapped(_ sender: Any) { if isFreshLaunch { let ac = UIAlertController(title: "Skip this page?", message: "Entering you teachers can make the app experience more personalized", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Stay", style: .cancel)) ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { (_) in for i in 0...7 { self.myTeachers[i] = nil self.teacherLabels[i].text = "CLICK TO SELECT" } self.performSegue(withIdentifier: "skipToWelcome", sender: nil) })) present(ac, animated: true) } else { if isSecondScreen { for i in 0...7 { self.myTeachers[i] = nil self.teacherLabels[i].text = "CLICK TO SELECT" } self.performSegue(withIdentifier: "skipFromSecondScreen", sender: nil) } else { dismiss(animated: true) } } } @IBAction func nextTapped(_ sender: Any) { var shouldPerformSegue = true for i in 0...7 { if buttons[i].isEnabled == true { if myTeachers[i] == nil { let ac = UIAlertController(title: "Missing Fields", message: "Make sure you fill in all your teachers before continuing.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) shouldPerformSegue = false } else { continue } } else { continue } } if shouldPerformSegue { if isFreshLaunch { performSegue(withIdentifier: "finishToWelcome", sender: nil) } else { if isPageEditing { performSegue(withIdentifier: "unwindToTeacherPage", sender: nil) } else { print("should be here") performSegue(withIdentifier: "newInfoSaved", sender: nil) } } } } override var prefersHomeIndicatorAutoHidden: Bool { return true } func buttonTapped(period: Int) { if classes[period - 1] == nil { subject = "All" } else { let selectedClass = classes[period - 1] if subjects.contains(selectedClass!) { subject = selectedClass! } else if vapa.contains(selectedClass!) { subject = "VAPA" } else if others.contains(selectedClass!) { subject = "General Electives" } else if worldLanguage.contains(selectedClass!) { subject = "World Language" } else if rop.contains(selectedClass!) { subject = "ROP" } else { subject = "All" } } performSegue(withIdentifier: "pickTeacher", sender: nil) } let subjects = ["English", "Social Studies", "Math", "Physical Education", "Science", "VAPA", "World Language", "General Electives", "ROP", "Sport", "Free Period"] var classes = [String?]() var buttons = [UIButton]() var classLabels = [UILabel]() var teacherLabels = [UILabel]() var subject = String() var period = Int() var myTeachers = [NewTeachers?]() var isFreshLaunch = true var isSecondScreen = false var isPageEditing = false func makeArrays() { buttons.append(p1Button) buttons.append(p2Button) buttons.append(p3Button) buttons.append(p4Button) buttons.append(p5Button) buttons.append(p6Button) buttons.append(p7Button) buttons.append(p8Button) classLabels.append(p1Class) classLabels.append(p2Class) classLabels.append(p3Class) classLabels.append(p4Class) classLabels.append(p5Class) classLabels.append(p6Class) classLabels.append(p7Class) classLabels.append(p8Class) teacherLabels.append(p1TeacherLabel) teacherLabels.append(p2TeacherLabel) teacherLabels.append(p3TeacherLabel) teacherLabels.append(p4TeacherLabel) teacherLabels.append(p5TeacherLabel) teacherLabels.append(p6TeacherLabel) teacherLabels.append(p7TeacherLabel) teacherLabels.append(p8TeacherLabel) } func autoResizeUI() { prevButton.titleLabel!.font = prevButton.titleLabel!.font.withSize(CGFloat(15).relativeToWidth) yourTeachers.font = yourTeachers.font.withSize(CGFloat(22).relativeToWidth) for label in teacherLabels { label.font = label.font.withSize(CGFloat(22).relativeToWidth) } for label in classLabels { label.font = label.font.withSize(CGFloat(14).relativeToWidth) } } override func viewDidLoad() { super.viewDidLoad() makeArrays() autoResizeUI() for i in 0...classLabels.count - 1 { if classes[i] == nil { classLabels[i].text = "PERIOD \(i + 1)" } else { classLabels[i].text = classes[i]!.uppercased() if classLabels[i].text == "SPORT" || classLabels[i].text == "FREE PERIOD" { teacherLabels[i].text = "N/A" buttons[i].isEnabled = false } } } for _ in 0...7 { myTeachers.append(nil) } if !isFreshLaunch { skipButton.titleLabel!.text = "CANCEL" } if isPrevButtonHidden { prevButton.isHidden = true } else { prevButton.isHidden = false } } @IBAction func unwindToTeachers(segue: UIStoryboardSegue) { if segue.identifier == "backToTeacher" { if let source = segue.source as? TeacherPickerViewController { let teacher = source.selectedItem myTeachers[period - 1] = teacher! let teacherLabel = "\(teacher!.first) \(teacher!.last)" teacherLabels[period - 1].text = teacherLabel.uppercased() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "pickTeacher" { if let vc = segue.destination as? TeacherPickerViewController { switch subject { case "All", "General Electives", "ROP": var preparedArray = [NewTeachers]() for classSubjects in subjectsRows { if classSubjects != "ADMINISTRATION" || classSubjects != "SUPPORT STAFF" || classSubjects != "SPECIAL EDUCATION" { let subjectGroup = subjectsDictionary[classSubjects] for teachers in subjectGroup! { preparedArray.append(teachers) } } } vc.teacherObjects = preparedArray case "English", "Social Studies", "Math", "Physical Education", "Science", "VAPA", "World Language", "History": var preparedArray = [NewTeachers]() let subjectGroup = subjectsDictionary[subject.uppercased()] for teachers in subjectGroup! { preparedArray.append(teachers) } vc.teacherObjects = preparedArray default: var preparedArray = [NewTeachers]() for classSubjects in subjectsRows { if classSubjects != "ADMINISTRATION" || classSubjects != "SUPPORT STAFF" || classSubjects != "SPECIAL EDUCATION" { let subjectGroup = subjectsDictionary[classSubjects] for teachers in subjectGroup! { preparedArray.append(teachers) } } } vc.teacherObjects = preparedArray } } } else if segue.identifier == "skipToWelcome" { } else if segue.identifier == "finishToWelcome" { if !classes.contains(nil) { for i in 0...7 { let mySchedule = MySchedule(context: PersistentService.context) mySchedule.name = classes[i] mySchedule.period = Int16(i + 1) let currentTeacher = myTeachers[i] let newTeacher = MyNewTeachers(context: PersistentService.context) newTeacher.first = currentTeacher?.first newTeacher.last = currentTeacher?.last newTeacher.subject1 = currentTeacher?.subject1 newTeacher.subject2 = currentTeacher?.subject2 newTeacher.isFemale = currentTeacher?.isFemale ?? false mySchedule.teacher = newTeacher PersistentService.saveContext() } } } } } <file_sep>// // Coaches+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(Coaches) public class Coaches: NSManagedObject { } <file_sep>// // MySchedule+CoreDataClass.swift // PHS App // // Created by <NAME> on 1/6/19. // Copyright © 2019 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(MySchedule) public class MySchedule: NSManagedObject { } <file_sep>// // Coaches+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension Coaches { @nonobjc public class func fetchRequest() -> NSFetchRequest<Coaches> { return NSFetchRequest<Coaches>(entityName: "Coaches") } @NSManaged public var first: String? @NSManaged public var last: String? @NSManaged public var email: String? @NSManaged public var gender: Bool @NSManaged public var team1: String? @NSManaged public var team2: String? } <file_sep>// // Teachers+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/27/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension Teachers { @nonobjc public class func fetchRequest() -> NSFetchRequest<Teachers> { return NSFetchRequest<Teachers>(entityName: "Teachers") } @NSManaged public var first: String? @NSManaged public var gender: Bool @NSManaged public var id: Int32 @NSManaged public var last: String? @NSManaged public var subject1: String? @NSManaged public var subject2: String? @NSManaged public var myTeacher: NSSet? } // MARK: Generated accessors for myTeacher extension Teachers { @objc(addMyTeacherObject:) @NSManaged public func addToMyTeacher(_ value: MyTeachers) @objc(removeMyTeacherObject:) @NSManaged public func removeFromMyTeacher(_ value: MyTeachers) @objc(addMyTeacher:) @NSManaged public func addToMyTeacher(_ values: NSSet) @objc(removeMyTeacher:) @NSManaged public func removeFromMyTeacher(_ values: NSSet) } <file_sep>// // SubjectsExpandableTableViewCell.swift // PHS App // // Created by <NAME> on 8/17/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import ExpandableCell class SubjectsExpandableTableViewCell: ExpandableCell { @IBOutlet weak var subjectLabel: UILabel! static let ID = "expandableCell" override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // My_Colors.swift // PHS App // // Created by <NAME> on 9/9/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation //var primaryColor = UIColor() //var secondaryColor = UIColor() //var darkThemePrimaryColor = UIColor() //var darkThemeSecondaryColor = UIColor() <file_sep>// // CollectionViewCell.swift // PHS App // // Created by <NAME> on 8/12/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var iconLabel: UILabel! } <file_sep>// // DetailPickerViewController.swift // PHS App // // Created by <NAME> on 8/19/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import PickerView let worldLanguage = ["Spanish", "French", "Chinese", "Korean", "Latin", "Other"] let rop = ["Intro to Med Careers", "Sprots Medicine", "Video Production", "Computer Graphics", "Other"] let vapa = ["Art Studio", "Ceramics", "Arts Survey", "Drawing & Painting", "Visual Imagery", "Computer Graphics", "Video Production", "Art Portfolio Prep", "AP Art History", "Dance", "Guitar", "Drama", "Tech Theatre", "Studio Music", "Marching Band", "Color Guard", "Band", "Orchestra", "Choir", "Portola Singers", "AP Music Theory", "Other"] let others = ["ASB", "Health", "Computer Science", "Yearbook", "Adv. Newspaper", "Modern Media", "Video Production", "Other"] class DetailPickerViewController: UIViewController { enum ItemsType : Int { case label, customView } enum PresentationType { case numbers(Int, Int), names(Int, Int) } @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var pickerView: PickerView! @IBAction func cancelTapped(_ sender: Any) { dismiss(animated: true) } @IBAction func doneTapped(_ sender: Any) { if currentSelectedValue != nil { selectedItem = currentSelectedValue! performSegue(withIdentifier: "detailBackToClass", sender: nil) } } var selectedSubject = String() var classes = [String]() var presentationType = PresentationType.numbers(0, 0) var selectedItem: String? var currentSelectedValue: String? var updateSelectedValue: ((_ newSelectedValue: String) -> Void)? var itemsType: PickerViewController.ItemsType = .label override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() switch selectedSubject { case "VAPA": classes = vapa case "World Language": classes = worldLanguage case "ROP": classes = rop case "General Electives": classes = others default: classes = vapa + rop + worldLanguage + others } configurePicker() } fileprivate func configurePicker() { pickerView.delegate = self pickerView.dataSource = self pickerView.scrollingStyle = .default pickerView.selectionStyle = .none if let currentSelected = currentSelectedValue, let indexOfCurrentSelectedValue = classes.index(of: currentSelected) { pickerView.currentSelectedRow = indexOfCurrentSelectedValue } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension DetailPickerViewController: PickerViewDelegate { func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat { return 50.0 } func pickerView(_ pickerView: PickerView, styleForLabel label: UILabel, highlighted: Bool) { label.textAlignment = .center if (highlighted) { label.font = UIFont(name: "Lato-Light", size: CGFloat(28).relativeToWidth) label.textColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) } else { label.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth) label.textColor = UIColor.lightGray.withAlphaComponent(0.75) } } func pickerView(_ pickerView: PickerView, didSelectRow row: Int, index: Int) { if self.classes[index] == "Other" { currentSelectedValue = selectedSubject } else { currentSelectedValue = self.classes[index] } } } extension DetailPickerViewController: PickerViewDataSource { func pickerView(_ pickerView: PickerView, titleForRow row: Int) -> String { return classes[row] } func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int { return classes.count } // func pickerView(_ pickerView: PickerView, titleForRow row: Int, index: Int) -> String { // // return classes[index] // } } <file_sep>// // IDCardViewController.swift // PHS App // // Created by <NAME> on 8/12/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreData import RSBarcodes_Swift import AVFoundation import LocalAuthentication class IDCardViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var navigationBar: UINavigationBar! @IBAction func dismiss(_ sender: Any) { dismiss(animated: true) } @IBOutlet weak var editButton: UIBarButtonItem! @IBAction func editTapped(_ sender: Any) { performSegue(withIdentifier: "editNameInput", sender: nil) } @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var gradeLabel: UILabel! @IBOutlet weak var shortID: UILabel! @IBOutlet weak var house: UILabel! @IBOutlet weak var barcode: UIImageView! @IBOutlet weak var longID: UILabel! @IBOutlet weak var addCardView: UIView! var addCardLabel = UILabel() // var thisUser = User(context: PersistentService.context) var thisUser = UserInfo() @IBOutlet weak var houseHeader: UILabel! @IBOutlet weak var gradeHeader: UILabel! @IBOutlet weak var shortIDHeader: UILabel! @IBOutlet weak var asbView: UILabel! @IBOutlet weak var stickerView: UILabel! var isUserData = false func faceIDAction() { let context = LAContext() let localizedReasonString = "Secure your information using Face ID and Touch ID." var authError: NSError? if #available(iOS 8.0, *) { if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) { print("I'm here now") context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: localizedReasonString) { (success, error) in DispatchQueue.main.async { if success { self.loadIDCard() } else { self.authenticateUsingShortID() } } } } else { authenticateUsingShortID() } } else { authenticateUsingShortID() } } func loadIDCard() { navigationBar.topItem?.rightBarButtonItem?.isEnabled = true let subviews: [UIView] = [nameLabel, barcode, gradeHeader, shortIDHeader, houseHeader, gradeLabel, shortID, house, longID, asbView, stickerView] for view in subviews { UIView.animate(withDuration: 0.5) { view.alpha = 1 } } } func authenticateUsingShortID() { let ac = UIAlertController(title: "Enter School Short ID", message: "enter short ID to verify your identity.", preferredStyle: .alert) ac.addTextField() ac.textFields![0].keyboardType = .numberPad let submitAction = UIAlertAction(title: "Verify", style: .default, handler: { [unowned ac] _ in let answer = ac.textFields![0] if answer.text != nil { if answer.text! == self.shortID.text! { self.loadIDCard() } else { self.failVerify(isShortID: true) answer.text = "" } } else { self.failVerify(isShortID: true) answer.text = "" } }) ac.addAction(submitAction) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(ac, animated: true) } func failVerify(isShortID: Bool) { var messageString = String() if isShortID { messageString = "Short ID" } else { messageString = "Code" } let ac = UIAlertController(title: "Incorrect \(messageString)", message: "You have entered an incorrect \(messageString), please try again.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { _ in if isShortID { self.authenticateUsingShortID() } else { } })) present(ac, animated: true) } func autoResizeUI() { let subviews: [UIView] = [nameLabel, barcode, gradeHeader, shortIDHeader, houseHeader, gradeLabel, shortID, house, longID, asbView, stickerView] for view in subviews { view.alpha = 0 } addCardView.alpha = 0 nameLabel.font = nameLabel.font.withSize(CGFloat(31).relativeToWidth) gradeHeader.font = gradeHeader.font.withSize(CGFloat(19).relativeToWidth) shortIDHeader.font = shortIDHeader.font.withSize(CGFloat(19).relativeToWidth) houseHeader.font = houseHeader.font.withSize(CGFloat(19).relativeToWidth) gradeLabel.font = gradeLabel.font.withSize(CGFloat(60).relativeToWidth) shortID.font = shortID.font.withSize(CGFloat(60).relativeToWidth) house.font = house.font.withSize(CGFloat(60).relativeToWidth) longID.font = longID.font.withSize(CGFloat(31).relativeToWidth) asbView.isUserInteractionEnabled = true asbView.isHidden = true stickerView.isHidden = true stickerView.isUserInteractionEnabled = true let asbGesture = UITapGestureRecognizer(target: self, action: #selector(asbTapped)) asbGesture.delegate = self asbView.addGestureRecognizer(asbGesture) let stickerGesture = UITapGestureRecognizer(target: self, action: #selector(stickerTapped)) stickerGesture.delegate = self stickerView.addGestureRecognizer(stickerGesture) } @objc func asbTapped() { if UserDefaults.standard.bool(forKey: "asbActivated") { let ac = UIAlertController(title: "ASB Card", message: "You currenlty have ASB feature activated, you may deactivate it if you wish.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) ac.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in let sheet = UIAlertController(title: "Deactivate ASB Feature", message: "Are you sure?", preferredStyle: .actionSheet) sheet.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in UserDefaults.standard.set(false, forKey: "asbActivated") self.setStandards() })) sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(sheet, animated: true) })) present(ac, animated: true) } else { let ac = UIAlertController(title: "Enter Code", message: "Show your advisement teacher your ID card to activate ASB on this device.", preferredStyle: .alert) ac.addTextField() let submitAction = UIAlertAction(title: "Verify", style: .default, handler: { [unowned ac] _ in let answer = ac.textFields![0] if answer.text != nil { if answer.text! == "app-activate-asb-now" { UserDefaults.standard.set(true, forKey: "asbActivated") self.setStandards() } else { self.failVerify(isShortID: false) answer.text = "" } } else { self.failVerify(isShortID: false) answer.text = "" } }) ac.addAction(submitAction) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(ac, animated: true) } } @objc func stickerTapped() { if UserDefaults.standard.bool(forKey: "stickerActivated") { let ac = UIAlertController(title: "Sticker", message: "You currenlty have sticker feature activated, you may deactivate it if you wish.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) ac.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in let sheet = UIAlertController(title: "Deactivate Sticker Feature", message: "Are you sure?", preferredStyle: .actionSheet) sheet.addAction(UIAlertAction(title: "Deactivate", style: .destructive, handler: { (_) in UserDefaults.standard.set(false, forKey: "stickerActivated") self.setStandards() })) sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(sheet, animated: true) })) present(ac, animated: true) } else { let ac = UIAlertController(title: "Enter Code", message: "Show your advisement teacher your ID card to activate sticker on this device.", preferredStyle: .alert) ac.addTextField() let submitAction = UIAlertAction(title: "Verify", style: .default, handler: { [unowned ac] _ in let answer = ac.textFields![0] if answer.text != nil { if answer.text! == "app-activate-sticker-now" { UserDefaults.standard.set(true, forKey: "stickerActivated") self.setStandards() } else { self.failVerify(isShortID: false) answer.text = "" } } else { self.failVerify(isShortID: false) answer.text = "" } }) ac.addAction(submitAction) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(ac, animated: true) } } func setStandards() { if UserDefaults.standard.bool(forKey: "asbActivated") { print("asbTrue") asbView.font = UIFont(name: "Lato-Bold", size: asbView.font.pointSize) asbView.textColor = UIColor(red: 0.376, green: 0.271, blue: 0.529, alpha: 1) } else { print("asbFalse") asbView.textColor = UIColor.lightGray } if UserDefaults.standard.bool(forKey: "stickerActivated") { print("stickerTrue") stickerView.font = UIFont(name: "Lato-Bold", size: asbView.font.pointSize) stickerView.textColor = UIColor(red: 0.376, green: 0.271, blue: 0.529, alpha: 1) } else { print("stickerFalse") stickerView.textColor = UIColor.lightGray } } override func viewDidLoad() { super.viewDidLoad() let notInitial = UserDefaults.standard.bool(forKey: "isInitial") if !notInitial { UserDefaults.standard.set(true, forKey: "isInitial") UserDefaults.standard.set(false, forKey: "asbActivated") UserDefaults.standard.set(false, forKey: "stickerActivated") } navigationBar.my_setNavigationBar() let userRequest: NSFetchRequest<User> = User.fetchRequest() do { let request = try PersistentService.context.fetch(userRequest) if request.count > 0 { isUserData = true let object = request.first! if object.first != nil && object.longID > 100000000 { navigationBar.topItem?.rightBarButtonItem?.isEnabled = false thisUser.first = object.first! thisUser.last = object.last! thisUser.longID = object.longID thisUser.shortID = object.shortID thisUser.grade = object.grade thisUser.house = object.house! navigationBar.topItem?.rightBarButtonItem = editButton autoResizeUI() setStandards() gradeLabel.text = String(object.grade) nameLabel.text = "\(object.first!) \(object.last!)" shortID.text = String(object.shortID) house.text = object.house?.uppercased() longID.text = String(object.longID) barcode.image = RSUnifiedCodeGenerator.shared.generateCode(String(object.longID), machineReadableCodeObjectType: AVMetadataObject.ObjectType.code39.rawValue) } } else { isUserData = false navigationBar.topItem?.rightBarButtonItem = nil let subviews: [UIView] = [nameLabel, barcode, gradeHeader, shortIDHeader, houseHeader, gradeLabel, shortID, house, longID, asbView, stickerView] for view in subviews { view.alpha = 0 } addCardView.isHidden = false addCardView.alpha = 1 view.addSubview(addCardView) } } catch { } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if isUserData { faceIDAction() } } override func viewWillLayoutSubviews() { addCardView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) addCardView.layer.cornerRadius = addCardView.bounds.height / 2 addCardLabel.bounds = CGRect(x: 0, y: 0, width: addCardView.frame.width, height: addCardView.frame.height) addCardLabel.center = CGPoint(x: addCardView.frame.width / 2, y: addCardView.frame.height / 2) addCardLabel.text = "FILL IN YOUR INFO" addCardLabel.textAlignment = .center addCardLabel.font = UIFont(name: "Lato-Bold", size: CGFloat(17).relativeToWidth) addCardLabel.textColor = UIColor.white addCardView.addSubview(addCardLabel) addCardLabel.my_dropShadow() let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(addCardTapped)) gestureRecognizer.delegate = self addCardView.addGestureRecognizer(gestureRecognizer) } @objc func addCardTapped() { performSegue(withIdentifier: "showNameInput", sender: nil) } @IBAction func unwindToIDCard(segue: UIStoryboardSegue) { if segue.identifier == "unwindToIDCard" { let updateRequest: NSFetchRequest<User> = User.fetchRequest() do { let request = try PersistentService.context.fetch(updateRequest) if let object = request.first { autoResizeUI() thisUser.first = object.first! thisUser.last = object.last! thisUser.longID = object.longID thisUser.shortID = object.shortID thisUser.grade = object.grade thisUser.house = object.house! gradeLabel.text = String(object.grade) nameLabel.text = "\(object.first!) \(object.last!)" shortID.text = String(object.shortID) house.text = object.house?.uppercased() longID.text = String(object.longID) barcode.image = RSUnifiedCodeGenerator.shared.generateCode(String(object.longID), machineReadableCodeObjectType: AVMetadataObject.ObjectType.code39.rawValue) navigationBar.topItem?.rightBarButtonItem = editButton loadIDCard() setStandards() asbView.isUserInteractionEnabled = true stickerView.isUserInteractionEnabled = true } } catch { } } } @IBAction func cancelToIDCard(segue: UIStoryboardSegue) { if segue.identifier == "cancelToIDCard" { } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showNameInput" { if let vc = segue.destination as? NameInputViewController { vc.isFreshLaunch = false } } else if segue.identifier == "editNameInput" { if let vc = segue.destination as? NameInputViewController { vc.isFreshLaunch = false vc.isPageEditing = true vc.first = thisUser.first vc.last = thisUser.last vc.house = thisUser.house vc.grade = Int(thisUser.grade) vc.shortID = String(thisUser.shortID) vc.longID = String(thisUser.longID) } } } } <file_sep>// // my_adjustFontSize.swift // PHS App // // Created by <NAME> on 8/9/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit import CoreGraphics extension CGFloat { var relativeToWidth: CGFloat { if (self / 375) * UIScreen.main.bounds.width < self { return (self / 375) * UIScreen.main.bounds.width } else { return (self / UIScreen.main.bounds.width) * UIScreen.main.bounds.width } } var barRelativeToWidth: CGFloat { return (self / 375) * UIScreen.main.bounds.width } } extension Int { var relativeToWidth: Int { if (self / 375) * Int(UIScreen.main.bounds.width) < self { return Int((self / 375) * Int(UIScreen.main.bounds.width)) } else { return Int((self / Int(UIScreen.main.bounds.width)) * Int(UIScreen.main.bounds.width)) } } var barRelativeToWidth: Int { return (self / 375) * Int(UIScreen.main.bounds.width) } } <file_sep>// // BellScheduleViewController.swift // PHS App // // Created by <NAME> on 9/25/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreGraphics import UserNotifications class BellScheduleViewController: UIViewController { var classesRaw = [Int]() var bellSchedule = [Date]() var classesString = [String]() var classesLabels = [UILabel]() var timeLabels = [UILabel]() var progressView = UIView() var progress = UIView() var day = Calendar.current.component(.day, from: Date()) var min = Calendar.current.component(.minute, from: Date()) var minimum = CGFloat() var maximum = CGFloat() var diff = CGFloat() var minOfSchool = numOfMinAtSchool(type: today) var minSinceSchool = Date().localTime().minFromSchoolStart() var percentage = CGFloat() let noSchoolLabel = UILabel() var labelConfigured = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) } func patchUserDefaults() { //remote notification patch let isNotifGranted = UserDefaults.standard.bool(forKey: "notifGranted") if !isNotifGranted { UserDefaults.standard.set(true, forKey: "notifGranted") UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (isGranted, error) in if !isGranted { let ac = UIAlertController (title: "Turn on Notifications", message: "Turn on notifications for Portolapp to receive updates on all things Portola!", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Yes", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in }) } } ac.addAction(settingsAction) let cancelAction = UIAlertAction(title: "No", style: .default, handler: nil) ac.addAction(cancelAction) self.present(ac, animated: true, completion: nil) } else { print("notification granted") } } } } override func viewDidLoad() { super.viewDidLoad() initilize() drawProgressLine() configureTime() configureHoliday() Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) patchUserDefaults() } @objc func update() { if Calendar.current.component(.day, from: Date()) != day { day = Calendar.current.component(.day, from: Date()) purge() initilize() configureTime() configureHoliday() if today == 20 || !Date().isSchoolDay() || Date() < Date(timeIntervalSince1970: 1566432000) { if progressView.isHidden == false { progressView.isHidden = true } } else { if progressView.isHidden == true { progressView.isHidden = false } } } else if Calendar.current.component(.minute, from: Date()) != min { configureTime() min = Calendar.current.component(.minute, from: Date()) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() progressView.layer.cornerRadius = progressView.bounds.width / 2 progress.layer.cornerRadius = progress.bounds.height / 2 if Date().isSchoolDay() && !labelConfigured { configureLabels() labelConfigured = true } } func initilize() { if Date() < Date(timeIntervalSince1970: 1566432000) { progressView.isHidden = true configureHoliday() } else if today != 20 && Date().isSchoolDay() { if today == 18 || today == 19 { bellSchedule.append(my_getSchedule(type: today, date: nil)![0]) for i in 0...uniq(source: my_getSchedule(type: today, date: nil)!).count - 1 { if i % 2 == 1 && i < 8 { bellSchedule.append(my_getSchedule(type: today, date: nil)![i]) } if i % 2 == 0 && i > 7 { bellSchedule.append(my_getSchedule(type: today, date: nil)![i]) } } } else { for i in 0...my_getSchedule(type: today, date: nil)!.count - 1 { if i % 2 == 0 { bellSchedule.append(my_getSchedule(type: today, date: nil)![i]) } } } } if let todayRaw = my_getStartEndPeriodLabel(type: today) { for i in 0...todayRaw.count - 1 { var prev: Int? if i > 0 { prev = todayRaw[i - 1] } else { prev = nil } if prev != nil { if todayRaw[i] != prev { classesRaw.append(todayRaw[i]) } } else { classesRaw.append(todayRaw[i]) } } } for classes in classesRaw { classesString.append(classes.getPeriodLabel().lowercased().capitalizingFirstLetter()) } if today != 20 && Date().isSchoolDay() { percentage = CGFloat(minSinceSchool) / CGFloat(minOfSchool!) } else { percentage = 0 } } func drawProgressLine() { if today == 20 { return } else if !Date().isSchoolDay() { return } progressView.bounds = CGRect(x: 0, y: 0, width: CGFloat(40).relativeToWidth, height: CGFloat(500).relativeToWidth) progressView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY - CGFloat(30).relativeToWidth) progressView.clipsToBounds = true progressView.layer.borderWidth = 3 progressView.layer.borderColor = UIColor.white.cgColor view.addSubview(progressView) progress.bounds = CGRect(x: 0, y: 0, width: CGFloat(35).relativeToWidth, height: CGFloat(35).relativeToWidth) progress.layer.borderWidth = 2.5 progress.layer.borderColor = UIColor.white.cgColor progress.clipsToBounds = true progress.my_setGradientBackground(colorOne: UIColor(red:0.89, green:0.62, blue:0.99, alpha:1.0), colorTwo: UIColor.white, inBounds: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: Int(CGFloat(35).barRelativeToWidth), height: Int(CGFloat(35).barRelativeToWidth)))) progressView.addSubview(progress) } func configureTime() { minimum = progressView.bounds.minY + CGFloat(progress.bounds.height.relativeToWidth / 2) maximum = progressView.bounds.maxY - CGFloat(progress.bounds.height.relativeToWidth / 2) diff = maximum - minimum minOfSchool = numOfMinAtSchool(type: today) minSinceSchool = Date().localTime().minFromSchoolStart() if today == 20 { return } else if !Date().isSchoolDay() { return } if Date().timeOfSchoolDay() != nil { switch Date().timeOfSchoolDay()! { case relativeTime.before: progress.center = CGPoint(x: progressView.bounds.midX, y: minimum) case relativeTime.during: self.progress.center = CGPoint(x: self.progressView.bounds.midX, y: minimum + diff * percentage) updateTime() case relativeTime.after: progress.center = CGPoint(x: progressView.bounds.midX, y: maximum) } } } func updateTime() { minimum = progressView.bounds.minY + CGFloat(progress.bounds.height.relativeToWidth / 2) maximum = progressView.bounds.maxY - CGFloat(progress.bounds.height.relativeToWidth / 2) diff = maximum - minimum minOfSchool = numOfMinAtSchool(type: today) minSinceSchool = Date().localTime().minFromSchoolStart() percentage = CGFloat(minSinceSchool) / CGFloat(minOfSchool!) UIView.animate(withDuration: 1.5) { self.progress.center = CGPoint(x: self.progressView.bounds.midX, y: self.minimum + self.diff * self.percentage) } } func configureLabels() { guard bellSchedule.count == classesString.count else { print(bellSchedule) print(classesString) return} bellSchedule.append(my_getStartEndTimeFromToday(type: today, dayType: dayType.today, date: nil)[1]) classesString.append("End Time") let top = progressView.frame.minY let bottom = progressView.frame.maxY let scaleFactor = CGFloat((bellSchedule.count * 2) - 1) for i in 0...classesString.count - 1 { let label = UILabel() label.bounds = CGRect(x: 0, y: 0, width: (progressView.center.x - progressView.frame.width / 2) - CGFloat(30).relativeToWidth, height: (bottom - top) / scaleFactor) label.center = CGPoint(x: (progressView.center.x - progressView.frame.width / 2) / 2, y: CGFloat(scaleFactor / 2) + top + (bottom - top) * CGFloat(2 * i) / scaleFactor) label.text = classesString[i].uppercased() label.textAlignment = .right label.textColor = UIColor.white label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.7 label.font = UIFont(name: "Lato-Light", size: CGFloat(18).relativeToWidth) classesLabels.append(label) view.addSubview(label) } for i in 0...bellSchedule.count - 1 { let label = UILabel() label.bounds = CGRect(x: 0, y: 0, width: (progressView.center.x - progressView.frame.width / 2) - CGFloat(30).relativeToWidth, height: (bottom - top) / scaleFactor) label.center = CGPoint(x: self.view.bounds.width - (progressView.center.x - progressView.frame.width / 2) / 2, y: CGFloat(scaleFactor / 2) + top + (bottom - top) * CGFloat(2 * i) / scaleFactor) let formatter = DateFormatter() formatter.dateFormat = "h:mm a" formatter.timeZone = TimeZone(abbreviation: "UTC") label.text = formatter.string(from: bellSchedule[i]) label.textAlignment = .left label.textColor = UIColor.white label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.font = UIFont(name: "Lato-Regular", size: CGFloat(20).relativeToWidth) timeLabels.append(label) view.addSubview(label) } } func purge() { for labels in classesLabels { labels.removeFromSuperview() } for labels in timeLabels { labels.removeFromSuperview() } classesLabels.removeAll() timeLabels.removeAll() classesString.removeAll() classesRaw.removeAll() bellSchedule.removeAll() } func configureHoliday() { noSchoolLabel.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: CGFloat(60).relativeToWidth) noSchoolLabel.center = CGPoint(x: self.view.center.x, y: self.view.center.y - CGFloat(40).relativeToWidth) noSchoolLabel.text = "NO SCHOOL TODAY" noSchoolLabel.font = UIFont(name: "Lato-Light", size: CGFloat(30).relativeToWidth) noSchoolLabel.textAlignment = .center noSchoolLabel.textColor = UIColor.white view.addSubview(noSchoolLabel) if today == 20 || !Date().isSchoolDay() || Date() < Date(timeIntervalSince1970: 1566432000) { noSchoolLabel.isHidden = false } else { noSchoolLabel.isHidden = true } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension String { func capitalizingFirstLetter() -> String { return prefix(1).uppercased() + dropFirst() } mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } } <file_sep>// // SchoolEvents.swift // PHS App // // Created by <NAME> on 8/21/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class SchoolEvents: NSObject { var date = Date() var time = String() var title = String() var notification = Bool() } <file_sep>// // my_UTCTimeDifference.swift // PHS App // // Created by <NAME> on 8/3/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func UTCDifference() -> Int { let offset = Double(TimeZone.current.secondsFromGMT()) return Int(offset / 3600) } <file_sep>// // Date.swift // PHS App // // Created by <NAME> on 7/31/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation class SpecialDays: NSObject { var date = Date() var type = Int() } <file_sep>// // my_customDateFormatter.swift // PHS App // // Created by <NAME> on 7/28/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension String { func my_customDateFormatter() -> Date { let firstArray = self.components(separatedBy: "/") if firstArray.count < 3 { print(firstArray) return Date.distantPast } let year = firstArray[0] var month = String() var day = String() if let monthNumber = Int(firstArray[1]) { if monthNumber < 1 || monthNumber > 12 { return Date.distantPast } else if monthNumber < 10 { month = "0\(monthNumber)" } else { month = "\(monthNumber)" } } if let dayNumber = Int(firstArray[2]) { if dayNumber < 1 || dayNumber > 31 { return Date.distantPast } else if dayNumber < 10 { day = "0\(dayNumber)" } else { day = "\(dayNumber)" } } let stringDate = "\(year)-\(month)-\(day)" let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" if let date = formatter.date(from: stringDate) { return date } else { return Date.distantPast } } } <file_sep>// // SavedEvents+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/9/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension SavedEvents { @nonobjc public class func fetchRequest() -> NSFetchRequest<SavedEvents> { return NSFetchRequest<SavedEvents>(entityName: "SavedEvents") } @NSManaged public var title: String? @NSManaged public var time: String? @NSManaged public var date: Date @NSManaged public var notification: Bool @NSManaged public var identifier: String? } <file_sep>// // ScanViewController.swift // PHS App // // Created by <NAME> on 8/14/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import RSBarcodes_Swift import AVFoundation class ScanViewController: RSCodeReaderViewController { override func viewDidLoad() { super.viewDidLoad() self.focusMarkLayer.strokeColor = UIColor.yellow.cgColor self.cornersLayer.strokeColor = UIColor.yellow.cgColor self.tapHandler = { point in print(point) } self.barcodesHandler = { barcodes in for barcode in barcodes { print("Barcode found: type=" + barcode.type.rawValue + " value=" + barcode.stringValue!) } } } } <file_sep>// // my_configureTopLabel.swift // PHS App // // Created by <NAME> on 8/2/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func timeStringFromDate(date: Date) -> String { let formatter = DateFormatter() formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "h:mm" let startTimeString = formatter.string(from: date) return startTimeString } <file_sep>// // UserInfo.swift // PHS App // // Created by <NAME> on 11/24/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class UserInfo: NSObject { var first = String() var last = String() var grade = Int16() var house = String() var shortID = Int32() var longID = Int32() } <file_sep>// // MyTeachers+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/18/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(MyTeachers) public class MyTeachers: NSManagedObject { } <file_sep>// // NewsTableViewCell.swift // PHS App // // Created by <NAME> on 8/30/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit class NewsTableViewCell: UITableViewCell { @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var newsTitle: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var thumbnail: UIImageView! var imageURL: URL? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // HousePointsViewController.swift // PHS App // // Created by <NAME> on 10/3/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreData class HousePointsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return houses.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let house = houses[indexPath.item] if let cell = rankCollectionView.dequeueReusableCell(withReuseIdentifier: "rank", for: indexPath) as? HouseRankCollectionViewCell { cell.house.text = house.name.uppercased() if indexPath.item != 0 { cell.house.textColor = cell.house.textColor.withAlphaComponent(0.7) cell.points.textColor = cell.points.textColor.withAlphaComponent(0.7) } cell.points.text = String(house.points) return cell } return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: rankCollectionView.bounds.width, height: rankCollectionView.bounds.height / 4 - CGFloat(2.5).relativeToWidth) } var houses = [Houses]() var ranksString = ["1st", "2nd", "3rd", "4th"] var userHouse: String? @IBOutlet weak var houseRankText: UILabel! @IBOutlet weak var housePointNumber: UILabel! @IBOutlet weak var trophyRank: UIImageView! @IBOutlet weak var ranks: UIStackView! @IBOutlet weak var rankCollectionView: UICollectionView! @IBOutlet weak var herPoints: UILabel! @IBOutlet weak var ornPoints: UILabel! @IBOutlet weak var pegPoints: UILabel! @IBOutlet weak var posPoints: UILabel! @IBOutlet weak var her: UIView! @IBOutlet weak var orn: UIView! @IBOutlet weak var peg: UIView! @IBOutlet weak var pos: UIView! @IBOutlet weak var herHeight: NSLayoutConstraint! @IBOutlet weak var ornHeight: NSLayoutConstraint! @IBOutlet weak var pegHeight: NSLayoutConstraint! @IBOutlet weak var posHeight: NSLayoutConstraint! @IBOutlet weak var baseline: UIView! @IBOutlet weak var rankTrailing: NSLayoutConstraint! @IBOutlet weak var baseLineBottom: NSLayoutConstraint! @IBOutlet weak var navigationBar: UINavigationBar! @IBAction func dismissTapped(_ sender: Any) { dismiss(animated: true) } @IBAction func refreshTapped(_ sender: Any) { houses.removeAll() fetchPoints() self.rankCollectionView.performBatchUpdates({ self.rankCollectionView.reloadSections(NSIndexSet(index: 0) as IndexSet) }) { (_) in self.configureGraph(isInitial: false) if self.userHouse != nil { self.housePointNumber.text = self.defineRank() } else { self.housePointNumber.text = "N/A" } } } override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() fetchPoints() rankCollectionView.delegate = self rankCollectionView.dataSource = self initialize() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.rankTrailing.constant = self.rankTrailing.constant.relativeToWidth self.baseLineBottom.constant = self.baseLineBottom.constant.relativeToWidth } func defineRank() -> String { for i in 0...houses.count - 1 { if houses[i].name.lowercased() == userHouse!.lowercased() { return ranksString[i] } } return "N/A" } func initialize() { herPoints.alpha = 0 ornPoints.alpha = 0 pegPoints.alpha = 0 posPoints.alpha = 0 herHeight.constant = 0 ornHeight.constant = 0 pegHeight.constant = 0 posHeight.constant = 0 let request: NSFetchRequest<User> = User.fetchRequest() do { let fetchRequest = try PersistentService.context.fetch(request) if let first = fetchRequest.first { userHouse = first.house if userHouse != nil { housePointNumber.text = defineRank() } else { let ac = UIAlertController(title: "No Information", message: "We don't know which house you are in. Please fill out your info under Tools -> ID Card.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) self.housePointNumber.text = "N/A" } } else { let ac = UIAlertController(title: "No Information", message: "We don't know which house you are in. Please fill out your info under Tools -> ID Card.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) self.housePointNumber.text = "N/A" } } catch { } print("OFIOIFSIEOFJEWIOFIOJEW") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) configureGraph(isInitial: true) } func fetchPoints() { if CheckInternet.Connection() { var name = String() var points = Int() if let data = try? String(contentsOf: URL(string: "https://spreadsheets.google.com/feeds/list/1XLgfb8kViNMPmgNy9-Gip039e_J6avIpf4k2kD46cNc/od6/public/basic?alt=json")!) { let jsonData = JSON(parseJSON: data) let entryArray = jsonData.dictionaryValue["feed"]!["entry"].arrayValue for entry in entryArray { let house = entry["content"]["$t"].stringValue let finalJSON = house.my_unquotedJSONFormatter(string: house, rows: 2) if finalJSON != "error" { let houseJSON = JSON(parseJSON: finalJSON) let dictionary = houseJSON.dictionaryObject! if let houseGet = dictionary["house"] as? String { name = houseGet } if let pointsGet = dictionary["points"] as? String { points = Int(pointsGet) ?? 1 } } let houseObject = Houses() houseObject.name = name houseObject.points = points houses.append(houseObject) } } } houses.sort { $0.points > $1.points } } func configureGraph(isInitial: Bool) { var isZero = Bool() var herPoint = Int() var ornPoint = Int() var pegPoint = Int() var posPoint = Int() var herPointDiff = Int() var ornPointDiff = Int() var pegPointDiff = Int() var posPointDiff = Int() for house in houses { if house.points == 0 { isZero = true break } else { isZero = false continue } } for house in houses { switch house.name { case "Hercules": herPoint = house.points herPointDiff = herPoint - (Int(herPoints.text!) ?? herPoint) case "Orion": ornPoint = house.points ornPointDiff = ornPoint - (Int(ornPoints.text!) ?? ornPoint) case "Pegasus": pegPoint = house.points pegPointDiff = pegPoint - (Int(pegPoints.text!) ?? pegPoint) case "Poseidon": posPoint = house.points posPointDiff = posPoint - (Int(posPoints.text!) ?? posPoint) default: break } } var divisionConstant = CGFloat() if self.houses[0].points == 0 { print("IS zERO") divisionConstant = 1.0 } else { divisionConstant = 1.0 // print("IS NOT ZERO") // print(self.houses[0].points / 10) // divisionConstant = CGFloat(1) / CGFloat(self.houses[0].points / 10) } if isInitial { print(divisionConstant, "THIS") UIView.animate(withDuration: 0.7, animations: { if isZero { self.herHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(herPoint)) self.ornHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(ornPoint)) self.pegHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(pegPoint)) self.posHeight.constant = CGFloat(10).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(posPoint)) self.view.layoutIfNeeded() } else { self.herHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(herPoint) - CGFloat(self.houses[self.houses.count - 1].points)) self.ornHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(ornPoint) - CGFloat(self.houses[self.houses.count - 1].points)) self.pegHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(pegPoint) - CGFloat(self.houses[self.houses.count - 1].points)) self.posHeight.constant = CGFloat(30).relativeToWidth + divisionConstant * CGFloat(15).relativeToWidth * (CGFloat(posPoint) - CGFloat(self.houses[self.houses.count - 1].points)) self.view.layoutIfNeeded() } }) { (_) in UIView.animate(withDuration: 0.3, animations: { self.herPoints.text = String(herPoint) self.ornPoints.text = String(ornPoint) self.pegPoints.text = String(pegPoint) self.posPoints.text = String(posPoint) self.herPoints.alpha = 1 self.ornPoints.alpha = 1 self.pegPoints.alpha = 1 self.posPoints.alpha = 1 }) } } else { UIView.animate(withDuration: 0.7, animations: { self.herHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(herPointDiff) * divisionConstant) self.ornHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(ornPointDiff) * divisionConstant) self.pegHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(pegPointDiff) * divisionConstant) self.posHeight.constant += CGFloat(15).relativeToWidth * (CGFloat(posPointDiff) * divisionConstant) self.view.layoutIfNeeded() }) { (_) in self.herPoints.text = String(herPoint) self.ornPoints.text = String(ornPoint) self.pegPoints.text = String(pegPoint) self.posPoints.text = String(posPoint) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // my_getStartEndLabel.swift // PHS App // // Created by <NAME> on 8/1/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation func my_getStartEndLabel(type: Int) -> [Bool]? { switch type { case 0: return defaultDaysStartEndLabel() case 1, 2: //pep assembly odd return [false, true, false, false, false, true, false, false, true, false, false, true, false] case 3, 4, 14: //extended lunch odd and hour of code return [false, true, false, false, true, false, false, true, false, false, true, false] case 5, 6: //finals type 1 return [false, true, false, true, false] case 7: //finals two periods return [false, true, false] case 8: //minimum 1-8 return [false, true, false, true, false, true, false, false, true, false, true, false, true, false, true, false] case 9, 10: //conferences return [false, true, false, false, true, false, true, false] case 11, 12: //PSAT 9 and PE testing return [false, false, true, false, true, false, false, true, false, true, false] case 13: //first 2 days of school return [false, true, false, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false] case 15: //Passion Day return [false, true, false, false, true, false, true, false] case 16: //Pre Testing return [false, true, false, false, true, false, true, false, false, true, false, true, false] case 17: //Testing return [false, false, true, false, false, true, false, true, false] case 18, 19: //CAASPP return [false, false, true, false, true, false, true, false, false, false, true, false] case 20: //NO SCHOOL return nil case 21: //fine arts assembly return [false, false, true, false, false, true, false, false, true, false] case 22: //monday schedule return [false, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false] case 23, 26, 28: //tuesday and friday schedule return [false, true, false, false, true, false, false, true, false, false, true, false] case 24, 25, 27: //wednesday and thursday schedule return [false, false, false, true, false, false, true, false, false, true, false] case 29: //super late start return [false, true, false, false, true, false, true, false] default: return defaultDaysStartEndLabel() } } func defaultDaysStartEndLabel() -> [Bool]? { switch Calendar.current.component(.weekday, from: Date()) { case 1, 7: return nil case 2: return [false, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false] case 3, 6: return [false, true, false, false, true, false, false, true, false, false, true, false] case 4, 5: return [false, false, false, true, false, false, true, false, false, true, false] default: return nil } } <file_sep>// // Today+CoreDataClass.swift // PHS App // // Created by <NAME> on 8/8/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData @objc(Today) public class Today: NSManagedObject { } <file_sep>// // IDInputViewController.swift // PHS App // // Created by <NAME> on 8/19/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import TextFieldEffects import RSBarcodes_Swift import AVFoundation import CoreData class IDInputViewController: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var yourID: UILabel! @IBOutlet weak var previousButton: UIButton! @IBAction func previousTapped(_ sender: Any) { if isFreshLaunch { _ = navigationController?.popViewController(animated: true) } else { dismiss(animated: true) } } @IBOutlet weak var shortIDTextField: HoshiTextField! @IBOutlet weak var longIDTextField: HoshiTextField! @IBOutlet weak var scanIDView: UIView! @IBAction func skipTapped(_ sender: Any) { if isFreshLaunch { let ac = UIAlertController(title: "Skip this page?", message: "Entering your ID number can save your ID card to your device in case you forget to bring it.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Skip", style: .default, handler: { (_) in self.shortID = nil self.longID = nil self.performSegue(withIdentifier: "skipWelcome", sender: nil) })) ac.addAction(UIAlertAction(title: "Stay", style: .cancel)) present(ac, animated: true) } else { performSegue(withIdentifier: "cancelToIDCard", sender: nil) } } @IBAction func nextTapped(_ sender: Any) { if shortIDTextField.text != nil && longIDTextField != nil { shortID = Int(shortIDTextField.text!) longID = Int(longIDTextField.text!) } if shortID != nil && longID != nil { if isFreshLaunch { saveData() performSegue(withIdentifier: "newWelcome", sender: nil) } else { if isPageEditing { saveEdits() performSegue(withIdentifier: "unwindToIDCard", sender: nil) } else { saveData() performSegue(withIdentifier: "unwindToIDCard", sender: nil) } } } else { let ac = UIAlertController(title: "Missing fields", message: "Make sure you fill in all fields before continuing.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel)) present(ac, animated: true) } } @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var skipButton: UIButton! func saveData() { let user = User(context: PersistentService.context) user.first = first user.last = last user.grade = Int16(grade ?? 0) user.house = house user.shortID = Int32(shortID ?? 0) user.longID = Int32(longID ?? 0) PersistentService.saveContext() } func saveEdits() { let updateRequest: NSFetchRequest<User> = User.fetchRequest() do { let request = try PersistentService.context.fetch(updateRequest) if let user = request.first { let shortIDEdit = Int32(shortID ?? 0) let longIDEdit = Int32(longID ?? 0) user.setValue(first, forKey: "first") user.setValue(last, forKey: "last") user.setValue(grade, forKey: "grade") user.setValue(house, forKey: "house") user.setValue(shortIDEdit, forKey: "shortID") user.setValue(longIDEdit, forKey: "longID") PersistentService.saveContext() } } catch { } } var first: String? var last: String? var grade: Int? var house: String? var shortID: Int? var longID: Int? var scanLabel = UILabel() var barImageView = UIImageView() var rescan = UIButton() var delete = UIButton() var longIDLabel = UILabel() var isFreshLaunch = true var isPageEditing = false override var prefersHomeIndicatorAutoHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() yourID.font = yourID.font.withSize(CGFloat(25).relativeToWidth) previousButton.titleLabel?.font = previousButton.titleLabel?.font.withSize(CGFloat(15).relativeToWidth) scanLabel.bounds = CGRect(x: 0, y: 0, width: scanIDView.frame.width * 0.8, height: scanIDView.frame.height * 0.8) scanLabel.center = CGPoint(x: scanIDView.frame.width / 2, y: scanIDView.frame.height / 2) scanLabel.textAlignment = .center scanLabel.text = "SCAN ID CARD" scanLabel.textColor = UIColor.white scanLabel.font = UIFont(name: "Lato-Regular", size: CGFloat(16)) scanIDView.addSubview(scanLabel) scanIDView.clipsToBounds = true scanIDView.layer.cornerRadius = scanIDView.frame.width / 2 scanIDView.backgroundColor = UIColor.white.withAlphaComponent(0) scanIDView.layer.borderWidth = 2 scanIDView.layer.borderColor = UIColor.white.cgColor let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(scanIDTapped)) gestureRecognizer.delegate = self scanIDView.addGestureRecognizer(gestureRecognizer) let tap = UITapGestureRecognizer(target: self, action: #selector(screenTapped)) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap) self.view.addSubview(longIDLabel) self.view.addSubview(rescan) self.view.addSubview(delete) if isFreshLaunch == false { skipButton.setTitle("CANCEL", for: .normal) nextButton.setTitle("SAVE", for: .normal) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if isFreshLaunch == false { skipButton.titleLabel!.text = "CANCEL" } if isPageEditing { if shortID != nil { shortIDTextField.text = String(shortID!) } if longID != nil { longIDTextField.text = String(longID!) generateBarcode(string: String(longID!)) } } } @objc func screenTapped() { if shortIDTextField.isEditing || longIDTextField.isEditing { if shortIDTextField.text != nil { shortID = Int(shortIDTextField.text!) shortIDTextField.resignFirstResponder() } else { shortID = nil shortIDTextField.resignFirstResponder() } if longIDTextField.text != nil { if CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: longIDTextField.text!)) { if let number = Int(longIDTextField.text!) { if number > 100000000 && number < 999999999 { longID = number generateBarcode(string: String(longID!)) longIDTextField.resignFirstResponder() } else { let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in self.longIDTextField.resignFirstResponder() self.longIDTextField.text = nil })) present(ac, animated: true) } } else { longID = nil longIDTextField.resignFirstResponder() self.barImageView.image = nil self.barImageView.alpha = 0 self.rescan.alpha = 0 self.delete.alpha = 0 self.longIDLabel.alpha = 0 self.scanIDView.alpha = 1 } } else { let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long and contain only numbers", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in self.longIDTextField.text = nil })) present(ac, animated: true) longIDTextField.resignFirstResponder() } } else { longID = nil longIDTextField.resignFirstResponder() } } } @objc func scanIDTapped() { scanIDView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3) performSegue(withIdentifier: "firstScan", sender: nil) } func textFieldDidEndEditing(_ textField: UITextField) { if textField == shortIDTextField { if textField.text != nil { shortID = Int(textField.text!) } shortIDTextField.resignFirstResponder() } else if textField == longIDTextField { if textField.text != nil { generateBarcode(string: String(longID!)) longID = Int(textField.text!) } longIDTextField.resignFirstResponder() } } @IBAction func unwindToViewController(segue: UIStoryboardSegue) { let source = segue.source as? FirstScanViewController scanIDView.backgroundColor = UIColor.white.withAlphaComponent(0) if source!.longID != nil { if CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: source!.longID!)) { longID = Int(source!.longID!) if longID! > 100000000 && longID! < 999999999 { generateBarcode(string: String(longID!)) } else { let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in self.longIDTextField.text = nil })) present(ac, animated: true) } } else { let ac = UIAlertController(title: "Not a valid ID number", message: "Your student ID number must be 9 digits long and contain only numbers", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in self.longIDTextField.text = nil })) present(ac, animated: true) } } else { self.longID = nil } } func generateBarcode(string: String) { longIDTextField.text = string if let scannedCode = RSUnifiedCodeGenerator.shared.generateCode(string, machineReadableCodeObjectType: AVMetadataObject.ObjectType.code39.rawValue) { barImageView.bounds = CGRect(x: 0, y: 0, width: CGFloat(240).relativeToWidth, height: CGFloat(80).relativeToWidth) barImageView.center = scanIDView.center barImageView.image = scannedCode self.view.addSubview(barImageView) self.scanIDView.alpha = 0 longIDLabel.bounds = CGRect(x: 0, y: 0, width: CGFloat(240).relativeToWidth, height: CGFloat(30).relativeToWidth) longIDLabel.text = string longIDLabel.textColor = UIColor.white longIDLabel.font = UIFont(name: "Lato-Light", size: CGFloat(24).relativeToWidth) longIDLabel.textAlignment = .center longIDLabel.center = CGPoint(x: barImageView.center.x, y: barImageView.center.y + CGFloat(60).relativeToWidth) rescan.bounds = CGRect(x: 0, y: 0, width: CGFloat(120).relativeToWidth, height: CGFloat(30).relativeToWidth) rescan.center = CGPoint(x: barImageView.center.x - CGFloat(50).relativeToWidth, y: barImageView.center.y + CGFloat(120).relativeToWidth) rescan.setTitle("Rescan ID Card", for: .normal) rescan.titleLabel!.font = UIFont(name: "Lato-Light", size: CGFloat(15).relativeToWidth) rescan.titleLabel!.textColor = UIColor.white rescan.titleLabel!.textAlignment = .center rescan.addTarget(self, action: #selector(rescanTapped), for: .touchUpInside) delete.bounds = CGRect(x: 0, y: 0, width: CGFloat(120).relativeToWidth, height: CGFloat(30).relativeToWidth) delete.center = CGPoint(x: barImageView.center.x + CGFloat(75).relativeToWidth, y: barImageView.center.y + CGFloat(120).relativeToWidth) delete.setTitle("Discard", for: .normal) delete.titleLabel!.font = UIFont(name: "Lato-Light", size: CGFloat(15).relativeToWidth) delete.titleLabel!.textColor = UIColor.white delete.titleLabel!.textAlignment = .center delete.addTarget(self, action: #selector(deleteTapped), for: .touchUpInside) self.barImageView.alpha = 1 self.rescan.alpha = 1 self.delete.alpha = 1 self.longIDLabel.alpha = 1 } } @objc func rescanTapped() { performSegue(withIdentifier: "firstScan", sender: nil) } @objc func deleteTapped() { let ac = UIAlertController(title: "Discard Scanned ID Card?", message: "Are you sure you want to delete this card?", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (_) in self.longIDTextField.text = nil self.barImageView.image = nil self.barImageView.alpha = 0 self.rescan.alpha = 0 self.delete.alpha = 0 self.longIDLabel.alpha = 0 self.scanIDView.alpha = 1 })) ac.addAction(UIAlertAction(title: "No", style: .cancel)) present(ac, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // my_nextMonday.swift // PHS App // // Created by <NAME> on 8/2/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension Date { func nextMonday() -> Date { var dayToAdd = Int() switch Calendar.current.component(.weekday, from: self) { case 1: dayToAdd = 1 case 2: dayToAdd = 7 case 3: dayToAdd = 6 case 4: dayToAdd = 5 case 5: dayToAdd = 4 case 6: dayToAdd = 3 case 7: dayToAdd = 2 default: dayToAdd = 9 - Calendar.current.component(.weekday, from: self) } let date = Calendar.current.date(byAdding: .day, value: dayToAdd, to: self) return date! } } <file_sep>// // AthleticsDetailViewController.swift // PHS App // // Created by <NAME> on 8/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import Segmentio import UserNotifications class AthleticsDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if upcomingGames.count >= 3 { return 3 } else { return upcomingGames.count } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: UIScreen.main.bounds.width, height: upcomingView.frame.height / 3) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = upcomingView.dequeueReusableCell(withReuseIdentifier: "upcoming", for: indexPath) as! UpcomingGamesCollectionViewCell let game = upcomingGames[indexPath.item] cell.PortolaLabel.text = "PORTOLA" cell.purpleCircle.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) cell.purpleCircle.layer.cornerRadius = 35 cell.purpleCircle.my_dropShadow() cell.grayCircle.backgroundColor = UIColor(red:0.68, green:0.68, blue:0.68, alpha:1.0) cell.grayCircle.layer.cornerRadius = 35 cell.grayCircle.my_dropShadow() cell.awayInitial.text = String(Array(game.other!).first!) cell.awayLabel.text = game.other?.uppercased() cell.team.text = "VARSITY" let formatter = DateFormatter() formatter.dateFormat = "MMM. dd" cell.date.text = formatter.string(from: game.time).uppercased() if game.isAway { cell.location.text = "AWAY" } else { cell.location.text = "HOME" } return cell } @IBAction func refreshTapped(_ sender: Any) { schedule.removeAll() performSelector(inBackground: #selector(loadSchedule), with: nil) } @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var segmentioView: Segmentio! var content = [SegmentioItem]() @IBAction func backTapped(_ sender: Any) { dismiss(animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return schedule.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = Bundle.main.loadNibNamed("GameScheduleTableViewCell", owner: self, options: nil)?.first as? GameScheduleTableViewCell { cell.sport = sport let game = schedule[indexPath.row] let dateFormatter = DateFormatter() dateFormatter.timeZone = Calendar.current.timeZone dateFormatter.dateFormat = "M/dd" cell.date.text = dateFormatter.string(from: game.time) let weekFormatter = DateFormatter() weekFormatter.timeZone = Calendar.current.timeZone weekFormatter.dateFormat = "EEEE" let weekdayString = weekFormatter.string(from: game.time).uppercased() cell.weekday.text = weekdayString let timeFormatter = DateFormatter() timeFormatter.timeZone = Calendar.current.timeZone timeFormatter.dateFormat = "h:mm a" let timeString = timeFormatter.string(from: game.time) cell.time.text = timeString if game.isAway { cell.isAway.text = "AWAY" } else { cell.isAway.text = "HOME" } cell.gameTime = game.time cell.identifier = "\(sport)\(Calendar.current.component(.day, from: game.time))\(Calendar.current.component(.month, from: game.time))" UNUserNotificationCenter.current().getPendingNotificationRequests { request in for notification in request { if cell.identifier == notification.identifier { cell.notification = true DispatchQueue.main.async { cell.bell.alpha = 1 } break } else { cell.notification = false DispatchQueue.main.async { cell.bell.alpha = 0 } } } } if game.homeScore != nil && game.awayScore != nil { cell.gameScheduleView.alpha = 0 cell.gameResultView.alpha = 1 cell.homeScore.text = String(game.homeScore!) cell.awayScore.text = String(game.awayScore!) if game.isAway { cell.homeTeam.text = game.other?.uppercased() cell.otherTeam = game.other ?? " " cell.awayTeam.text = "PORTOLA" } else { cell.homeTeam.text = "PORTOLA" cell.otherTeam = game.other ?? " " cell.awayTeam.text = game.other?.uppercased() } } else { cell.gameScheduleView.alpha = 1 cell.gameResultView.alpha = 0 cell.sendSubviewToBack(cell.gameResultView) cell.awayTeamSchedule.text = game.other?.uppercased() cell.otherTeam = game.other ?? " " } return cell } else { return UITableViewCell() } } var sport = String() @IBOutlet weak var scheduleView: UITableView! var schedule = [Games]() var upcomingGames = [Games]() @IBOutlet weak var homeView: UIView! @IBOutlet weak var upcomingView: UICollectionView! @IBOutlet weak var overall: UILabel! @IBOutlet weak var record: UILabel! @IBOutlet weak var varsity: UILabel! @IBOutlet weak var upcoming: UILabel! @IBOutlet weak var nothingLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() navigationBar.topItem!.title = sport record.alpha = 0 nothingLabel.alpha = 0 navigationBar.my_setNavigationBar() scheduleView.delegate = self scheduleView.dataSource = self upcomingView.delegate = self upcomingView.dataSource = self setSegmentedControl() segmentioView.selectedSegmentioIndex = 0 homeView.frame = CGRect(x: 0, y: segmentioView.frame.maxY, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - segmentioView.frame.maxY) record.font = record.font.withSize(CGFloat(58).relativeToWidth) overall.font = overall.font.withSize(CGFloat(19).relativeToWidth) varsity.font = varsity.font.withSize(CGFloat(18).relativeToWidth) upcoming.font = upcoming.font.withSize(CGFloat(19).relativeToWidth) view.addSubview(scheduleView) view.bringSubviewToFront(homeView) view.bringSubviewToFront(segmentioView) performSelector(inBackground: #selector(loadSchedule), with: nil) let layout = self.upcomingView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = -10 } @objc func loadSchedule() { if CheckInternet.Connection() { if let data = try? String(contentsOf: URL(string: "https://portola.epicteam.app/api/sports")!) { let jsonData = JSON(parseJSON: data) if let array = jsonData.dictionaryValue["sports"]?.arrayValue { for item in array { if let parsedInfo = item.dictionaryObject { if let name = parsedInfo["name"] as? String { if name == sport { let game = Games() game.sport = sport if let date = parsedInfo["when"] as? String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" game.time = formatter.date(from: date) ?? Date.distantPast } if let opponent = parsedInfo["other"] as? String { game.other = opponent } else { game.other = nil } if let isAway = parsedInfo["is_away"] as? Bool { game.isAway = isAway } if let home = parsedInfo["home_score"] as? Int { game.homeScore = home } else { game.homeScore = nil } if let away = parsedInfo["away_score"] as? Int { game.awayScore = away } else { game.awayScore = nil } schedule.append(game) if game.time > Date() { upcomingGames.append(game) } } else { continue } } } } schedule = schedule.sorted(by: { $0.time < $1.time } ) upcomingGames = upcomingGames.sorted(by: {$0.time < $1.time}) } } DispatchQueue.main.async { self.scheduleView.reloadData() self.upcomingView.reloadData() self.configureHome() } } else { let ac = UIAlertController(title: "No Internet Connection", message: "Cannot load schedule because there is no internet connection.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (_) in self.dismiss(animated: true) })) } } func configureHome() { var wins = 0 var losses = 0 var ties: Int? = nil for games in schedule { if games.homeScore != nil && games.awayScore != nil { if games.isAway { if games.homeScore! < games.awayScore! { if sport == "Girls Golf" || sport == "Boys Golf" { losses += 1 } else { wins += 1 } } else if games.homeScore! > games.awayScore! { if sport == "Girls Golf" || sport == "Boys Golf" { wins += 1 } else { losses += 1 } } else { if ties == nil { ties = 1 } else { ties! += 1 } } } else { if games.homeScore! > games.awayScore! { if sport == "Girls Golf" || sport == "Boys Golf" { losses += 1 } else { wins += 1 } } else if games.homeScore! < games.awayScore! { if sport == "Girls Golf" || sport == "Boys Golf" { wins += 1 } else { losses += 1 } } else { if ties == nil { ties = 1 } else { ties! += 1 } } } } } if ties == nil { record.text = "\(wins)-\(losses)" } else { record.text = "\(wins)-\(ties!)-\(losses)" } record.alpha = 1 if upcomingGames.count == 0 { nothingLabel.alpha = 1 } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) segmentioView.valueDidChange = { segmentio, segmentIndex in switch segmentIndex { case 0: self.view.sendSubviewToBack(self.scheduleView) case 1: self.view.bringSubviewToFront(self.scheduleView) default: break } } } func setSegmentedControl() { view.addSubview(segmentioView) let position = SegmentioPosition.dynamic let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white) let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none) let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)) segmentioView.selectedSegmentioIndex = 0 let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: ( defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)), selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white), highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white) ) ,animationDuration: 0.2) let home = SegmentioItem(title: "HOME", image: nil) let schedule = SegmentioItem(title: "SCHEDULE", image: nil) content = [home, schedule] segmentioView.setup(content: content, style: .onlyLabel, options: options) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // MyTeachers+CoreDataProperties.swift // PHS App // // Created by <NAME> on 8/27/18. // Copyright © 2018 Portola App Development. All rights reserved. // // import Foundation import CoreData extension MyTeachers { @nonobjc public class func fetchRequest() -> NSFetchRequest<MyTeachers> { return NSFetchRequest<MyTeachers>(entityName: "MyTeachers") } @NSManaged public var period: Int16 @NSManaged public var teacher: Teachers? } <file_sep>// // my_isDuringSchool.swift // PHS App // // Created by <NAME> on 8/4/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation enum relativeTime { case before case during case after } extension Date { func getRelativeTime() -> relativeTime? { let currentTime = self.localTime() if currentTime.isSchoolDay() { let type = getDayType(date: currentTime) let schedule = my_getSchedule(type: type, date: currentTime)! let start = schedule.first! let end = schedule.last! if currentTime < start { return .before } else if currentTime >= end { return .after } else { return .during } } else { return nil } } } <file_sep>// // my_boolToLabel.swift // PHS App // // Created by <NAME> on 8/2/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation extension Bool { func startEndLabelFromBool() -> String { if self { return "STARTS" } else { return "ENDS" } } } <file_sep>// // my_unquotedJSONFormatter.swift // PHS App // // Created by <NAME> on 7/28/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit extension String { func my_unquotedJSONFormatter(string: String, rows: Int) -> String { var finalString = "" var isComma = false let firstArray = string.components(separatedBy: ", ") if firstArray.count != rows { print("error: \(firstArray)") return "error" } var secondArray = [String]() for item in firstArray { let individual = item.components(separatedBy: ": ") for key in individual { secondArray.append(key) } } if secondArray.count != rows * 2 { print("error: \(secondArray)") return "error" } else { finalString += "{ " for i in 0...secondArray.count - 2 { if isComma { finalString += "\"\(secondArray[i])\", " } else { finalString += "\"\(secondArray[i])\": " } isComma = !isComma } finalString += "\"\(secondArray[secondArray.count - 1])\" }" } // finalString = "{ \"\(secondArray[0])\": \"\(secondArray[1])\", \"\(secondArray[2])\": \"\(secondArray[3])\", \"\(secondArray[4])\": \"\(secondArray[5])\", \"\(secondArray[6])\": \"\(secondArray[7])\" }" return finalString } static func createFormattedJSON() -> String? { let string = String() let rows = Int() let finalString = string.my_unquotedJSONFormatter(string: string, rows: rows) return finalString } } <file_sep>// // NewTeachers.swift // PHS App // // Created by <NAME> on 1/6/19. // Copyright © 2019 Portola App Development. All rights reserved. // import UIKit class NewTeachers: NSObject { var id = Int() var first = String() var last = String() var subject1 = String() var subject2: String? var isFemale = Bool() } <file_sep>// // ViewController.swift // PHS App // // Created by <NAME> on 7/22/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import CoreGraphics //import XLActionController class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var isFreshLaunch = true var safeArea = CGFloat() @IBOutlet weak var navigationBackground: UIImageView! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var collectionView: UICollectionView! let icons = ["Clubs", "Teachers", "ID Card", "Call", "Calendar", "Portola Pilot", "PNN"] let iconImages: [UIImage] = [ UIImage(named: "clubs")!, UIImage(named: "teachers")!, UIImage(named: "id")!, UIImage(named: "call")!, UIImage(named: "calendar")!, UIImage(named: "pilot")!, UIImage(named: "pnn")!, UIImage(named: "housePoints")! ] let currentIcons = ["Teachers", "ID Card", "Call", "Calendar", "Portola Pilot", "House Points"] let currentIconImages: [UIImage] = [ UIImage(named: "teachers")!, UIImage(named: "id")!, UIImage(named: "call")!, UIImage(named: "calendar")!, UIImage(named: "pilot")!, UIImage(named: "housePoints")! ] override func viewWillAppear(_ animated: Bool) { if isFreshLaunch { self.tabBarController!.selectedIndex = 1 isFreshLaunch = false } for cell in collectionView.indexPathsForSelectedItems ?? [] { collectionView.deselectItem(at: cell, animated: true) let deselectedCell = collectionView.cellForItem(at: cell) deselectedCell?.backgroundColor = UIColor.white } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() collectionView.delegate = self collectionView.dataSource = self collectionView.allowsMultipleSelection = false drawLines() let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.itemSize = CGSize(width: (self.view.bounds.width) / 2, height: safeArea / 4) } func drawLines() { let safeTopY = navigationBar.bounds.maxY - (20 - UIApplication.shared.statusBarFrame.height) var bottomConstant = 0 if UIScreen.main.bounds.height == 812 { bottomConstant = 34 } let safeBottomY = tabBarController!.tabBar.frame.minY - CGFloat(bottomConstant) safeArea = safeBottomY - safeTopY let renderer1 = UIGraphicsImageRenderer(size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) let img1 = renderer1.image { ctx in ctx.cgContext.setStrokeColor(UIColor(red:0.82, green:0.70, blue:0.88, alpha:1.0).cgColor) ctx.cgContext.setLineWidth(0.5) ctx.cgContext.move(to: CGPoint(x: self.view.bounds.midX, y: navigationBar.frame.maxY - (20 - UIApplication.shared.statusBarFrame.height)) ) ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.midX, y: self.view.bounds.height)) ctx.cgContext.move(to: CGPoint(x: 0, y: safeTopY + safeArea / 2)) ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.maxX, y: safeTopY + safeArea / 2)) ctx.cgContext.move(to: CGPoint(x: 0, y: safeTopY + safeArea / 4)) ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.maxX, y: safeTopY + safeArea / 4)) ctx.cgContext.move(to: CGPoint(x: 0, y: safeTopY + safeArea / 4 * 3)) ctx.cgContext.addLine(to: CGPoint(x: self.view.bounds.maxX, y: safeTopY + safeArea / 4 * 3)) ctx.cgContext.drawPath(using: .stroke) } let image = UIImageView(image: img1) image.image = img1 } func callNumber(number: String) { let numberString = number guard let url = URL(string: "telprompt://\(numberString)") else { return } UIApplication.shared.open(url) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentIcons.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell cell.iconLabel.text = currentIcons[indexPath.item] cell.iconImageView.image = currentIconImages[indexPath.item] if currentIcons[indexPath.item] == "Clubs" { cell.iconLabel.textColor = UIColor.gray } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) if let item = cell as? CollectionViewCell { if item.iconLabel.text != "Call" { cell?.layer.backgroundColor = UIColor(red:0.82, green:0.82, blue:0.82, alpha: 0.6).cgColor } } let cellItem = cell as! CollectionViewCell switch cellItem.iconLabel.text! { case "Call": let ac = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) ac.addAction(UIAlertAction(title: "Front Office", style: .default, handler: { (_) in self.callNumber(number: "9499368200") })) ac.addAction(UIAlertAction(title: "Attedance Office", style: .default, handler: { (_) in self.callNumber(number: "9499368201") })) ac.addAction(UIAlertAction(title: "Counseling Office", style: .default, handler: { (_) in self.callNumber(number: "9499368227") })) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(ac, animated: true) default: let vc = storyboard?.instantiateViewController(withIdentifier: cellItem.iconLabel.text!) present(vc!, animated: true) } } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.layer.backgroundColor = UIColor.white.cgColor } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell { if cell.iconLabel.text == "Call" { if cell.isSelected { collectionView.deselectItem(at: indexPath, animated: true) return true } } else { return true } } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // MyTeachersTableViewCell.swift // PHS App // // Created by <NAME> on 8/20/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import MessageUI class MyTeachersTableViewCell: UITableViewCell, MFMailComposeViewControllerDelegate { @IBOutlet weak var circleView: UIView! @IBOutlet weak var initialsLabel: UILabel! @IBOutlet weak var periodLabel: UILabel! @IBOutlet weak var teacherLabel: UILabel! @IBOutlet weak var classLabel: UILabel! @IBOutlet weak var emailImageView: UIImageView! @IBOutlet weak var emailButtonView: UIView! var first = String() var last = String() var gender = Bool() override func awakeFromNib() { super.awakeFromNib() circleView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) circleView.layer.cornerRadius = 25 emailButtonView.layer.cornerRadius = 25 emailButtonView.layer.borderWidth = 2 emailButtonView.layer.borderColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0).cgColor let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(emailTapped)) gestureRecognizer.delegate = self emailButtonView.addGestureRecognizer(gestureRecognizer) teacherLabel.text = "\(first.uppercased()) \(last.uppercased())" circleView.my_dropShadow() } override func setSelected(_ selected: Bool, animated: Bool) { circleView.backgroundColor = UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0) } @objc func emailTapped() { emailButtonView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.45) var address = String() let trimmedLast = last.replacingOccurrences(of: "-", with: "").replacingOccurrences(of: " ", with: "") address = "\(first)\(trimmedLast)@<EMAIL>" sendEmail(address: address, isFemale: gender, lastName: last) } func sendEmail(address: String, isFemale: Bool, lastName: String) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients([address]) var title = String() if isFemale { title = "Ms." } else { title = "Mr." } mail.setMessageBody("<p>Hello, \(title) \(lastName), <br><br><br> <br>Sincerely,", isHTML: true) self.parentViewController?.present(mail, animated: true) } else { } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { emailButtonView.backgroundColor = UIColor.white self.parentViewController?.dismiss(animated: true) } } <file_sep>// // MySchedule+CoreDataProperties.swift // PHS App // // Created by <NAME> on 1/6/19. // Copyright © 2019 Portola App Development. All rights reserved. // // import Foundation import CoreData extension MySchedule { @nonobjc public class func fetchRequest() -> NSFetchRequest<MySchedule> { return NSFetchRequest<MySchedule>(entityName: "MySchedule") } @NSManaged public var period: Int16 @NSManaged public var name: String? @NSManaged public var teacher: MyNewTeachers? } <file_sep>// // my_isLongBreak.swift // PHS App // // Created by <NAME> on 9/4/18. // Copyright © 2018 Portola App Development. All rights reserved. // import Foundation import UIKit //FOR NOTIFICATION PURPOSES ONLY extension Date { var isLongBreak: Bool { switch Calendar.current.component(.month, from: self) { case 11: if Calendar.current.component(.day, from: self) == 22 || Calendar.current.component(.day, from: self) == 23 { return true } else { return false } case 12: if Calendar.current.component(.day, from: self) >= 25 && Calendar.current.component(.day, from: self) <= 31 { return true } else { return false } case 1: if Calendar.current.component(.day, from: self) >= 1 && Calendar.current.component(.day, from: self) <= 4 { return true } else { return false } case 4: if Calendar.current.component(.day, from: self) >= 1 && Calendar.current.component(.day, from: self) <= 5 { return true } else { return false } default: return false } } } <file_sep>// // PortolaPilotViewController.swift // PHS App // // Created by <NAME> on 8/13/18. // Copyright © 2018 Portola App Development. All rights reserved. // import UIKit import SwiftyXMLParser import Segmentio import SDWebImage class PortolaPilotViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return current.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let article = current[indexPath.row] let cell = Bundle.main.loadNibNamed("NewsTableViewCell", owner: self, options: nil)?.first as! NewsTableViewCell cell.newsTitle.text = article.title cell.authorLabel.text = article.author let formatter = DateFormatter() formatter.dateFormat = "MM/dd/yy" formatter.timeZone = Calendar.current.timeZone formatter.locale = Calendar.current.locale cell.dateLabel.text = formatter.string(from: article.pubDate) if article.imageLink != nil { cell.thumbnail.sd_setImage(with: article.imageLink, placeholderImage: UIImage(named: "newsPlaceholder")) } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! NewsTableViewCell let article = current[indexPath.row] if let vc = storyboard?.instantiateViewController(withIdentifier: "newsDetail") as? NewsDetailViewController { vc.titleText = cell.newsTitle.text! vc.info = "By \(cell.authorLabel.text!) on \(cell.dateLabel.text!)." vc.imageLink = article.imageLink vc.news = article.content vc.storyLink = article.link if let navigator = navigationController { navigator.pushViewController(vc, animated: true) } else { print("no navigation controller") } } else { print("no view controller") } } var content = [SegmentioItem]() var articles = [NewsArticle]() var groupDictionary = [String: [NewsArticle]]() var groupCategories = [String]() var current = [NewsArticle]() var indicator = UIActivityIndicatorView() @IBOutlet weak var segmentioView: Segmentio! @IBOutlet weak var newsTableView: UITableView! @IBAction func dismiss(_ sender: Any) { dismiss(animated: true) } @IBOutlet weak var navigationBar: UINavigationBar! override func viewDidLoad() { super.viewDidLoad() navigationBar.my_setNavigationBar() setSegmentedControl() if CheckInternet.Connection() { performSelector(inBackground: #selector(parseFeed), with: nil) } else { setAlertController(title: "No Internet Connection", message: "We could not load any news articles because you are not connected to the Internet.", preferredStyle: .alert, actionTitle: "OK") } newsTableView.delegate = self newsTableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if newsTableView.indexPathForSelectedRow != nil { newsTableView.deselectRow(at: newsTableView.indexPathForSelectedRow!, animated: true) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) if current.count == 0 { indicator.bounds = CGRect(x: 0, y: 0, width: 200, height: 200) indicator.center = self.view.center indicator.color = UIColor.black indicator.startAnimating() indicator.alpha = 1 view.addSubview(indicator) view.bringSubviewToFront(indicator) } segmentioView.valueDidChange = { segmentio, segmentIndex in switch segmentIndex { case 0: self.current = self.articles case 1: self.current = self.groupDictionary["NEWS"] ?? [] case 2: self.current = self.groupDictionary["OPINION"] ?? [] case 3: self.current = self.groupDictionary["FEATURES"] ?? [] case 4: self.current = self.groupDictionary["SHOWCASE"] ?? [] case 5: self.current = self.groupDictionary["SPORTS"] ?? [] case 6: self.current = self.groupDictionary["A&E"] ?? [] case 7: self.current = self.groupDictionary["THE PAW PRINT"] ?? [] default: print("more coming") } self.newsTableView.reloadData() } } func setSegmentedControl() { let position = SegmentioPosition.dynamic let indicator = SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 1, color: .white) let horizontal = SegmentioHorizontalSeparatorOptions(type: SegmentioHorizontalSeparatorType.none) let vertical = SegmentioVerticalSeparatorOptions(ratio: 0.1, color: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0)) segmentioView.selectedSegmentioIndex = 0 let options = SegmentioOptions(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), segmentPosition: position, scrollEnabled: true, indicatorOptions: indicator, horizontalSeparatorOptions: horizontal, verticalSeparatorOptions: vertical, imageContentMode: .center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: ( defaultState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: UIColor.white.withAlphaComponent(0.5)), selectedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white), highlightedState: SegmentioState(backgroundColor: UIColor(red:0.42, green:0.25, blue:0.57, alpha:1.0), titleFont: UIFont(name: "Lato-Bold", size: CGFloat(16).relativeToWidth)!, titleTextColor: .white) ) ,animationDuration: 0.2) let allItem = SegmentioItem(title: "ALL", image: nil) let aeItem = SegmentioItem(title: "A&E", image: nil) let featuresItem = SegmentioItem(title: "FEATURES", image: nil) let opinionItem = SegmentioItem(title: "OPINION", image: nil) let pawPrintItem = SegmentioItem(title: "PAW PRINT", image: nil) let sportsItem = SegmentioItem(title: "SPORTS", image: nil) let newsItem = SegmentioItem(title: "NEWS", image: nil) let showcaseItem = SegmentioItem(title: "SHOWCASE", image: nil) content = [allItem, newsItem, opinionItem, featuresItem, showcaseItem, sportsItem, aeItem, pawPrintItem] segmentioView.setup(content: content, style: .onlyLabel, options: options) } func setAlertController(title: String, message: String?, preferredStyle: UIAlertController.Style, actionTitle: String) { let ac = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) ac.addAction(UIAlertAction(title: actionTitle, style: .default, handler: nil)) present(ac, animated: true) } func loadThumbnail(url: URL) -> UIImage? { if let data = try? Data(contentsOf: url) { if let image = UIImage(data: data) { return image } else { return nil } } else { return nil } } @objc func parseFeed() { if let xmlContent = try? String(contentsOf: URL(string: "https://portolapilot.com/feed/")!) { let xml = try! XML.parse(xmlContent) let itemArray = xml["rss"]["channel"]["item"].all! for i in 0...itemArray.count - 1 { let item = itemArray[i] //configure categories array var categories = [String?]() for elements in item.childElements { if elements.name == "category" { categories.append(elements.text) } } if categories.count < 3 { for _ in 0...(2 - categories.count) { categories.append(nil) } } let object = xml["rss"]["channel"]["item"][i] let article = NewsArticle() article.title = object["title"].text ?? "News Article" article.link = object["link"].text ?? "https://portolapilot.com/" let formatter = DateFormatter() formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z" formatter.timeZone = Calendar.current.timeZone formatter.locale = Calendar.current.locale let dateString = object["pubDate"].text if dateString != nil { article.pubDate = formatter.date(from: dateString!)! } else { article.pubDate = Date.distantPast } if let rawAuthor = object["dc:creator"].text { if rawAuthor.contains(",") { let newAuthor = rawAuthor.split(separator: ",") article.author = String(newAuthor[0]) } } else { article.author = "Student Journalist" } article.category1 = categories[0]! article.category2 = categories[1] article.category3 = categories[2] article.content = object["content:encoded"].text ?? "Error Loading Article." if let linkString = object["link"].text { let array = linkString.components(separatedBy: "/") if array.count >= 5 { let shortTitle = array[3] if let data = try? String(contentsOf: URL(string: "http://portolapilot.com/wp-json/oembed/1.0/embed?url=http%3A%2F%2Fportolapilot.com%2F\(shortTitle)%2F")!) { if let jsonData = JSON(parseJSON: data).dictionaryObject!["thumbnail_url"] as? String { if let urlImage = URL(string: jsonData) { article.imageLink = urlImage } } } } } articles.append(article) } generateTypes() } else { setAlertController(title: "Error", message: "There was an error accessing Portola Pilot feed, please try again later.", preferredStyle: .alert, actionTitle: "OK") } } func generateTypes() { for news in articles { let key = news.category1 let key2 = news.category2 let key3 = news.category3 let upper = key.uppercased() let upper2 = key2?.uppercased() let upper3 = key3?.uppercased() if var newsType = groupDictionary[upper] { newsType.append(news) groupDictionary[upper] = newsType } else { groupDictionary[upper] = [news] } if upper2 != nil { if var newsType2 = groupDictionary[upper2!] { newsType2.append(news) groupDictionary[upper] = newsType2 } else { groupDictionary[upper2!] = [news] } } if upper3 != nil { if var newsType3 = groupDictionary[upper3!] { newsType3.append(news) groupDictionary[upper] = newsType3 } else { groupDictionary[upper3!] = [news] } } } groupCategories = [String](groupDictionary.keys) print(groupCategories) DispatchQueue.main.async { self.indicator.viewFadeOut() self.current = self.articles self.newsTableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } }
6a4e675fc57d81a13e74aa8d1da198efb66fe759
[ "Swift", "Ruby", "Markdown" ]
92
Swift
Cuiboy/Portolapp
bf70dd9e14ab6bd0ca5dca3fa860a69b1542bbc8
2aedb8e7c53f9646213a586359bf89c0e86fcce6
refs/heads/master
<repo_name>TieChi/tests<file_sep>/underscore/underscore.js import _ from 'underscore'; let arr = [1,2,3,4,5,6]; // let a = _.map(arr, (num) => { // return a*2 // }) console.log(arr);<file_sep>/AngularJS-imooc/AngularJS实战第二章第五节指令源代码/app/$Directive&Directive/ex.js let myModule = angular.module('MyModule',[]); //公共的superman方法, // 先定义了控制器中的所有方法 // 在定义link中的事件 myModule.directive("superman",function (){ return { scope: {}, restrict: 'ECMA', controller: function ($scope){ $scope.abilities = []; this.addStrength = function() { $scope.abilities.push("strength"); }; this.addSpeed = function() { $scope.abilities.push("speed"); }; this.addLight = function() { $scope.abilities.push("light"); }; }, link: function(scope, element, attrs) { element.bind("mouseenter", function() { console.log(scope.abilities); }); } } }); //在具体指令中引用公共指令, // 并使用其定义的方法 myModule.directive('strength',function (){ return { require: '^superman', link: function(scope, element, attrs, supermanCtrl) { supermanCtrl.addStrength(); } } }); myModule.directive('speed',function (){ return { require: '^superman', link: function(scope, element, attrs, supermanCtrl) { supermanCtrl.addSpeed(); } } }); myModule.directive('light',function (){ return { require: '^superman', link: function(scope, element, attrs, supermanCtrl) { supermanCtrl.addLight(); } } }); <file_sep>/Node.js/day2/05.js let Person = require('./test/Person.js'); let person = new Person("小明"); person.sayHello(); <file_sep>/Node.js/album/models/file.js let fs = require("fs") exports.getUp = function (callback) { callback() } exports.getAllAlbum = function (callback) { fs.readdir("./upload", function (err, files) { var allAlbums = []; (function iterator(i){ if (i === files.length) { callback(allAlbums) return } fs.stat("./upload/" + files[i], function (err, stats) { if ( stats.isDirectory() ) { allAlbums.push(files[i]) } iterator(i+1) }) })(0); }) } exports.getImagesByAlbumName = function (name, callback) { let list = fs.readdirSync("./upload/"+name) let allImages = [] for (let i=0; i<list.length; i++) { let file = fs.statSync("./upload/" + name + '/' + list[i]) if ( file.isFile() ) { allImages.push(list[i]) } } callback(allImages) }<file_sep>/Node-imooc/http/scope.js let globalVariable = 'This is global variable'; <file_sep>/vue-imooc/vuex-1/src/router/index.js import Vue from 'vue' import Router from 'vue-router' <<<<<<< HEAD // import Vuex from 'Vuex' import Hello from '@/components/Hello' Vue.use(Router) // Vue.use(Vuex) // let store = new Vuex({ // }) ======= Vue.use(Router) >>>>>>> eda3521920c2855a33d682ebac40e0c21532f2d6 export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello } ] }) <file_sep>/Node.js/day2/test/foo.js let msg = "Hello World"; let showMsg = function () { console.log(msg); } exports.msg = msg; exports.showMsg = showMsg;<file_sep>/1/D3-1/main.js /*添加节点div,并向其中添加Hello World*/ let body = d3.select('body'); body.style("color","black").style("background-color","#fff"); /*创建div节点,并将它添加到body中*/ let div = body.append('div'); div.html('Hello World!'); /*选中所有的section节点, 向每一个section中添加节点和Hello World!*/ let section = d3.select('body').selectAll('section'); let divs = section.append('div'); divs.html('Hello World!'); <file_sep>/AngularJS-imooc/AngularJS实战第二章第四节路由源代码/app/ex3.js var routerApp = angular.module('routerApp',['ui.router']); routerApp.config(function ($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/index'); $stateProvider .state('index',{ url: '/index', views: { '': { templateUrl: 'tpls3/index.html' }, 'topbar@index': { templateUrl: 'tpls3/topbar.html' }, 'main@index': { templateUrl: 'tpls3/home.html' } } }) .state('index.usermng',{ url: '/usermng', views: { 'main@index': { templateUrl: 'tpls3/usermng.html', controller: function($scope, $state) { $scope.addUserType = function() { $state.go("index.usermng.addusertype"); } } } } }) .state('index.report',{ url: '/report', views: { 'main@index': { template: '<div>报告</div>' } } }) .state('index.settings',{ url: '/settings', views: { 'main@index': { template: '<div>关于</div>' } } }) });<file_sep>/Node.js/day5/03.js let express = require("express") let formidable = require("formidable") let app = express() let db = require("./model/db.js") app.set("view engine", "ejs") app.use(express.static("./public")) app.get("/", function(req, res, next) { res.render("index") }) app.get("/find", function(req, res, next) { db.find("03", function (err, result) { res.json(result) }) }) app.post("/commit", function (req, res) { let form = new formidable.IncomingForm() form.parse(req, function(err, fields) { db.insertOne("03", { "name": fields.name, "message": fields.message }, function (err, result) { if (err) { res.json("false") return } res.json("true") }) }) }) app.listen(3000)<file_sep>/AngularJS-imooc/AngularJS实战第二章第五节指令源代码/app/$Directive&Controller/js.js let myModule = angular.module('MyModule',[]); myModule.directive('loader',function (){ return { restrict: 'ECMA', link: function(scope,element,attr) { element.bind('mouseenter',function (event){ scope.$apply(attr.howtoload); }) } } }); myModule.controller('MyCtrl',['$scope',function ($scope){ $scope.loadData = function (){ console.log('......'); } }]); myModule.controller('MyCtrl2',['$scope',function ($scope){ $scope.loadData = function (){ console.log('。。。。。。'); } }]);<file_sep>/Node-imooc/http/callback.js /*负责console的动作*/ function learn (something) { console.log(something); } /*负责调用回调函数和拼接字符串*/ function we (callback, something) { something += 'is cool'; callback(something); } we (learn, 'Node.js');<file_sep>/AngularJS-imooc/AngularJS实战第二章第五节指令源代码/app/$templateCache/ex.js var myModule = angular.module("MyModule", []); myModule.run(function($templateCache) { $templateCache.put("hello.html","<div>!!!!!!!!!!!!</div>"); }); myModule.directive("hello", function($templateCache) { return { restrict: "ECMA", template: $templateCache.get("hello.html"), replace: true } });<file_sep>/Node.js/day4/02/app.js let datas = [ { title: "No.0", content: "content<br>content<br>content<br>content" }, { title: "No.1", content: "content<br>content<br>content<br>content" }, { title: "No.2", content: "content<br>content<br>content<br>content" }, { title: "No.3", content: "content<br>content<br>content<br>content" } ] let express = require("express") let app = express() // app.set("view engine", "ejs") app.use(express.static("./public")) app.get("/news", function (req, res) { res.json(datas) }) app.listen(3000)<file_sep>/Node.js/day1/08_fs.js let http = require("http"); let fs = require("fs"); let server = http.createServer(function (req, res){ if (req.url == "/favicon.ico") { return } let userId = parseInt(Math.random()*999999) + 1000; res.writeHead(200, {"Content-Type": "text/html;charset=UTF8"}); fs.readFile("./text/1.txt", function(err,data){ if (err) { throw err; } res.end(data); }) }); server.listen(4000, "127.0.0.1");<file_sep>/Node.js/day1/02_staticrender.js let http = require("http"); let fs = require("fs"); let server = http.createServer(function (req, res) { if(req.url == '/square') { fs.readFile('./html/square.html', function(err, data) { res.writeHead(200, {"Content-type":"text/html;charset=utf-8"}); res.end(data); }); } else if (req.url == '/circle') { fs.readFile('./html/circle.html', function(err, data) { res.writeHead(200, {"Content-type":"text/html;charset=utf-8"}); res.end(data); }); } else if (req.url == '/jpg') { fs.readFile('./html/0.jpg', function(err, data) { res.writeHead(200, {"Content-type":"image/jpg"}); res.end(data); }); } else { res.writeHead(404, {"Content-type":"text/html;charset=utf-8"}); res.end("NOT FOUND!!"); } }); server.listen(3000, "127.0.0.1"); //如果想修改结果,必须中断当前运行的服务器 //重启node,才能刷新结果。<file_sep>/Node.js/day2/12.js var http = require("http"); var querystring = require("querystring"); var formidable = require('formidable'); var fs = require('fs'); var server = http.createServer(function(req,res){ if (req.url == '/favicon.ico') { return; } if(req.url == "/doPost" && req.method.toLowerCase() == "post"){ let form = new formidable.IncomingForm(); form.uploadDir = "./dirs"; form.parse(req, function (err, fields, files) { let oldPath = __dirname + '/' + files.upload.path; let newPath = __dirname + '/dirs/' + '123456' + '.jpg'; console.log(oldPath); console.log(newPath); fs.rename(oldPath, newPath, function () { res.writeHead(200, {'Content-type': 'text/plain'}); res.end('success'); }); }); } else if (req.url == '/') { fs.readFile('./index.html', function (err, data) { if (err) { throw err; } res.writeHead(200, {'Content-type': 'text/html'}); res.end(data); }); } }); server.listen(8080,"127.0.0.1");<file_sep>/Node.js/day2/14.js let ejs = require('ejs'); let string = "今天买了iphone<%= a %>"; let data = { a: 'X' } let html = ejs.render(string, data); console.log(html);<file_sep>/NodeInAction-code/exerise/ex3.2/index.js let http = require('http'); let fs = require('fs'); http.createServer(function (req, res) { if(req.url == '/') { fs.readFile('./titles.json', function (err, data) { console.error(err); res.end('Server Error'); }); } }).listen(8000, "127.0.0.1");<file_sep>/1/D3-2/main.js /*添加节点div,并向其中添加Hello World*/ /*添加svg节点到#graph中, 并将svg命名为v*/ let v = d3.select("#graph") .append("svg"); v.attr("width",900).attr("height",400); <file_sep>/vue-imooc/router-2/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import Apple from '@/components/Apple' import Banana from '@/components/Banana' import red from '@/components/red' Vue.use(Router) let green = { template: '<div>THIS IS GREEN</div>' } let orange = { template: '<div>THIS IS ORANGE</div>' } export default new Router({ mode: 'history', routes: [ { path: '/Apple', name: 'Apple', component: Apple, children: [ { path: 'red', component: red } ] }, { path: '/Banana', name: 'Banana', component: Banana }, { path: '/other', component: { view1: green, view2: orange } } ] }) <file_sep>/Node.js/day1/09_fs.js let http = require("http"); let fs = require("fs"); let server = http.createServer(function (req, res){ if (req.url == "/favicon.ico") { return } let userId = parseInt(Math.random()*999999) + 1000; res.writeHead(200, {"Content-Type": "text/html;charset=UTF8"}); fs.stat("./text", function (err, data){ if (err) { throw err; } res.end("THIS IS IT"); console.log(data.isDirectory()) }); }); server.listen(4000, "127.0.0.1");<file_sep>/1/南丁格尔图/main.js var echarts = require('echarts'); // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 绘制图表 myChart.setOption({ backgroundColor: '#232323', series: [{ name: '访问来源', type: 'pie', radius: '55%', roseType: 'angle', itemStyle: { normal: { shadowBlur: 200, shadowOffsetX: 0, shadowOffsetY: 0, shadowColor: 'rgba(0,0,0,0.5)', color: '#c23531' } }, data: [ {value:235,name:'视频广告'}, {value:274,name:'联盟广告'}, {value:310,name:'邮件营销'}, {value:335,name:'邮件访问'}, {value:400,name:'搜索引擎'} ], textStyle: { color: 'rgba(255, 255, 255, 0.3)' }, label: { normal: { textStyle: { color: 'rgba(255,255,255,0.3)' } } }, labelLine: { normal: { lineStyle: { color: 'rgba(255,255,255,0.3)' } } }, visualMap: { // 不显示 visualMap 组件,只用于明暗度的映射 show: false, // 映射的最小值为 80 min: 80, // 映射的最大值为 600 max: 600, inRange: { // 明暗度的范围是 0 到 1 colorLightness: [0, 1] } } }] }); <file_sep>/Node.js/day5/model/db.js let MongoClient = require('mongodb').MongoClient /*连接数据库的函数*/ /*在连接到mongodb后执行回调*/ function _connectDB(callback) { let url = 'mongodb://localhost:27017/dao' MongoClient.connect(url, function(err, db) { callback(err, db) }) } /*在collection中添加一项的函数*/ exports.insertOne = function(collectionName, json, callback) { _connectDB(function (err, db) { /*在_connectDB(连接数据库)的回调函数中,添加增加一项的方法*/ db.collection(collectionName).insertOne(json, function (err, rlt) { /*在添加一项的回调函数中, *执行业务逻辑调用insertOne时的回调函数*/ callback(err, rlt) db.close() }) }) } exports.find = function() { let collectionName = arguments[0] let args, callback if (arguments.length === 2) { args = { skip:0, limit:0 } callback = arguments[1] } else { args = arguments[1] callback = arguments[2] } _connectDB(function (err, db) { let cursor = db.collection(collectionName).find({}).skip(Number(args.skip)).limit(args.limit) let rlt = [] cursor.each(function (err, doc) { if (err) { callback(err, null) return } if (doc !== null) { rlt.push(doc) } else { callback(null, rlt) } }) }) } exports.deleteMany = function(collectionName, json, callback) { _connectDB(function (err, db) { db.collection(collectionName).deleteMany(json, function (err, rlt) { callback(err, rlt) db.close() }) }) } exports.modMany = function(collectionName, preJson, modJson, callback) { _connectDB(function (err, db) { db.collection(collectionName).updateMany(preJson, modJson, function (err, result) { callback(err, result) db.close() }) }) }<file_sep>/Node.js/day2/test/Person.js function Person (name) { this.name = name; } Person.prototype = { sayHello: function () { console.log(this.name + ' : Hello,everyone.'); } } module.exports = Person;<file_sep>/webpack-basic-usage/src/script/hello.js var $ = require('jquery'); function hello() { // body... } // let body = $('body'); // console.log(body);<file_sep>/Node-imooc/crawler-promise.js let http = require('http'); let Promise = require('Promise'); let cheerio = require('cheerio'); let baseUrl = 'http://www.imooc.com/learn'; let url = 'http://www.imooc.com/learn/637'; function filterChapters (html) { let $ = cheerio.load(html); let chapters = $('.mod-chapters').find('.chapter'); let title = ''; for (i=0; i<chapters.length; i++) { title += $(chapters[i]).find('.chapter-content').html(); } console.log(title) } function getPageAsync () { return new Promise(function (resolve, reject) { console.log('crawling'); http.get(url, function (res) { let html = ''; res.on('data', function (data) { html += data; }); res.on('end', function () { resolve(html) // filterChapters(html); }) }).on('error', function() { reject(error); console.log('ERROR'); }); }) } let fetchCourseArray = []; videoIds.forEach( id => { fetchCourseArray.push(getPageAsync(baseUrl + id)); }); Promise .all(fetchCourseArray) .then(function (pages) { let courseData = []; pages.forEach(function (html) { }); }) <file_sep>/Node.js/day1/07_router.js let http = require('http'); let server = http.createServer(function (req, res) { let userurl = req.url; res.writeHead(200, {"Content-type":"text/html;charset-UTF8"}); if (userurl.substr(0,9) == '/student/') { res.end("学生") } else if (userurl.substr(0,9) == '/teacher/') { res.end("教师") } }); server.listen(3000, '127.0.0.1');<file_sep>/webpack-basic-usage/webpack.config.js var htmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { //js文件的输入和生成设置 entry: { hello: './src/script/hello.js', a: './src/script/a.js', b: './src/script/b.js', c: './src/script/c.js' }, output: { filename: './dist/js/[name].js' }, //html文件的输入和生成设置 plugins: [ //插件功效:以某个html文件为模板更新创建首页内容 //(体现为script标签的的动态引用和date数据的更新) new htmlWebpackPlugin({ //html文件模板 template: 'src/index.html', filename:"./dist/a.html", //注入信息的位置 inject: 'head', //修改title和date数据信息 title: 'a', //引用路径 chunks: ['hello','a'], date: new Date() }), new htmlWebpackPlugin({ template: 'src/index.html', filename:"./dist/b.html", inject: 'head', title: 'b', excludeChunks: ['a','c'], date: new Date() }), new htmlWebpackPlugin({ template: 'src/c.html', filename:"./dist/c.html", inject: false, title: 'c', // excludeChunks: ['a','b'], date: new Date() }) ] }<file_sep>/Node.js/day5/01.js let express = require("express") let app = express() let MongoClient = require('mongodb').MongoClient let assert = require('assert') app.get("/", function(req, res){ let url = 'mongodb://localhost:27017/01' MongoClient.connect(url, function(err, db) { if (err) { console.log('fail') } assert.equal(null, err); console.log('success') db.collection('rest').insertOne({ "name": "haha", "age": Math.random() }, function(err, rlt) { console.log(rlt) db.close(); }) }) res.send("Hello") }) app.listen(3000)<file_sep>/Node-imooc/beginning/server.js let http = require('http'); let server = http.createServer(function serverFun(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('This is the fucking Hello World\n'); }) server.listen(1337, '127.0.0.1'); console.log('Running');<file_sep>/vue-imooc/1/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' Vue.config.productionTip = false let foreHead = { template: '<span>THIS IS FOREHEAD!!!</span>' } let hindBrain = { template: '<span>THIS IS HINDBRAIN!!!</span>' } let myHeader = { template: `<p>THIS IS MY HEADER! <br/><br/><br/><fore-head></fore-head> <br/><br/><br/><hind-brain></hind-brain> </p>`, components: { 'fore-head': foreHead, 'hind-brain': hindBrain } } /* eslint-disable no-new */ new Vue({ el: '#app', components: { 'my-header': myHeader } }) <file_sep>/Node.js/day2/04.js let foo = require("./test/foo.js"); console.log(foo.msg); foo.showMsg();<file_sep>/Node.js/day2/03.js let http = require("http"); let fs = require("fs"); let url = require("url"); let path = require("path"); let server = http.createServer(function(req, res){ let pathname = url.parse(req.url).pathname; let fileUrl = ''; if (pathname == '/favicon.ico') { return } if (pathname !== '/') { fileUrl = './'+path.normalize('static/'+ pathname); } else { fileUrl = './static/index.html'; } let extName = path.extname(req.url); fs.readFile(fileUrl, function (err, data) { getMime(extName, function (mime) { res.writeHead(200, {"Content-Type": "text/html;charset=utf8"}); res.end(data); }); }); }); server.listen(3000, '127.0.0.1'); function getMime (extName, callback) { let mime; fs.readFile("./mime.json", function (err, data) { if (err) throw Error("找不到相关文件"); mimeObj = JSON.parse(data); let mime = mimeObj[extName] || 'text/plain'; callback(mime); }); }<file_sep>/AngularJS-imooc/AngularJS实战第二章第四节路由源代码/app/ex.js var routerApp = angular.module('routerApp',['ui.router']); routerApp.config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home',{ url: '/home', templateUrl: 'tpls2/home.html' }) .state('about',{ url: '/about', templateUrl: 'tpls2/about.html' }) });
213fd13d8b3bbf4f5d44849d870b289a0eb18dec
[ "JavaScript" ]
35
JavaScript
TieChi/tests
bbc20ed4a0316d9643c621e9aee127685300e526
2e9771d339efa024a8acbd4825e1de9e4d5badbc
refs/heads/master
<file_sep>Introduction ============ This library packages `bootstrap-slider`_ for `fanstatic`_. .. _`fanstatic`: http://fanstatic.org .. _`bootstrap-slider`: https://github.com/seiyria/bootstrap-slider/ This requires integration between your web framework and ``fanstatic``, and making sure that the original resources (shipped in the ``resources`` directory in ``js.bootstrap_slider``) are published to some URL. <file_sep>import js.jquery from fanstatic import Library, Resource, Group library = Library('bootstrap-slider', 'resources') slider_css = Resource( library, 'bootstrap-slider.css', minified='bootstrap-slider.min.css') slider_js = Resource( library, 'bootstrap-slider.js', minified='bootstrap-slider.min.js', depends=[js.jquery.jquery]) slider = Group([slider_css, slider_js])
ffb6d5dc4d17317e43a03d31c2b61032030b0e5f
[ "Markdown", "Python" ]
2
Markdown
fanstatic/js.bootstrap_slider
e282eee5959bd4203697410d7fb37ba510fc0cdb
7bfe51ec6814654633c097ad0be13d43a76877a6
refs/heads/main
<repo_name>Combatd/introProgrammingSwift5<file_sep>/section3/optionals.playground/Contents.swift import UIKit // Optionals let developers specify which data could be nil // and which data is guaranteed to not be nil //struct Person { // let firstName: String // let middleName: String? // let lastName: String // // func printFullName() { // // if nil value, empty string // let middle = middleName ?? "" // // if middleName == nil { // // middle = "" // // } // print("\(firstName) \(middle) \(lastName)") // } //} // //var person1 = Person(firstName: "Jenna", middleName: nil, lastName: "Smith") //var person2 = Person(firstName: "Bob", middleName: "Leroy", lastName: "Jenkins") // //person1.printFullName() //person2.printFullName() class Person { let firstName: String let middleName: String? let lastName: String let spouse: Person? // initializer init(firstName: String, middleName: String?, lastName: String, spouse: Person?) { self.firstName = firstName self.middleName = middleName self.lastName = lastName self.spouse = spouse } func printFullName() { // if nil value, empty string let middle = middleName ?? "" // if middleName == nil { // middle = "" // } print("\(firstName) \(middle) \(lastName)") } } let person1 = Person(firstName: "Kimbo", middleName: "Joe", lastName: "Slice", spouse: nil) // optional chaining, calling a function on something that could be optional // if the spouse is not nil, print the Person's spouse name // else print that they don't have a spouse if let spouseName = person1.spouse?.printFullName() { print(spouseName) } else { print("\(person1.firstName) does not have a spouse.") } print(person1.spouse?.printFullName() ?? print("\(person1.firstName) does not have a spouse.")) // unwrapping an optional value, can be useful, but can get runtime errors // try not to use these // print(person1.spouse!.getFullName()) // If you have an optional (Question Mark ?), make sure to check if it is nil. // Always use optional chaining // Never force unwrap optionals, or you will get runtime crashes @IBOutlet weak var someButton: UIButton! // implicitly unwrapped ooptional // url examplewebsite.com let myWebsite = URL(string: "examplewebsite.com") <file_sep>/section4/mvcifyme/mvcifyme/Model/AppleProduct.swift // // AppleProduct.swift // mvcifyme // // Created by <NAME> on 10/11/20. // import Foundation class AppleProduct { // private variables are only accessible & set inside the same class // public private can access anywhere but only set in the class public private(set) var name: String public private(set) var color: String public private(set) var price: Double init(name: String, color: String, price: Double) { self.name = name self.color = color self.price = price } } <file_sep>/section4/objectsandclasses.playground/Contents.swift import UIKit // What is a Class? // The most popular paradigm - Object Oriented Programming // With a Class, you can create a blueprint and create copies of it // You could have a Car Class and instantiate multiple objects with the Car properties and functions class Vehicle { var tires = 4 var headlights = 2 var horsepower = 468 var model = "" func drive() { // accelerate the vehicle } func brake() { } } // instantiate a Vehicle instance let bmw = Vehicle() bmw.model = "328i" let ford = Vehicle() ford.model = "F150" ford.brake() // Objects are passed by reference, not by value func someFunction(vehicle: Vehicle) { vehicle.model = "Cheese" } print(ford.model) someFunction(vehicle: ford) print(ford.model) // You can't copy an object, but you can copy the values in memory // The constant model property was passed by reference var someonesAge = 20 func passByValue(age: Int) { let newAge = age // makes a copy of the value and stores in a new memory location } passByValue(age: someonesAge) // View Component //class NewVC: UIViewController { // override func viewDidLoad() { // // } //} <file_sep>/section2/boolsandcomparisons.playground/Contents.swift import UIKit // Bool is the explicit type, Boolean is for type casting var amITheBestTeacherEver: Bool = true amITheBestTeacherEver = false // Booleans are more commonly used for comparisons or doing based on conditions if true == false || true == true { print("WTFish") } var hasDataFinishedDownloading: Bool = false // ... loading spinner if !hasDataFinishedDownloading { print("Loading data...") } hasDataFinishedDownloading = true // Load the UI and other app features // State Control! if 1 == 2 { print("Should not see this") } // Equal to: == // Not equal to: != // Greater than: > // Greater than or equal to: >= // Less than or equal to: <= // Less than: < var bankBalance = 400 var itemToBuy = 100 if bankBalance >= itemToBuy { print("purchased item") } if itemToBuy > bankBalance { print("You need more money!") } if itemToBuy == bankBalance { print("Hey buddy, your balance is now 0") } var bookTitle1 = "<NAME> and the Moppet of Mire" var bookTitle2 = "<NAME> the Moppet of Mire" if bookTitle1 != bookTitle2 { print("Need to fix spelling before printing") } else if bookTitle2.count > 10 { print("find a new title for the book") } else { print("Book looks great, send to printer") } <file_sep>/section4/mvcifyme/mvcifyme/View/CustomPrettyView.swift // // CustomPrettyView.swift // mvcifyme // // Created by <NAME> on 10/11/20. // import UIKit class CustomPrettyView: UIView { override func awakeFromNib() { layer.cornerRadius = 20 layer.shadowColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) // color literal layer.shadowRadius = 10 layer.shadowOpacity = 0.75 backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) layer.borderColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) layer.borderWidth = 5 } } <file_sep>/section1/strings.playground/Contents.swift import UIKit var str = "Hello, playground" // Declaration: Type inference var message: String = "This is a String" // Declaration: Explicit Type var age: String = "20" // There might be a case where you can store an age where you don't plan on doing mathematical operations with it // Swift is a statically-typed language - type safe var fullName = "<NAME>" var aMessage: String = "Hey There!" let firstName = "Jenna" let lastName = "Smith" fullName = firstName + " " + lastName // string concatenation print(fullName) var newMessage: String = "Hi, my name is \(firstName) and I am \(age) years old" print(newMessage) // string interpolation newMessage.append(". I like scary clowns.") print(newMessage) <file_sep>/section1/variables.playground/Contents.swift import UIKit // Lets talk about a Person! // What are some attributes of a person? var name = "Bob" // String var age = 51 // Integer var weight = 212.15 // Double var isOrganDonor = false // Boolean print(weight) // var is mutable - they can change! weight = 200.10 print(weight) // Variables are stored in the RAM on your computer, memory space // Define constant using let keyword let eyeColor = "Blue" <file_sep>/section2/loopstime.playground/Contents.swift import UIKit // These should be in an array! var employee1Salary = 45000.0 var employee2Salary = 100000.0 var employee3Salary = 54000.0 var employee4Salary = 20000.0 // something seems wrong here....DRY Don't Repeat Yourself //employee1Salary = employee1Salary + (employee1Salary * 0.10) //employee2Salary = employee2Salary + (employee2Salary * 0.10) //employee3Salary = employee3Salary + (employee3Salary * 0.10) //employee4Salary = employee4Salary + (employee4Salary * 0.10) var salaries = Array<Double>() salaries.append(employee1Salary) salaries.append(employee2Salary) salaries.append(employee3Salary) salaries.append(employee4Salary) // This is still a lot of manual work. DRY Don't Repeat Yourself //salaries[0] = salaries[0] + (salaries[0] * 0.10) // Why don't we create a while loop? var idx = 0 repeat { salaries[idx] = salaries[idx] + (salaries[idx] * 0.10) idx += 1 } while (idx < salaries.count) // Remember, last array index is length - 1 // ... is inclusive of the final index! for x in 1...5 { print("Value of x: \(x)") } // ..< is exclusive of the final index! for x in 1..<5 { print("Value of x: \(x)") } // Let us do the same thing in a for in loop with a range! for i in 0..<salaries.count { salaries[i] = salaries[i] + (salaries[i] * 0.10) } // foreach enumerable for salary in salaries { print("Salary: \(salary)") } <file_sep>/README.md # Introduction to Programming in Swift 5 This is an Introduction to Programming in Swift 5 for building simple programs with the Swift programming language and preparing to learn iOS mobile development. ## Learning Goals * An Introduction to Swift 5 programming concepts * Installing the necessary tools - XCode * Working with data such as Integers and Strings * Creating reusable code with functions * Working with data constructs such as arrays and dictionaries * Object-oriented programming (Classes, Composition, Inheritance, etc) * Model View Controller (MVC) Software Architecture <file_sep>/section4/polymorphism.playground/Contents.swift import UIKit // What is Polymorphism? // Dictionary says it is the condition of occuring in several different forms // Stack Overflow has an interesting answer to this: /* Polymorphism allows the expression of some sort of contract with potentially many types implementing that contract whether through class inheritance or not in different ways each according to their own purpose. Code using that contract should not have to care about which implementation is involved, only that the contract will be obeyed. */ // At some point, those abstracted, not yet defined methods will have to be implemented! class Shape { var area: Double? func calculateArea(valA: Double, valB: Double) { } } class Triangle: Shape { override func calculateArea(valA: Double, valB: Double) { area = (valA * valB) / 2 } } class Rectangle: Shape { override func calculateArea(valA: Double, valB: Double) { area = valA * valB } } <file_sep>/section3/uptownfunctions.playground/Contents.swift import UIKit // Shape 1 var length = 5 var width = 10 var area = length * width // Shape 2 var length2 = 6 var width2 = 12 var area2 = length2 * width2 // We are starting to violate DRY - Don't Repeat Yourself func calculateArea(length: Int, width: Int) -> Int { // let area = length * width // return area // returns Int area return length * width // single line return for simple operations } let shape1 = calculateArea(length: 5, width: 4) let shape2 = calculateArea(length: 6, width: 2) let shape3 = calculateArea(length: 4, width: 4) var bankAccountBalance = 500.00 // double var alienStomperShoes = 350.00 // double func purchaseItem(currentBalance: Double, itemPrice: Double) -> Double { if itemPrice <= currentBalance { print("Purchased item for: $\(itemPrice)") return currentBalance - itemPrice } else { print("You need more money to purchase the item") return currentBalance } } func mutatingPurchaseItem(currentBalance: inout Double, itemPrice: Double) { if itemPrice <= currentBalance { currentBalance = currentBalance - itemPrice print("Purchased item for: $\(itemPrice)") } else { print("You need more money to purchase the item") } } bankAccountBalance = purchaseItem(currentBalance: bankAccountBalance, itemPrice: alienStomperShoes) var retroLunchBox = 40.00 bankAccountBalance = purchaseItem(currentBalance: bankAccountBalance, itemPrice: retroLunchBox) <file_sep>/section3/09-dictionaries.playground/Contents.swift import UIKit /*: ### Code Example */ var namesOfIntegers = [Int: String]() namesOfIntegers[3] = "three" namesOfIntegers[4] = "four" namesOfIntegers = [:] var ageDictionary = ["John": 33, "Samantha": 14] var airports: [String: String] = ["YYZ": "Toronto Pearson", "LAX": "Los Angeles International"] print("The airports dictionary has: \(airports.count) items") if airports.isEmpty { print("The airports dictionary is empty!") } airports["LHR"] = "London" airports["LHR"] = "London Heathrow" airports["DEV"] = "Coder International" airports["DEV"] = nil for (airportCode, airportName) in airports { print("\(airportCode): \(airportName)") } for key in airports.keys { print("Key: \(key)") } for val in airports.values { print("Value: \(val)") } /*: ### Exercise Consider a real-world dictionary that you might read on your desk. 1. Create an animal dictionary where the key is the name of the animal and the value should be a string which represents the definition of the animal 2. Add ten animals to this dictionary 3. Iterate through the dictionary and print the keys and values in this format: `"Animal: X -- Description: Y"` where X is the name of the animal and Y is the description of the animal 4. Clear out the entire dictionary and then instead use this dictionary to store United States state abbrieviations and full names (ie CA : California) 5. Store ten state names and abbreviations in this dictionary and then print them in this format: `Y: X` where Y is the name of the state and where X is the abbreviation 6. Set the first state you chose to `nil` 7. Iterate through the array and print each key and value and see what happened to that state you set to nil */ var animals: [String: String] = ["Human": "Homo Sapien Sapiens, a primate species that created civilization. Only known intelligent species in the Milky Way Galaxy as of now."] animals["Dog"] = "Best Friends!" animals["Cat"] = "Guardians of the Computer Keyboard" animals["Cockatiel"] = "Sometimes confused with parakeets" animals["Guinea Pig"] = "Cute Little Rodent" for (animal, animalDescription) in animals { print("Animal: \(animal) -- Description: \(animalDescription)") } animals = [:] // clearing things out! animals["USA"] = "United States" // this ain't no state! and it isn't an animal! animals["CA"] = "California" for (abbreviation, fullName) in animals { print("\(fullName) : \(abbreviation)") } animals["USA"] = nil // getting removed now for (abbreviation, fullName) in animals { print("\(fullName) : \(abbreviation)") } // the USA is gone <file_sep>/section3/fizzbuzz.playground/Contents.swift func fizzBuzz(){ let end = 100 for integer in 1...end { if integer % 3 == 0 && integer % 5 == 0 { print("FizzBuzz") } else if integer % 3 == 0 { print("Fizz") } else if integer % 5 == 0 { print("Buzz") } else { print(integer) } } } //fizzBuzz() var amount = 0 for x in 0..<10 { if x % 2 == 0 { amount += 3 } } print(amount) let planets = ["Jupiter", "Mars", "Venus", "Earth"] print(planets.last!) //let result = true == false && false != true // //let firstName = "Amy" //let lastName = "Smith" //let age = 25 // //let profile = "\(firstName)\(lastName)\(age)" //let average = Int(10.3 + 4.0) / 2 //var sum = 0 //for i in 0...20 { // sum += 1 //} //print(sum) var nicknames = ["jax" : "James"] nicknames["spike"] = "Tom" nicknames["jax"] = "Billy" //let result = nicknames["jax"]! //var result = 0.0 //func calcPerimeter(sides: [Double], perimeter: Double) { // var perm = perimeter // for x in 0..<sides.count { // perm += sides[x] // } // print(perm) //} // //calcPerimeter(sides:[5.0,2.0,3.1], perimeter: result) var randomstuff = false if (randomstuff) { print(true) } enum Device: Int { case iPhone case Android case MacBook case Windows } var chosen: Device = .MacBook let result = chosen.rawValue var fullName = "empty" var firstName: String? var lastName: String? firstName = "Jan" if let first = firstName, let last = lastName { fullName = "\(first) \(last)" } // //struct Person { // var name: String // var age: Int //} //let john = Person(name: "John", age: 21) //var steven = john //steven.name = "Steven" //print(john.name) class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } let john = Person(name: "John", age: 21) var steven = john steven.name = "Steven" print(john.name) <file_sep>/section3/dictionaries.playground/Contents.swift import UIKit var namesOfIntegers = [Int: String]() // unique integer keys with string values namesOfIntegers[3] = "three" namesOfIntegers[44] = "forty four" namesOfIntegers = [:] // clear out the dictionary keys and values // var airports = ["YYZ": "Toronto Pearson", "LAX": "Los Angeles International"] var airports: [String: String] = ["YYZ": "Toronto Pearson", "LAX": "Los Angeles International"] print("The airports dictionary has: \(airports.count) items") if airports.isEmpty { print("The airports dictionary is empty!") } airports["LHR"] = "London" airports["LHR"] = "London Heathrow" // overwrites previous value airports["DEV"] = "Devlife International" airports["DEV"] = nil // destroy this key value pair with a nil value // getting a tuple, a data structure that has more than one element in it // for (key, value) in whatever for (airportCode, airportName) in airports { print("\(airportCode): \(airportName)") } for airportCode in airports.keys { print("Key: \(airportCode)") } for airportName in airports.values { print("Value: \(airportName)") } <file_sep>/section2/ArrayMiArray.playground/Contents.swift import UIKit var employee1Salary = 45000.0 var employee2Salary = 54000.0 var employee3Salary = 100000.0 var employee4Salary = 20000.0 // array of type int var employeeSalaries: [Double] = [45000.0, 54000.0, 100000.0, 20000.0] // [] brackets {} braces // var employeeSalaries: Array<Double> = [45000.0, 54000.0, 100000.0, 20000.0] print(employeeSalaries.count) employeeSalaries.append(39000.34) print(employeeSalaries.count) employeeSalaries.remove(at: 1) // remove second element print(employeeSalaries.count) // Create empty array of type string var students = [String]() // () initializes the array students.append("Jon") students.append("Jacob") students.append("Jose") students.append("Jingle") students.append("Heimer") students.append("Smith") students.remove(at: 2) // remove Jose, the 3rd element print(students) <file_sep>/section1/numbers.playground/Contents.swift import UIKit var age = 15 // Integer var price = 10.99 // Double - Default Type for Decimals /* Multi-line Comment */ var aPrice: Float = 10.99 var personAge: Int = 15 var thePrice: Double = 10.99 var length = 10 var width = 5 let area = length * width // Multiplication print(area) var health = 100 var poisonDamage = 15 health = health - poisonDamage // subtraction print(health) health -= poisonDamage // Subtraction Compound assignment operator print(health) var potion = 20 health += potion // Addition Compound assignment operator health = health + potion // Addition var students = 30 var treats = 500 let treatsPerStudent = treats / students // Division print(treatsPerStudent) // => 16 (integer result) let remainder = treats % students // Remainder operator (modulo) print(remainder) var tLength: Double = 10 var tWidth: Double = 5 // Pythagorean Theorem a^2 + b^2 = c^2 let areaTriangle = sqrt(pow(tLength, 2) + pow(tWidth, 2)) print(areaTriangle) var quantity: Int = 5 var productPrice: Double = 10.99 var cost = Double(quantity) * productPrice // type cast to quantity print(cost) <file_sep>/section4/mvcifyme/mvcifyme/mvcifymeApp.swift // // mvcifymeApp.swift // mvcifyme // // Created by <NAME> on 10/11/20. // import SwiftUI @main struct mvcifymeApp: App { var body: some Scene { WindowGroup { ContentView() } } } <file_sep>/section1/hello-swift.playground/Contents.swift import UIKit var message = "Hello, World!" print(message)
017048c0a8beab43012cf7cbf5ac10f7649254fe
[ "Swift", "Markdown" ]
18
Swift
Combatd/introProgrammingSwift5
2c3600c75125332832b03813875356b45e4dd3d6
f7a564e9d1c801b457d83fae8bc602f6ce3032b9
refs/heads/main
<repo_name>Ditya4/chat_tkinter_client_server<file_sep>/socket_chat_client.py import socket import tkinter as tk from sys import exit #=============================================================================== # def send_message(event): # print('Click') # text = edit_1.get() # print(text) # edit_1.delete(0, tk.END) #=============================================================================== def send_to_server(user, text): global conn message = user + "~~~" + text conn.send(message.encode('utf-8')) print('send', message) def pressed(event): #if event.char == 'a': print('Enter') text = edit_1.get() print(text) edit_1.delete(0, tk.END) send_to_server(USER, text) def on_closing(): global conn conn.close() exit() def memo_1_add(text): print("memo_1 get text:", text) if '~~~~' in text: text = text.replace('~~~~', '') print('memo_1 text after replace:', text) if text.count('~~~') > 1: print('memo_1 ~~~ count > 1') user_end = text.find('~~~') user = text[:user_end] message_start = user_end + 3 message = text[message_start:] memo_1.insert(tk.END, user + ': ' + message + '\n') def update_clock(): global conn conn.send('~~~~'.encode('utf-8')) received_bytes = conn.recv(1000) print("this_line", received_bytes) if received_bytes: received_text = received_bytes.decode('utf-8') if received_text != "~~~~": print('received text:', received_text) memo_1_add(received_text) else: print('( ~~~~ )') root.after(2000, update_clock) root = tk.Tk() USER = "Ditya" FORM_WEIGHT = 900 FORM_HEIGHT = 600 FORM_OFFSET_X = 200 FORM_OFFSET_Y = 100 root.geometry(str(FORM_WEIGHT) + 'x' + str(FORM_HEIGHT) + '+' + str(FORM_OFFSET_X) + '+' + str(FORM_OFFSET_Y)) string_variable = tk.StringVar() string_variable.set('') edit_1 = tk.Entry(root, textvariable=string_variable) edit_1.focus_set() edit_1.place(x=20, y=20) send_button = tk.Button(root, text='Send') send_button.place(x=20, y=60) memo_1 = tk.Text(root) memo_1.place(x=20, y=100) conn = socket.socket() conn.connect( ('127.0.0.1', 12351)) edit_1.bind("<Return>", pressed) send_button.bind('<Button-1>', pressed) root.protocol("WM_DELETE_WINDOW", on_closing) root.after(5000, update_clock) tk.mainloop() #from time import sleep #=============================================================================== # conn = socket.socket() # conn.connect( ('127.0.0.1', 12345)) # print('Enter next line("Exit" for quit):') # while True: # text = input() # if text == 'Exit': # conn.close() # break # conn.send(text.encode('utf-8')) # data = conn.recv(1000) # print('Echo from server received, with text:', data.decode('utf-8')) # print('Enter next line("Exit" for quit):') #=============================================================================== <file_sep>/socket_chat_server.py import socket from random import choice, randint sock = socket.socket() list_of_messages = ['Zeus~~~Где мой топор?', 'Demon~~~А я осиновый кол точу', 'Кузенька~~~Ой беда, беда, огорчение.'] sock.bind( ("127.0.0.1", 12351) ) # ('127.0.0.1', port) sock.listen(10) print(0) conn1, addr1 = sock.accept() while True: data = conn1.recv(1000) if data: text = data.decode('utf-8') if text == "~~~~": pass if randint(0, 6) == 1: data = choice(list_of_messages).encode('utf-8') # data = 'Zeus~~~Где мой топор?'.encode('utf-8') # pass conn1.send(data) conn1.close()
6bbbdab5b242ae8c5c9aad0de62b8bef6a0b45c6
[ "Python" ]
2
Python
Ditya4/chat_tkinter_client_server
139e485d9bb4481dfca4cc86e1524207271a9e2c
50d8df55021ca371d056922545a3efc0dbd7933b
refs/heads/master
<file_sep>//function add (a, b) { // return(a+b); //} // //var toAdd = [9,5]; // //console.log(add(...toAdd)); //var groupA = ['Jeff', 'Stef']; //var groupB = ['Mat', 'Jen']; // //var final = ['4', ...groupA, ...groupB]; // //console.log(final); var person = ['Jeff', 55] var person2 = ['Stef', 53] function greet(name, age) { console.log('Hi ' + name + ', you are ' + age); } greet(...person); greet(...person2); var names = ['Mike', 'Ben']; var final = ['Jeff', ...names]; function greet2(name) { for (var i = 0; i < name.length; i++) { console.log('Hi ' + name[i]); } } greet2(final);
2a58650298f1b939ad85b52fb44bc57c8226fd06
[ "JavaScript" ]
1
JavaScript
JeffGordon521/ReactTodo
353ec695d20a692ae0a042f26b0955ad422da48d
c557c6f76d9f3f5486c971d22ce43b71a9cac288
refs/heads/master
<file_sep>function scrollPageTo(id) { $('html, body').animate({ scrollTop: $("#"+id).offset().top }, 'slow'); } $('.scroll-me').click( function(e) { e.preventDefault(); scrollPageTo( $(this).data('section') ); } ); $('body').scrollspy({ target: '#nav-links' }); document.querySelector('.credits-toggle').addEventListener('click', function(event) { event.preventDefault(); console.log('Log'); }, false);
9aa58c94616953423f0dd922a28890f5f5f689d1
[ "JavaScript" ]
1
JavaScript
stephjiayi/first-world-war
522777001d5b8cead76e5f758647f8e836429137
0c934f90f1342f6f2355a263c55db130c0e94ec2
refs/heads/master
<file_sep>import React from 'react'; import '../modal-shared/modalShared.css'; import './editModal.css'; import PropTypes from 'prop-types'; import ModalShared from '../modal-shared/modalShared'; export default function EditModal(props) { return ( <ModalShared show={props.show} modalBody={ [ <div className="modal-edit-buttons-container"> <div className="modal-buttons modal-edit-button" onClick={props.deleteClicked}> Edit </div> <div className="modal-buttons modal-cancel-button" onClick={props.cancelClicked}> Cancel </div> </div> ] } modalTitle="Edit Brakes" stylingId="edit" /> ); } EditModal.propTypes = { show: PropTypes.bool.isRequired, deleteClicked: PropTypes.func.isRequired, cancelClicked: PropTypes.func.isRequired, stylingId: PropTypes.string.isRequired }; <file_sep>export default class ComponentsData { constructor(dbid, productname, manufacturer, contact, failrate) { this.dbid = dbid; this.productname = productname; this.manufacturer = manufacturer; this.contact = contact; this.failrate = failrate; } static get describe() { return ['Component Name', 'Manufacturer', 'Contact', 'Fail Rate']; } static get getIds() { return ['productname', 'manufacturer', 'contact', 'failrate']; } static get types() { return ['string', 'string', 'string', 'number']; } static get constraints() { return [{ canBeEmpty: false }, { canBeEmpty: false }, { canBeEmpty: false }, { moreThan: 0, lessThanOrEqualTo: 100, canBeEmpty: false, }]; } getData() { return [this.productname, this.manufacturer, this.contact, this.failrate]; } } <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { getDisplayName, getIcon } from '../utils'; import './TopMenu.css'; import './TopMenuColors.css'; function SearchField(props) { return ( <div id="mainSearchField"> <img id="searchIcon" src={getIcon('search')} alt="Search Icon" /> <input type="text" className="beautiful-textfield" placeholder={`Search ${getDisplayName(props.currentSelectedMenuItem)}`} onBlur={() => { props.setSearchActive(false); }} onFocus={(e) => { props.setSearchActive(true); props.setSearchContents(e.target.value); }} onChange={(e) => { props.setSearchContents(e.target.value); }} value={props.searchContents} /> </div> ); } SearchField.propTypes = { currentSelectedMenuItem: PropTypes.string.isRequired, setSearchActive: PropTypes.func.isRequired, searchContents: PropTypes.string.isRequired, setSearchContents: PropTypes.func.isRequired, }; function TopMenuButton(props) { return ( <div className={`topMenuButtonCircle ${props.disabled ? 'topMenuButtonCircleDisabled' : 'topMenuButtonCircleEnabled'}`} onClick={props.onClick}> <div className="topMenuButtonInnerCircle"> <img className={`topMenuButtonIcon${props.disabled ? ' topMenuButtonIconDisabled' : ''}`} id={props.imgId} src={getIcon(props.iconName)} alt={props.alt} /> </div> </div> ); } TopMenuButton.propTypes = { disabled: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired, imgId: PropTypes.string.isRequired, iconName: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, }; function MenuItem(props) { const myItemSelected = props.myMenuItem === props.currentSelectedMenuItem; return ( <div className={`segmentedControlOption segmentedControlOption${myItemSelected ? 'Selected' : 'Deselected'}`} onClick={props.onClick}> <div className={`segmentedControlImageWrapper ${myItemSelected ? 'segmentedItemSelected' : 'segmentedItemDeselected'}`}> <img className="segmentedControlIcon" src={getIcon(props.myMenuItem)} alt={getDisplayName(props.myMenuItem)} /> </div> </div> ); } MenuItem.propTypes = { myMenuItem: PropTypes.string.isRequired, currentSelectedMenuItem: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; export default class TopMenu extends React.Component { handleMenuPress(menuItem) { this.props.setSelectedMenuItem(menuItem); } render() { return ( <div id="topMenu"> <div id="topMenuMainSection"> <div className="topSegEqual" id="buttonsBar"> <div id="selectOrDeselectAll" className="topMenuButtonCircleEnabled" onClick={this.props.performDeSelectAll} > {this.props.selectionToggleButtonIsSelectAll ? 'Select All' : 'Deselect All'} </div> <TopMenuButton iconName="edit" alt="Edit" imgId="editIcon" disabled={!this.props.editEnabled} onClick={() => { this.props.performEdit(); }} /> <TopMenuButton iconName="delete" alt="Delete" imgId="deleteIcon" disabled={!this.props.deleteEnabled} onClick={() => { this.props.performDelete(); }} /> <TopMenuButton iconName="plus" alt="Add" imgId="plusIcon" disabled={false} onClick={() => { this.props.performAdd(); }} /> </div> <div id="mainSegmentedControl"> <MenuItem currentSelectedMenuItem={this.props.currentSelectedMenuItem} myMenuItem="components" onClick={() => this.handleMenuPress('components')} /> <MenuItem currentSelectedMenuItem={this.props.currentSelectedMenuItem} myMenuItem="failures" onClick={() => this.handleMenuPress('failures')} /> <MenuItem currentSelectedMenuItem={this.props.currentSelectedMenuItem} myMenuItem="modes" onClick={() => this.handleMenuPress('modes')} /> </div> <div className="topSegEqual"> <SearchField currentSelectedMenuItem={this.props.currentSelectedMenuItem} setSearchActive={this.props.setSearchActive} searchContents={this.props.searchContents} setSearchContents={this.props.setSearchContents} /> </div> </div> <div id="topMenuSelectedDisplay"> { this.props.searchTip !== '' ? this.props.searchTip : getDisplayName(this.props.currentSelectedMenuItem) } </div> </div> ); } } TopMenu.propTypes = { setSelectedMenuItem: PropTypes.func.isRequired, editEnabled: PropTypes.bool.isRequired, deleteEnabled: PropTypes.bool.isRequired, performDelete: PropTypes.func.isRequired, performAdd: PropTypes.func.isRequired, performEdit: PropTypes.func.isRequired, performDeSelectAll: PropTypes.func.isRequired, currentSelectedMenuItem: PropTypes.string.isRequired, selectionToggleButtonIsSelectAll: PropTypes.bool.isRequired, setSearchActive: PropTypes.func.isRequired, searchContents: PropTypes.string.isRequired, setSearchContents: PropTypes.func.isRequired, searchTip: PropTypes.string.isRequired, }; <file_sep>export default function cleanseInput(x) { if (x.length === 0) { return x; } let rturn = x; if (rturn[0] === ' ') { rturn = rturn.substring(1); } if (rturn.length === 0) { return rturn; } if (rturn[rturn.length - 1] === ' ') { rturn = rturn.substring(0, rturn.length - 1); } return rturn; } <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { getIcon } from '../utils'; import './pager.css'; export default class Pager extends React.Component { constructor(props) { super(props); this.state={ textFieldPage: this.props.currentPage, }; } componentDidUpdate(prevProps) { if (prevProps.currentPage !== this.props.currentPage) { // eslint-disable-next-line react/no-did-update-set-state this.setState({ textFieldPage: this.props.currentPage, }); } } render() { if (this.props.pages === 0) { return (<div />); } return ( <div id="pager-master"> <div id="pager-currentPageDisplay"> <span>Page</span> <input id="pager-input" min="1" max={this.props.pages} value={this.state.textFieldPage} onChange={(val) => { this.setState({ textFieldPage: val.target.value, }); }} onKeyDown={(event) => { if (event.key!=='Enter') { return; } let val=this.state.textFieldPage; if (isNaN(val)) { this.setState({ textFieldPage: this.props.currentPage, }); return; } let num=Number.parseInt(val, 10); if (num>=1 && num<=this.props.pages) { this.props.setPage(num); } else { this.setState({ textFieldPage: this.props.currentPage, }); } }} onBlur={() => { this.setState({ textFieldPage: this.props.currentPage, }); }} /> <span>{`of ${this.props.pages}`}</span> </div> <div id="pager-adjust"> <div className={`pager-adjust-buttons ${this.props.currentPage>1 ? 'pager-adjust-buttons-enabled' : 'pager-adjust-buttons-disabled'}`} onClick={() => { if (this.props.currentPage>1) { this.props.setPage(this.props.currentPage-1); } }} > <img className={`pager-adjust-icon${this.props.currentPage>1 ? '' : ' pager-adjust-icon-disabled'}`} alt="Last Page" src={getIcon("LeftArrow")} /> </div> <div className={`pager-adjust-buttons ${this.props.currentPage<this.props.pages ? 'pager-adjust-buttons-enabled' : 'pager-adjust-buttons-disabled'}`} onClick={() => { if (this.props.currentPage<this.props.pages) { this.props.setPage(this.props.currentPage+1); } }} > <img className={`pager-adjust-icon${this.props.currentPage<this.props.pages ? '' : ' pager-adjust-icon-disabled'}`} alt="Next Page" src={getIcon("RightArrow")} /> </div> </div> </div> ); } } Pager.propTypes = { currentPage: PropTypes.number.isRequired, pages: PropTypes.number.isRequired, setPage: PropTypes.func.isRequired, }; <file_sep>import ComponentIcon from './icons/components.svg'; import FailureIcon from './icons/failures.svg'; import ModeIcon from './icons/modes.svg'; import SearchIcon from './icons/magnifying.svg'; import PlusIcon from './icons/plus.svg'; import ArrowUp from './icons/arrowup.svg'; import ArrowDown from './icons/arrowdown.svg'; import Delete from './icons/delete.svg'; import Edit from './icons/edit.svg'; import Checkmark from './icons/checkmark.svg'; import Xmark from './icons/xmark.svg'; import LeftArrow from './icons/arrowleft.svg'; import RightArrow from './icons/arrowright.svg'; import ComponentIconDark from './icons/components-dark.svg'; import FailureIconDark from './icons/failures-dark.svg'; import ModeIconDark from './icons/modes-dark.svg'; import SearchIconDark from './icons/magnifying-dark.svg'; import PlusIconDark from './icons/plus-dark.svg'; import ArrowUpDark from './icons/arrowup-dark.svg'; import ArrowDownDark from './icons/arrowdown-dark.svg'; import DeleteDark from './icons/delete-dark.svg'; import EditDark from './icons/edit-dark.svg'; import CheckmarkDark from './icons/checkmark-dark.svg'; import XmarkDark from './icons/xmark-dark.svg'; import LeftArrowDark from './icons/arrowleft-dark.svg'; import RightArrowDark from './icons/arrowright-dark.svg'; export function getDisplayName(menuItem) { switch (menuItem) { case 'components': return 'Components'; case 'failures': return 'Mapping'; case 'modes': return 'Fail Modes'; default: console.log(`Get display name called on unrecognized menu item ${menuItem}`); } return undefined; } export function getSingularDisplayName(menuItem) { switch (menuItem) { case 'components': return 'Component'; case 'failures': return 'Mapping'; case 'modes': return 'Fail Mode'; default: console.log(`Get singular display name called on unrecognized menu item ${menuItem}`); } return undefined; } export function getIcon(name) { const isDarkTheme = window.matchMedia('(prefers-color-scheme: dark)').matches; switch (name) { case 'components': if (isDarkTheme) { return ComponentIconDark; } return ComponentIcon; case 'failures': if (isDarkTheme) { return FailureIconDark; } return FailureIcon; case 'modes': if (isDarkTheme) { return ModeIconDark; } return ModeIcon; case 'search': if (isDarkTheme) { return SearchIconDark; } return SearchIcon; case 'plus': if (isDarkTheme) { return PlusIconDark; } return PlusIcon; case 'UpArrow': if (isDarkTheme) { return ArrowUpDark; } return ArrowUp; case 'DownArrow': if (isDarkTheme) { return ArrowDownDark; } return ArrowDown; case 'delete': if (isDarkTheme) { return DeleteDark; } return Delete; case 'edit': if (isDarkTheme) { return EditDark; } return Edit; case 'checkmark': if (isDarkTheme) { return CheckmarkDark; } return Checkmark; case 'xmark': if (isDarkTheme) { return XmarkDark; } return Xmark; case 'LeftArrow': if (isDarkTheme) { return LeftArrowDark; } return LeftArrow; case 'RightArrow': if (isDarkTheme) { return RightArrowDark; } return RightArrow; case '': return undefined; default: console.log(`Requested icon ${name} not found.`); } return undefined; } <file_sep>export default function dataSearch(rawData, column, key) { if (rawData.length===0) { return []; } let curPrototypeIds = rawData[0].constructor.getIds; let searchIndex = -1; for (let i=0;i<curPrototypeIds.length;i++) { if (curPrototypeIds[i] === column) { searchIndex = i; } } if (searchIndex === -1) { console.log(`Search error: Couldn't find search column ${column}`); return []; } let searchResult=[]; for (let i=0;i<rawData.length;i++) { const tryMatch = String(rawData[i].getData()[searchIndex]); if (tryMatch.indexOf(key) !== -1) { searchResult.push({ index: i, data: rawData[i], }); } } return searchResult; } <file_sep>import './App.css'; import './Table/Table.css'; import React from 'react'; import serverRequestDelete from './services/serverRequestDelete'; import getPrototype from './GetPrototypes'; import ComponentsData from './DataStructs/ComponentsData'; import ModesData from './DataStructs/ModesData'; import FailsData from './DataStructs/FailsData'; import MainTable from './Table/Table'; import TopMenu from './TopMenu/TopMenu'; import httpCall from './services/httpCall'; import DeleteModal from './Modals/DeleteModal/deleteModal'; import AddEditModal from './Modals/AddEditModal/addEditModal'; import { getDisplayName, getSingularDisplayName } from './utils'; import serverRequestAdd from './services/serverRequestAdd'; import serverRequestUpdate from './services/serverRequestUpdate'; import * as globals from './globals'; import cleanseInput from './DataStructs/cleanseInput'; import dataSearch from './dataSearch'; import rootTypeToState from './DataStructs/rootTypeToState'; import getCorrespondingDisplayNameOfColumnId from './DataStructs/getCorrespondingDisplayNameOfColumnId'; import autocompleteSearch from './autocompleteSearch'; import Pager from './Pager/pager'; class App extends React.Component { async fetchComponents() { const callUrl=`${globals.rootURL}/components/fetchAll`; const rawData=this.rawComponentsData; const relevantSelections=this.componentSelections; const relevantSelectionCache=this.componentsSelectedCache; await httpCall(callUrl).then((reqsReturn) => { relevantSelectionCache.length=0; const gottenData = reqsReturn[0]; let newRawData = Array(gottenData.length); for (let i = 0; i < gottenData.length; i++) { const current = gottenData[i]; newRawData[i] = new ComponentsData(current.pkid, current.productname, current.manufacturer, current.contact, current.failrate); } this.componentSelections=this.realignSelections(rawData, gottenData, relevantSelectionCache, relevantSelections, newRawData); this.rawComponentsData=newRawData; }); } async fetchModes() { const callUrl=`${globals.rootURL}/fail_mode/fetchAll`; const rawData=this.rawModesData; const relevantSelections=this.modesSelections; const relevantSelectionCache=this.modesSelectedCache; await httpCall(callUrl).then((reqsReturn) => { relevantSelectionCache.length=0; const gottenData = reqsReturn[0]; let newRawData = Array(gottenData.length); for (let i = 0; i < gottenData.length; i++) { const current = gottenData[i]; newRawData[i] = new ModesData(current.pkid, current.failname, current.code, current.description); } this.modesSelections=this.realignSelections(rawData, gottenData, relevantSelectionCache, relevantSelections, newRawData); this.rawModesData=newRawData; }); } // eslint-disable-next-line class-methods-use-this realignSelections(rawData, gottenData, relevantSelectionCache, relevantSelections, newRawData) { let pkidToOldIndexMap = new Map(); for (let i=0;i<rawData.length;i++) { pkidToOldIndexMap.set(rawData[i].dbid, i); } let newSelectionData=Array(gottenData.length); for (let i=0;i<newRawData.length;i++) { let oldIndex=pkidToOldIndexMap.get(newRawData[i].dbid); if (oldIndex===undefined) { newSelectionData[i]=false; } else { newSelectionData[i]=relevantSelections[oldIndex]; if (newSelectionData[i]) { relevantSelectionCache.push(i); } } } return newSelectionData; } async fetchFailures() { const callUrl=`${globals.rootURL}/mapping/fetchAll`; const rawData=this.rawFailsData; const relevantSelections=this.failuresSelections; const relevantSelectionCache=this.failuresSelectedCache; await httpCall(callUrl).then((reqsReturn) => { relevantSelectionCache.length=0; const gottenData = reqsReturn[0]; let newRawData = Array(gottenData.length); for (let i = 0; i < gottenData.length; i++) { const current = gottenData[i]; newRawData[i] = new FailsData(current.pkid, current.failComponentId, current.failComponentName, current.failModeId, current.failModeName, current.failCode, current.failDescription); } this.failuresSelections=this.realignSelections(rawData, gottenData, relevantSelectionCache, relevantSelections, newRawData); this.rawFailsData=newRawData; }); } constructor(props) { super(props); this.selectionAnchor = -1; this.selectionLastAction = ''; this.componentsSelectedCache = []; // selection cache is in database sorting this.modesSelectedCache = []; this.failuresSelectedCache = []; this.currentSortToDbMapping = []; this.currentDbToSortMapping = []; this.rawComponentsData = []; this.rawModesData = []; this.rawFailsData = []; this.state = { currentSelectedMenuItem: 'failures', sortedColumn: { components: 'num', failures: 'num', modes: 'num', }, sortMethodAscending: { components: true, failures: true, modes: true, }, pages: { components: 0, failures: 0, modes: 0, }, numberOfPages: 0, displayLRange: 0, displayRRange: 0, displayData: [], deleteModalShown: false, deleteModalText: '', addModalShown: false, dataLength: -1, isInSearch: false, searchColumn: { components: 'productname', failures: 'failedcomponent', modes: 'name', }, searchContents: "", editModalShown: false, additionalEditInfo: {}, }; } componentDidMount() { this.fetchFailures().then(() => { this.recomputeData('failures', 'num', true); }); } changeCurrentSelectedMenuItem(val) { this.recomputeData(val); this.setState({ currentSelectedMenuItem: val, searchContents: "", }); switch (val) { case "components": this.fetchComponents() .then(() => { this.recomputeData('components', this.state.sortedColumn.components, this.state.sortMethodAscending.components, "", false, this.state.searchColumn.components); }); break; case "failures": this.fetchFailures() .then(() => { this.recomputeData('failures', this.state.sortedColumn.failures, this.state.sortMethodAscending.failures, "", false, this.state.searchColumn.failures); }); break; case "modes": this.fetchModes() .then(() => { this.recomputeData('modes', this.state.sortedColumn.modes, this.state.sortMethodAscending.modes, "", false, this.state.searchColumn.modes); }); break; default: console.log(`Invalid menu item change ${val}`); } } getRawData(selectedState = this.state.currentSelectedMenuItem) { switch (selectedState) { case 'components': return this.rawComponentsData; case 'failures': return this.rawFailsData; case 'modes': return this.rawModesData; default: console.log(`Get raw data called on invalid state ${selectedState}.`); return undefined; } } recomputeData(selectedState = this.state.currentSelectedMenuItem, sortedColumn = this.state.sortedColumn[selectedState], sortMethodAscending = this.state.sortMethodAscending[selectedState], searchContents = this.state.searchContents, isInSearch = this.state.isInSearch, searchColumn = this.state.searchColumn[this.state.currentSelectedMenuItem], currentPage = null) { this.selectionAnchor = -1; this.selectionLastAction = ''; console.log('Recomputing display data'); let accompanyingSelectionData = []; let accompanyingLRange; let accompanyingRRange; switch (selectedState) { case 'components': accompanyingSelectionData = this.componentSelections; accompanyingLRange=this.state.pages.components; break; case 'failures': accompanyingSelectionData = this.failuresSelections; accompanyingLRange=this.state.pages.failures; break; case 'modes': accompanyingSelectionData = this.modesSelections; accompanyingLRange=this.state.pages.modes; break; default: console.log(`Unknown selected state (${selectedState})`); } if (currentPage !== null) { accompanyingLRange=currentPage; } let displayData = this.getRawData(selectedState).slice(); let totalPages = Math.floor(displayData.length / globals.eachPage); accompanyingLRange = Math.min(accompanyingLRange, totalPages); accompanyingLRange*=globals.eachPage; accompanyingRRange=Math.min(accompanyingLRange+globals.eachPage, displayData.length); for (let i = 0; i < displayData.length; i++) { displayData[i].num = i + 1; displayData[i].selected = accompanyingSelectionData[i]; } if (isInSearch) { displayData=dataSearch(displayData, searchColumn, searchContents); for (let i=0;i<displayData.length;i++) { displayData[i]=displayData[i].data; } } this.currentSortToDbMapping = Array(displayData.length); this.currentDbToSortMapping = Array(displayData.length); if (displayData.length > 0) { if (sortedColumn === 'num') { if (!sortMethodAscending) { displayData.reverse(); } } else { const elementsDescription = displayData[0].constructor.getIds; const elementsType = displayData[0].constructor.types; let sortBy = -1; for (let i = 0; i < elementsDescription.length; i++) { if (elementsDescription[i] === sortedColumn) { sortBy = i; } } if (sortBy === -1) { console.log(`Cannot find sort column ID ${sortedColumn}`); return displayData; } const floatSort = elementsType[sortBy] === 'number'; displayData.sort((a, b) => { const aData = a.getData(); const bData = b.getData(); let aComp = aData[sortBy]; let bComp = bData[sortBy]; if (floatSort) { aComp = parseFloat(aComp); bComp = parseFloat(bComp); } if (sortMethodAscending) { return (aComp > bComp ? 1 : -1); } return (aComp < bComp ? 1 : -1); }); } for (let i = 0; i < displayData.length; i++) { this.currentSortToDbMapping[i] = displayData[i].num - 1; } for (let i = 0; i < displayData.length; i++) { this.currentDbToSortMapping[this.currentSortToDbMapping[i]] = i; } } this.setState({ displayData: displayData, dataLength: displayData.length, displayLRange: accompanyingLRange, displayRRange: accompanyingRRange, numberOfPages: displayData.length === 0 ? 0 : Math.floor(displayData.length/globals.eachPage)+1, }); return null; } getRelSelectionArrayAndCache(currentMenuState = this.state.currentSelectedMenuItem) { let relSelectionArray; let relSelectionCache; switch (currentMenuState) { case 'components': relSelectionArray = this.componentSelections; relSelectionCache = this.componentsSelectedCache; break; case 'failures': relSelectionArray = this.failuresSelections; relSelectionCache = this.failuresSelectedCache; break; case 'modes': relSelectionArray = this.modesSelections; relSelectionCache = this.modesSelectedCache; break; default: console.log(`Getting relevant selection and cache for unknown table type ${currentMenuState}`); } return [relSelectionArray, relSelectionCache]; } handleDeSelectAllButtonPressed() { const shouldSelectAll = this.selectionToggleButtonIsSelectAll(); const [relSelectionArray, relSelectionCache] = this.getRelSelectionArrayAndCache(); // clear the cache relSelectionCache.length = 0; for (let i = 0; i < this.state.displayData.length; i++) { relSelectionArray[this.currentSortToDbMapping[i]] = shouldSelectAll; } for (let i=0;i<relSelectionArray.length;i++) { if (relSelectionArray[i]) { relSelectionCache.push(i); } } const newDisplayData = this.state.displayData.slice(); for (let i = 0; i < newDisplayData.length; i++) { newDisplayData[i].selected = shouldSelectAll; } this.setState({ displayData: newDisplayData, }); } processClick(tableRow, action) { // single select -> deselect everything and only select one. set this to the anchor. // multi select -> toggle the selection on that one. if it is now selected, set it to the anchor. // if it isn't selected. set the anchor to no anchor. // range select -> look at the anchor. if there is no anchor, simply treat this as a multi-select (but without setting another anchor) // if there is an anchor, use it and LEAVE IT THERE. // if the last action was a multi-select, completely erase its selection and do the selection. // remember to set the anchor to none every time the table is resorted // required data for each state: anchor, lastAction // IMPORTANT: Anchor is in terms of current coordinates // eslint-disable-next-line prefer-const let [relSelectionArray, relSelectionCache] = this.getRelSelectionArrayAndCache(tableRow.tableType); const selectIndex = tableRow.tableIndex; // eslint-disable-next-line react/no-access-state-in-setstate const newDisplayData = this.state.displayData.slice(); if (action === 'single') { for (let i = 0; i < relSelectionCache.length; i++) { relSelectionArray[relSelectionCache[i]] = false; } const dbIndex = this.currentSortToDbMapping[selectIndex]; relSelectionArray[dbIndex] = true; for (let i = 0; i < relSelectionCache.length; i++) { if (this.currentDbToSortMapping[relSelectionCache[i]] !== undefined) { newDisplayData[this.currentDbToSortMapping[relSelectionCache[i]]].selected = false; } } newDisplayData[selectIndex].selected = true; relSelectionCache = [dbIndex]; this.selectionLastAction = { action: 'single', params: selectIndex, }; this.selectionAnchor = selectIndex; } else if (action === 'multi' || (action === 'range' && this.selectionAnchor === -1)) { const dbIndex = this.currentSortToDbMapping[selectIndex]; if (relSelectionArray[dbIndex]) { // remove the selection and set anchor to none relSelectionArray[dbIndex] = false; newDisplayData[selectIndex].selected = false; for (let i = 0; i < relSelectionCache.length; i++) { if (relSelectionCache[i] === dbIndex) { relSelectionCache.splice(i, 1); } } this.selectionAnchor = -1; } else { // add the selection and set anchor to the selection relSelectionArray[dbIndex] = true; newDisplayData[selectIndex].selected = true; relSelectionCache.push(dbIndex); if (action !== 'range') { this.selectionAnchor = selectIndex; } } if (action === 'range') { this.selectionLastAction = { action: 'range_multi_fallback', params: selectIndex, }; } else { this.selectionLastAction = { action: 'multi', params: selectIndex, }; } } else if (action === 'range') { if (this.selectionLastAction.action === 'range') { const eraseL = Math.min(this.selectionAnchor, this.selectionLastAction.params); const eraseR = Math.max(this.selectionAnchor, this.selectionLastAction.params); for (let i = eraseL; i <= eraseR; i++) { relSelectionArray[this.currentSortToDbMapping[i]] = false; newDisplayData[i].selected = false; } for (let i = 0; i < relSelectionCache.length; i++) { if (this.currentDbToSortMapping[relSelectionCache[i]] >= eraseL && this.currentDbToSortMapping[relSelectionCache[i]] <= eraseR) { relSelectionCache.splice(i, 1); i--; } } } const l = Math.min(selectIndex, this.selectionAnchor); const r = Math.max(selectIndex, this.selectionAnchor); for (let i = l; i <= r; i++) { if (!relSelectionArray[this.currentSortToDbMapping[i]]) { relSelectionCache.push(this.currentSortToDbMapping[i]); } relSelectionArray[this.currentSortToDbMapping[i]] = true; newDisplayData[i].selected = true; } this.selectionLastAction = { action: 'range', params: selectIndex, }; } switch (tableRow.tableType) { case 'components': this.componentSelections = relSelectionArray; this.componentsSelectedCache = relSelectionCache; break; case 'failures': this.failuresSelections = relSelectionArray; this.failuresSelectedCache = relSelectionCache; break; case 'modes': this.modesSelections = relSelectionArray; this.modesSelectedCache = relSelectionCache; break; default: console.log(`Processing click for unknown table type ${tableRow.tableType}`); } this.setState({ displayData: newDisplayData, }); } async getSelectedDetails() { // gets details about the current selection for deletion. // selectionCache: a list of indexes are selected in the current selected page // rawData: just the raw list of data of the current selected page // selectionRawData: an array of booleans that provides the source of truth for whether or not every element is selected on the page. // relatedFailureDeletions: the indexes of the dependencies in Failures that would be deleted const currentState = this.state.currentSelectedMenuItem; let selectionCache; let rawData; let selectionRawData; const relatedFailureDeletions = []; switch (currentState) { case 'components': selectionCache = this.componentsSelectedCache; rawData = this.rawComponentsData; selectionRawData = this.componentSelections; break; case 'failures': selectionCache = this.failuresSelectedCache; rawData = this.rawFailsData; selectionRawData = this.failuresSelections; break; case 'modes': selectionCache = this.modesSelectedCache; rawData = this.rawModesData; selectionRawData = this.modesSelections; break; default: console.log(`Delete selection called on invalid menu item ${this.state.currentSelectedMenuItem}`); } if (currentState !== 'failures') { await this.fetchFailures(); const dbidGettingDeletedMap = {}; for (let i = 0; i < selectionCache.length; i++) { dbidGettingDeletedMap[rawData[selectionCache[i]].dbid] = true; } for (let i = 0; i < this.rawFailsData.length; i++) { if (currentState === 'components') { if (dbidGettingDeletedMap[this.rawFailsData[i].failComponentId] === true) { relatedFailureDeletions.push(i); } } else if (dbidGettingDeletedMap[this.rawFailsData[i].failModeId] === true) { relatedFailureDeletions.push(i); } } } return [selectionCache, rawData, selectionRawData, relatedFailureDeletions]; } async deleteSelection() { // delete the current selection, taking into consideration that dependencies (such as failures) also have to be deleted. const deleteSelection = []; const selectionDetails = await this.getSelectedDetails(); const selectionCache = selectionDetails[0]; const rawData = selectionDetails[1]; const selectionRawData = selectionDetails[2]; const relatedFailureDeletions = selectionDetails[3]; if (selectionCache.length > 0) { for (let i = 0; i < selectionCache.length; i++) { deleteSelection.push(rawData[selectionCache[i]].dbid); } // send list of deletions to server and wait for server response await serverRequestDelete(deleteSelection, this.state.currentSelectedMenuItem); // delete the elements from the local copy according to the cache, which holds a list of items which are selected. selectionCache.sort(); for (let i = selectionCache.length - 1; i >= 0; i--) { rawData.splice(selectionCache[i], 1); selectionRawData.splice(selectionCache[i], 1); } // clear the cache selectionCache.length = 0; if (relatedFailureDeletions.length > 0) { // erase related deletions relatedFailureDeletions.sort(); // remove all the related deletions from failures // again, go through the list of things that have to be deleted and delete them. for (let i = relatedFailureDeletions.length - 1; i >= 0; i--) { this.rawFailsData.splice(relatedFailureDeletions[i], 1); this.failuresSelections.splice(relatedFailureDeletions[i], 1); } // now remove these things from the cache. this.failuresSelectedCache.sort(); let currentRelatedFailureDeletionsAt = relatedFailureDeletions.length - 1; for (let i = this.failuresSelectedCache.length - 1; i >= 0; i--) { if (currentRelatedFailureDeletionsAt !== -1) { if (this.failuresSelectedCache[i] === relatedFailureDeletions[currentRelatedFailureDeletionsAt]) { this.rawFailsData.splice(i, 1); this.failuresSelections.splice(i, 1); currentRelatedFailureDeletionsAt--; } } } } this.recomputeData(); this.selectionAnchor=-1; } } async confirmAndDelete() { // generate a confirmation message and show the modal let nextConfirmMessage; const selectionDetails = await this.getSelectedDetails(); const selectionCache = selectionDetails[0]; const willDelete = selectionDetails[3].length; if (selectionCache.length === 0) { return; } const currentState = this.state.currentSelectedMenuItem; if (currentState === 'failures') { nextConfirmMessage = `${selectionCache.length} ${getSingularDisplayName('failures')}${selectionCache.length > 1 ? 's' : ''} will be deleted permanently`; this.setState({ deleteModalShown: true, deleteModalText: nextConfirmMessage, }); } else { nextConfirmMessage = `${selectionCache.length} ${getSingularDisplayName(currentState === 'components' ? 'components' : 'modes')}${selectionCache.length > 1 ? 's' : ''}`; if (willDelete > 0) nextConfirmMessage += ` and ${willDelete} related ${getSingularDisplayName('failures')}${willDelete > 1 ? 's' : ''}`; nextConfirmMessage += ' will be deleted permanently'; this.setState({ deleteModalShown: true, deleteModalText: nextConfirmMessage, }); } } getCurrentNumberOfSelections() { // get the number of items currently selected switch (this.state.currentSelectedMenuItem) { case 'components': return this.componentsSelectedCache.length; case 'failures': return this.failuresSelectedCache.length; case 'modes': return this.modesSelectedCache.length; default: console.log(`Getting current nuumber ot selections called on invalid menu item ${this.state.currentSelectedMenuItem}`); } return undefined; } checkDeleteEnabled() { // determines whether or not the delete button is greyed out. return this.getCurrentNumberOfSelections() > 0; } checkEditEnabled() { // determines whether or not the edit button is greyed out return this.getCurrentNumberOfSelections() === 1; } selectionToggleButtonIsSelectAll() { // determines whether or not the selection button is select all if (this.state.dataLength === 0) { return true; } return this.getCurrentNumberOfSelections() !== this.state.dataLength; } generateNewObject(currentState = this.state.currentSelectedMenuItem, args) { const curPrototype = getPrototype(currentState).constructor; const isRootType = curPrototype.rootDescribe !== undefined; const identifiers = isRootType ? curPrototype.rootTypes : curPrototype.getIds; const serverObj = {}; if (args.length === identifiers.length) { for (let i = 0; i < identifiers.length; i++) { serverObj[identifiers[i]] = isRootType ? this.fetchInfoByIndex(rootTypeToState(curPrototype.rootTypes[i]), args[i]).dbid : cleanseInput(args[i]); } } else { console.log(`Generate new object: argument length mismatch`); return {}; } let dataStructObj; let linkedComponentIndex=-1; let linkedModeIndex=-1; switch (currentState) { case 'components': dataStructObj=new ComponentsData(-1, serverObj.productname, serverObj.manufacturer, serverObj.contact, serverObj.failrate); break; case 'failures': for (let i=0;i<this.rawComponentsData.length;i++) { if (this.rawComponentsData[i].dbid===serverObj.component_pkid) { linkedComponentIndex=i; } } for (let i=0;i<this.rawModesData.length;i++) { if (this.rawModesData[i].dbid===serverObj.mode_pkid) { linkedModeIndex=i; } } if (linkedComponentIndex===-1||linkedModeIndex===-1) { console.log(`Generate new object: linked component or linked mode not found.`); return {}; } dataStructObj=new FailsData(-1, serverObj.component_pkid, this.rawComponentsData[linkedComponentIndex].productname, serverObj.mode_pkid, this.rawModesData[linkedModeIndex].failname, this.rawModesData[linkedModeIndex].code, this.rawModesData[linkedModeIndex].description); break; case 'modes': dataStructObj=new ModesData(-1, serverObj.name, serverObj.code, serverObj.description); break; default: console.log(`Creating object called on invalid menu item ${currentState}`); } return { serverObj, dataStructObj }; } createAndAddObject(dataStructObj, currentState) { const [relSelectionArray, relSelectionCache] = this.getRelSelectionArrayAndCache(currentState); switch (currentState) { case 'components': this.rawComponentsData.unshift(dataStructObj); break; case 'failures': this.rawFailsData.unshift(dataStructObj); break; case 'modes': this.rawModesData.unshift(dataStructObj); break; default: console.log(`Creating object called on invalid menu item ${currentState}`); } relSelectionArray.unshift(false); for (let i=0;i<relSelectionCache.length;i++) { relSelectionCache[i]++; } this.selectionAnchor=-1; this.recomputeData(); } updateObject(dataStructObj, index, currentState) { switch (currentState) { case 'components': this.rawComponentsData[index]=dataStructObj; for (let i=0;i<this.rawFailsData.length;i++) { if (this.rawFailsData[i].failComponentId === this.rawComponentsData[index].dbid) { this.rawFailsData[i].failComponentName = this.rawComponentsData[index].productname; } } break; case 'failures': this.rawFailsData[index]=dataStructObj; break; case 'modes': this.rawModesData[index]=dataStructObj; for (let i=0;i<this.rawFailsData.length;i++) { if (this.rawFailsData[i].failModeId === this.rawModesData[index].dbid) { this.rawFailsData[i].failModeName = this.rawModesData[index].failname; this.rawFailsData[i].failCode = this.rawModesData[index].code; this.rawFailsData[i].failDescription = this.rawModesData[index].description; } } break; default: console.log(`Updating object called on invalid menu item ${currentState}`); } this.recomputeData(); } fetchInfoByIndex(state, index) { switch (state) { case 'components': return this.rawComponentsData[index]; case 'failures': return this.rawFailsData[index]; case 'modes': return this.rawModesData[index]; default: console.log(`Fetch info on index called on invalid menu item ${state}`); } return null; } async fetchRootDataByDbid(type, dbid, performFetch) { let match = -1; let rawMatchData=(type==='component_pkid' ? this.rawComponentsData : this.rawModesData); for (let j=0;j<rawMatchData.length;j++) { if (rawMatchData[j].dbid === dbid) { match=j; break; } } let didGoFetch = false; if (match === -1 && performFetch) { didGoFetch=true; if (type==='component_pkid') { await this.fetchComponents(); [match] = await this.fetchRootDataByDbid(type, dbid, false); } else { await this.fetchModes(); [match] = await this.fetchRootDataByDbid(type, dbid, false); } } return [match, didGoFetch]; } render() { return ( <div id="masterContainer" className={window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark-theme' : ''}> <DeleteModal show={this.state.deleteModalShown} text={this.state.deleteModalText} deleteClicked={() => { this.deleteSelection(); this.setState({ deleteModalShown: false, }); }} cancelClicked={() => { this.setState({ deleteModalShown: false, }); }} /> <AddEditModal modalType="add" show={this.state.addModalShown} submitClicked={(args) => { let { serverObj, dataStructObj } = this.generateNewObject(this.state.currentSelectedMenuItem, args); if (serverObj === undefined || dataStructObj === undefined) { return; } serverRequestAdd(serverObj, this.state.currentSelectedMenuItem).then((res) => { // eslint-disable-next-line prefer-destructuring dataStructObj.dbid=res.data[0]; this.createAndAddObject(dataStructObj, this.state.currentSelectedMenuItem); }); this.setState({ addModalShown: false, }); }} cancelClicked={() => { this.setState({ addModalShown: false, }); }} addItemDisplayTitle={getSingularDisplayName(this.state.currentSelectedMenuItem)} objectPrototype={getPrototype(this.state.currentSelectedMenuItem)} autocompleteSearch={autocompleteSearch.bind(this)} fetchInfoByIndex={this.fetchInfoByIndex.bind(this)} additionalEditInfo={{}} /> <AddEditModal modalType="edit" show={this.state.editModalShown} submitClicked={(args) => { let { serverObj, dataStructObj }= this.generateNewObject(this.state.currentSelectedMenuItem, args); if (serverObj === undefined || dataStructObj === undefined) { return; } let { index } = this.state.additionalEditInfo; switch (this.state.currentSelectedMenuItem) { case "components": serverObj.pkid=this.rawComponentsData[index].dbid; dataStructObj.dbid=this.rawComponentsData[index].dbid; break; case "failures": serverObj.pkid=this.rawFailsData[index].dbid; dataStructObj.dbid=this.rawFailsData[index].dbid; break; case "modes": serverObj.pkid=this.rawModesData[index].dbid; dataStructObj.dbid=this.rawModesData[index].dbid; break; default: console.log(`Tried to assign pkid with invalid state ${this.state.currentSelectedMenuItem}`); } serverRequestUpdate(serverObj, this.state.currentSelectedMenuItem).then(() => { this.updateObject(dataStructObj, index, this.state.currentSelectedMenuItem); }); this.setState({ editModalShown: false, }); }} cancelClicked={() => { this.setState({ editModalShown: false, }); }} addItemDisplayTitle={getSingularDisplayName(this.state.currentSelectedMenuItem)} objectPrototype={getPrototype(this.state.currentSelectedMenuItem)} autocompleteSearch={autocompleteSearch.bind(this)} fetchInfoByIndex={this.fetchInfoByIndex.bind(this)} additionalEditInfo={this.state.additionalEditInfo} /> <div id="masterInnerContainer"> <div id="topMenuContainer"> <TopMenu currentSelectedMenuItem={this.state.currentSelectedMenuItem} setSelectedMenuItem={this.changeCurrentSelectedMenuItem.bind(this)} deleteEnabled={this.checkDeleteEnabled()} editEnabled={this.checkEditEnabled()} performDelete={this.confirmAndDelete.bind(this)} performAdd={async () => { this.setState({ addModalShown: true, }); let isRootType = getPrototype(this.state.currentSelectedMenuItem).constructor.rootDescribe !== undefined; if (isRootType) { let types=getPrototype(this.state.currentSelectedMenuItem).constructor.rootTypes; for (let i=0;i<types.length;i++) { if (types[i]==='component_pkid' || types[i]==='mode_pkid') { if (types[i]==='component_pkid') { this.fetchComponents(); } else { this.fetchModes(); } } else { console.log(`Unrecognized root type ${types[i]}`); } } } }} performEdit={async () => { let [selectionCache, rawData, , relatedFailureDeletions] = await this.getSelectedDetails(); if (selectionCache.length !== 1) { return; } let editIndex=selectionCache[0]; let name; switch (this.state.currentSelectedMenuItem) { case 'components': name=rawData[editIndex].productname; break; case 'failures': name='Failure'; break; case 'mode': name=rawData[editIndex].failname; break; default: console.log(`Perform edit called on unexpected state ${this.state.currentSelectedMenuItem}`); } let sub=`Database ID ${rawData[editIndex].dbid}`; if (relatedFailureDeletions.length>0) { sub=`${sub} • ${getSingularDisplayName(this.state.currentSelectedMenuItem)} associated with ${relatedFailureDeletions.length} Mapping${relatedFailureDeletions.length>1 ? "s" : ""}`; } let isRootType = rawData[editIndex].constructor.rootDescribe !== undefined; let rootData=[]; if (isRootType) { let types=rawData[editIndex].constructor.rootTypes; let rawRootData=rawData[editIndex].getRootData(); let fetchJobs=[]; for (let i=0;i<types.length;i++) { if (types[i]==='component_pkid' || types[i]==='mode_pkid') { fetchJobs.push(this.fetchRootDataByDbid(types[i], rawRootData[i], true)); } else { console.log(`Unrecognized root type ${types[i]}`); } } let results = await Promise.all(fetchJobs); for (let i=0;i<types.length;i++) { // eslint-disable-next-line no-await-in-loop let [match, fetched] = results[i]; if (!fetched) { if (types[i] === 'component_pkid') { this.fetchComponents(); } else { this.fetchModes(); } } if (match === -1) { console.log(`Failed to load edit view, couldn't find ${types[i]==='component_pkid' ? 'Component' : 'Mode'} with database ID ${rawRootData[i]}`); return; } rootData.push(match); } } this.setState({ editModalShown: true, additionalEditInfo: { index: editIndex, name: name, sub: sub, data: isRootType ? rootData : rawData[editIndex].getData(), }, }); }} performDeSelectAll={this.handleDeSelectAllButtonPressed.bind(this)} selectionToggleButtonIsSelectAll={this.selectionToggleButtonIsSelectAll()} setSearchActive={(val) => { if (!val && this.state.searchContents !== '') { return; } this.setState({ isInSearch: val, }); }} searchContents={this.state.searchContents} setSearchContents={(val) => { this.setState({ searchContents: val, }); this.recomputeData(undefined, undefined, undefined, val, true); // actually do the search now }} searchTip={this.state.isInSearch ? `${getDisplayName(this.state.currentSelectedMenuItem)}: Searching ${getCorrespondingDisplayNameOfColumnId(getPrototype(this.state.currentSelectedMenuItem), this.state.searchColumn[this.state.currentSelectedMenuItem])}` : ''} /> </div> <MainTable displayData={this.state.displayData} displayLRange={this.state.displayLRange} displayRRange={this.state.displayRRange} sortedColumn={this.state.sortedColumn[this.state.currentSelectedMenuItem]} sortMethodAscending={this.state.sortMethodAscending[this.state.currentSelectedMenuItem]} tableType={this.state.currentSelectedMenuItem} processClick={this.processClick.bind(this)} highlightData={this.state.highlightData} tableDataPrototype={getPrototype(this.state.currentSelectedMenuItem)} handleHeaderClick={(id, cmdOrOptionHeld) => { if (!this.state.isInSearch || (this.state.isInSearch && cmdOrOptionHeld)) { let newSortedColumn = { ...this.state.sortedColumn }; let newSortMethodAscending = { ...this.state.sortMethodAscending }; if (id === newSortedColumn[this.state.currentSelectedMenuItem]) { newSortMethodAscending[this.state.currentSelectedMenuItem] = !newSortMethodAscending[this.state.currentSelectedMenuItem]; } else { newSortedColumn[this.state.currentSelectedMenuItem] = id; newSortMethodAscending[this.state.currentSelectedMenuItem] = true; } this.recomputeData(this.state.currentSelectedMenuItem, newSortedColumn[this.state.currentSelectedMenuItem], newSortMethodAscending[this.state.currentSelectedMenuItem]); this.setState(() => ({ sortedColumn: newSortedColumn, sortMethodAscending: newSortMethodAscending, })); } else { if (id === 'num') { return; } let newSearchColumn = { ...this.state.searchColumn }; newSearchColumn[this.state.currentSelectedMenuItem] = id; this.setState({ searchColumn: newSearchColumn, }); this.recomputeData(undefined, undefined, undefined, undefined, undefined, id); } }} isInSearch={this.state.isInSearch} searchColumn={this.state.searchColumn[this.state.currentSelectedMenuItem]} /> <Pager pages={this.state.numberOfPages} currentPage={this.state.pages[this.state.currentSelectedMenuItem]+1} setPage={(page) => { let newPages={ ...this.state.pages }; newPages[this.state.currentSelectedMenuItem]=page-1; this.setState({ pages: newPages, }); this.recomputeData(undefined, undefined, undefined, undefined, undefined, undefined, page-1); }} /> </div> </div> ); } } export default App; <file_sep>import FailsData from './DataStructs/FailsData'; import ComponentsData from './DataStructs/ComponentsData'; import ModesData from './DataStructs/ModesData'; export default function getPrototype(curState) { switch (curState) { case 'components': return new ComponentsData('', '', '', '', '', ''); case 'failures': return new FailsData('', '', '', '', '', ''); case 'modes': return new ModesData('', '', '', ''); default: console.log(`Unknown state for prototype ${curState}`); } return undefined; } <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import ModalShared from '../modal-shared/modalShared'; import '../modal-shared/modalShared.css'; import './addEditModal.css'; import './addEditModalColors.css'; import '../../Shared Components/Bordered Input Box Styles/borderedInputBox.css'; import '../../Shared Components/Bordered Input Box Styles/borderedInputBoxColors.css'; import validateInput from '../../DataStructs/validateInput'; import AutocompleteBox from '../../Shared Components/Autocomplete Box/AutocompleteBox'; export default class AddEditModal extends React.Component { initialize(firstTime) { const isRootDescribe = (this.props.objectPrototype.constructor.rootDescribe !== undefined); let addModalFields; if (isRootDescribe) { addModalFields=this.props.objectPrototype.constructor.rootDescribe.length; } else { addModalFields=this.props.objectPrototype.constructor.describe.length; } const inputIsInvalidState = Array(addModalFields); let inputFieldValuesState = Array(addModalFields); for (let i = 0; i < addModalFields; i++) { inputIsInvalidState[i] = false; inputFieldValuesState[i] = isRootDescribe ? -1 : ''; } if (this.props.modalType === 'edit' && this.props.additionalEditInfo.data !== undefined) { inputFieldValuesState = this.props.additionalEditInfo.data; } if (firstTime) { this.state = { inputIsInvalid: inputIsInvalidState, inputFieldValues: inputFieldValuesState, inputInvalidMessage: '', autocompleteSelectedInfo: [], }; } else { this.setState({ inputIsInvalid: inputIsInvalidState, inputFieldValues: inputFieldValuesState, inputInvalidMessage: '', autocompleteSelectedInfo: [], }); } } constructor(props) { super(props); // state the addModal has to keep track of: whether or not an input box is red this.initialize(true); } componentDidUpdate(prevProps) { if (prevProps.objectPrototype !== this.props.objectPrototype || prevProps.show !== this.props.show || prevProps.additionalEditInfo !== this.props.additionalEditInfo) { this.initialize(false); } } render() { if (this.props.modalType !== 'add' && this.props.modalType !== 'edit') { console.log(`Addedit called on invalid modal type ${this.props.modalType}`); } const curPrototype = this.props.objectPrototype.constructor; const isRootDescribe = (curPrototype.rootDescribe !== undefined); const addChildren = []; let description = (isRootDescribe ? curPrototype.rootDescribe : curPrototype.describe); if (this.props.show && description.length === this.state.inputFieldValues.length) { for (let i = 0; i < description.length; i++) { if (isRootDescribe) { addChildren.push( <div className="modal-addedit-row" key={`modal-addedit-row-${description[i]}`}> <div className="modal-addedit-row-label"> {description[i]} </div> <AutocompleteBox autocompleteSearch={(val) => { let translatedName; switch (curPrototype.rootTypes[i]) { case "component_pkid": translatedName = 'components'; break; case 'mode_pkid': translatedName = 'modes'; break; default: console.log(`Translated name requested for unknown root type ${curPrototype.rootTypes[i]}`); return []; } let sortedSearchResults = this.props.autocompleteSearch(translatedName, val); let autocompleteList = []; switch (curPrototype.rootTypes[i]) { case "component_pkid": for (let j = 0; j < sortedSearchResults.length; j++) { autocompleteList.push({ main: sortedSearchResults[j].data.productname, sub: sortedSearchResults[j].data.manufacturer, id: sortedSearchResults[j].index, }); } break; case 'mode_pkid': for (let j = 0; j < sortedSearchResults.length; j++) { autocompleteList.push({ main: sortedSearchResults[j].data.failname, sub: sortedSearchResults[j].data.code, id: sortedSearchResults[j].index, }); } break; default: } return autocompleteList; }} boxRevIndex={description.length - i} inputIsInvalid={this.state.inputIsInvalid[i]} inputSelectedId={this.state.inputFieldValues[i]} setInputInvalid={(val) => { let newInputIsInvalid = this.state.inputIsInvalid.slice(); newInputIsInvalid[i] = val; this.setState({ inputIsInvalid: newInputIsInvalid, }); }} setInputSelectedId={(val) => { let newInputFieldValues = this.state.inputFieldValues.slice(); newInputFieldValues[i] = val; let newAutocompleteInfo; let fetchedObject; switch (curPrototype.rootTypes[i]) { case "component_pkid": fetchedObject = this.props.fetchInfoByIndex('components', val); newAutocompleteInfo = { index: val, main: fetchedObject.productname, sub: fetchedObject.manufacturer, }; break; case "mode_pkid": fetchedObject = this.props.fetchInfoByIndex('modes', val); newAutocompleteInfo = { index: val, main: fetchedObject.failname, sub: fetchedObject.code, }; break; default: console.log(`Unrecognized root type ${curPrototype.rootTypes}`); } let newAutocompleteSelectedInfo = this.state.autocompleteSelectedInfo.slice(); newAutocompleteSelectedInfo[i] = newAutocompleteInfo; this.setState({ inputFieldValues: newInputFieldValues, autocompleteSelectedInfo: newAutocompleteSelectedInfo, }); }} selectedInfo={this.state.autocompleteSelectedInfo[i]} /> </div>, ); } else { addChildren.push( <div className="modal-addedit-row" key={`modal-addedit-row-${description[i]}`}> <div className="modal-addedit-row-label"> {description[i]} </div> <input className={`bordered-input-box${this.state.inputIsInvalid[i] ? ' bordered-input-box-invalid' : ''}`} type="text" value={this.state.inputFieldValues[i] === null ? '' : this.state.inputFieldValues[i]} onChange={(val) => { const newState = this.state.inputFieldValues.slice(); newState[i] = val.target.value; this.setState({ inputFieldValues: newState, }); }} onBlur={(e) => { const currentValue = e.target.value; const newInputIsInvalidState = this.state.inputIsInvalid.slice(); newInputIsInvalidState[i] = validateInput(currentValue, curPrototype.types[i], curPrototype.constraints[i]) !== ''; this.setState({ inputIsInvalid: newInputIsInvalidState, }); }} /> </div>, ); } } } let modalTitle; if (this.props.modalType === 'add') { modalTitle=`Add ${this.props.addItemDisplayTitle}`; } else { modalTitle=( <div> {`Edit ${this.props.additionalEditInfo.name}`} <div className="modal-edit-sub"> {this.props.additionalEditInfo.sub} </div> </div> ); } return ( <ModalShared show={this.props.show} modalBody={ [ <div id="addedit-modal-create-list" key="addedit-modal-main-list"> {addChildren} </div>, <div id="addedit-modal-error-message" key="addedit-modal-error-message">{ this.state.inputInvalidMessage }</div>, <div className="modal-buttons-container" key="modal-addedit-buttons-container"> <div className={`modal-buttons modal-${this.props.modalType === 'add' ? 'add' : 'edit'}-button`} onClick={() => { let encounteredError = false; let errorMessage = ''; const newInputIsInvalidState = Array(isRootDescribe ? curPrototype.rootDescribe.length : curPrototype.describe.length); for (let i = 0; i < curPrototype.describe.length; i++) { let validationResult; if (isRootDescribe) { validationResult = (this.state.inputFieldValues[i] === -1 ? 'Cannot be empty' : ''); } else { validationResult = validateInput(this.state.inputFieldValues[i], curPrototype.types[i], curPrototype.constraints[i]); } if (validationResult !== '' && !encounteredError) { encounteredError = true; errorMessage = `Invalid ${curPrototype.describe[i]}: ${validationResult}`; } newInputIsInvalidState[i] = (validationResult !== ''); } if (!encounteredError) { this.props.submitClicked(this.state.inputFieldValues); } this.setState({ inputIsInvalid: newInputIsInvalidState, inputInvalidMessage: errorMessage, }); }} > {this.props.modalType === 'add' ? 'Add' : 'Edit'} </div> <div className="modal-buttons modal-cancel-button" onClick={this.props.cancelClicked}> Cancel </div> </div>, ] } modalTitle={modalTitle} stylingId="addedit" /> ); } } AddEditModal.propTypes = { modalType: PropTypes.string.isRequired, show: PropTypes.bool.isRequired, objectPrototype: PropTypes.object.isRequired, addItemDisplayTitle: PropTypes.string.isRequired, submitClicked: PropTypes.func.isRequired, cancelClicked: PropTypes.func.isRequired, autocompleteSearch: PropTypes.func.isRequired, fetchInfoByIndex: PropTypes.func.isRequired, additionalEditInfo: PropTypes.object.isRequired, }; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import ModalShared from '../modal-shared/modalShared'; import '../modal-shared/modalShared.css'; import './deleteModal.css'; import './deleteModalColors.css'; export default function DeleteModal(props) { return ( <ModalShared show={props.show} modalBody={ [ <div className="modal-text" key="modal-delete-main-text">{ props.text }</div>, <div className="modal-buttons-container" key="modal-delete-buttons-container"> <div className="modal-buttons modal-delete-button" onClick={props.deleteClicked}> Delete </div> <div className="modal-buttons modal-cancel-button" onClick={props.cancelClicked}> Cancel </div> </div>, ] } modalTitle="Are you sure?" stylingId="delete" /> ); } DeleteModal.propTypes = { show: PropTypes.bool.isRequired, text: PropTypes.string.isRequired, deleteClicked: PropTypes.func.isRequired, cancelClicked: PropTypes.func.isRequired, }; <file_sep>export default class FailsData { constructor(dbid, failComponentId, failComponentName, failModeId, failModeName, failCode, failDescription) { this.dbid = dbid; this.failComponentId = failComponentId; this.failComponentName = failComponentName; this.failModeId = failModeId; this.failModeName = failModeName; this.failCode = failCode; this.failDescription = failDescription; } static get describe() { return ['Component', 'Fail Mode', 'Fail Code', 'Description']; } static get rootTypes() { return ['component_pkid', 'mode_pkid']; // this is kinda basic for now, add as things go on. built to be extendable } static get rootDescribe() { return ["Failed Component", "Fail Name"]; } getRootData() { return [this.failComponentId, this.failModeId]; } static get getIds() { return ['failedcomponent', 'failname', 'code', 'reason']; } static get types() { return ['string', 'string', 'string', 'string']; } getData() { return [this.failComponentName, this.failModeName, this.failCode, this.failDescription]; } } <file_sep># DataStructs ## .describe() Provides the title for the table ## .getIds() Provides identifiers for which things such as which column is currently being sorted is coded in and for deserializing data from the server ## .types() Provides type information. The sorter uses this and the add and edit modals also uses this for input validation. ### Valid Types: string, number will add as needed ## .constraints() Provides constraint information for the add and edit modals ## Valid arguments moreThan: number, lessThanOrEqualTo: number for numbers canBeEmpty: bool for any will add as needed <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import TableSeparator from './TableSeparator'; import { getIcon } from '../utils'; import './TableColors.css'; function TableHeaderItem(props) { return ( // parameters: what to display, my id, the currently being sorted id, which way its being sorted <th onMouseDown={(e) => { e.preventDefault(); props.handleHeaderClick(e.metaKey || e.altKey); }} className="TableHeaderTh" > <div className={`tableHeaderItem${props.highlight ? 'Highlighted' : 'Unhighlighted'}`}> <div className={props.greyOut ? 'tableHeaderItem-greyOut' : ''}>{ props.displayItem }</div> <div className={`tableHeaderSort${props.sortArrow!=='' ? '' : ' tableHeaderHidden'}`}> <img src={getIcon(props.sortArrow)} className="tableHeaderSort-icon" alt="Sorting Icon" /> </div> </div> </th> ); } TableHeaderItem.propTypes = { displayItem: PropTypes.string.isRequired, highlight: PropTypes.bool.isRequired, greyOut: PropTypes.bool.isRequired, sortArrow: PropTypes.string.isRequired, handleHeaderClick: PropTypes.func.isRequired, }; function TableHeader(props) { const headerData = props.headerData.constructor.describe.slice(); headerData.unshift('#'); const headerDataIds = props.headerData.constructor.getIds.slice(); headerDataIds.unshift('num'); const children = Array(headerData.length + 3); for (let i = 0; i < headerData.length; i++) { children[i] = React.createElement(TableHeaderItem, { displayItem: headerData[i], highlight: headerDataIds[i] === props.sortedColumn, greyOut: props.isInSearch && props.searchColumn !== headerDataIds[i], sortArrow: headerDataIds[i] === props.sortedColumn ? (props.sortMethodAscending ? 'DownArrow' : 'UpArrow') : '', handleHeaderClick: (cmdOrOptionHeld) => { props.handleHeaderClick(headerDataIds[i], cmdOrOptionHeld); }, key: `HeaderItem${headerDataIds[i]}`, }, null); } return React.createElement('tr', { id: 'TableHeader' }, children); } TableHeader.propTypes = { headerData: PropTypes.object.isRequired, sortedColumn: PropTypes.string.isRequired, sortMethodAscending: PropTypes.bool.isRequired, handleHeaderClick: PropTypes.func.isRequired, isInSearch: PropTypes.bool.isRequired, searchColumn: PropTypes.string.isRequired, }; function TableRow(props) { const { rowData } = props; const children = Array(rowData.length + 3); children[0] = <td key="num" className={(props.rowHighlighted ? 'TableRowHighlighted' : '')}>{props.rowNumber}</td>; for (let i = 1; i <= rowData.length; i++) { children[i] = ( <td key={props.rowIds[i - 1]} className={(props.rowHighlighted ? 'TableRowHighlighted' : '')}> {rowData[i - 1]} </td> ); } return ( <tr className="TableRow" onClick={(e) => { let typeOfAction = 'single'; if (e.shiftKey) { typeOfAction = 'range'; } else if (e.metaKey || e.altKey) { typeOfAction = 'multi'; } props.processClick(props.rowSelectIdentifier, typeOfAction); }} > {children} </tr> ); /* There are two parts to a rowSelectIdentifier. The type of table (Components, Failures, Modes, etc.) and the dbid (primary key) */ } TableRow.propTypes = { rowData: PropTypes.arrayOf(PropTypes.string).isRequired, rowHighlighted: PropTypes.bool.isRequired, rowNumber: PropTypes.number.isRequired, rowIds: PropTypes.arrayOf(PropTypes.string).isRequired, processClick: PropTypes.func.isRequired, rowSelectIdentifier: PropTypes.shape({ tableType: PropTypes.string, tableIndex: PropTypes.number, }).isRequired, }; export default function MainTable(props) { const tableData = props.displayData; const { displayLRange } = props; const { displayRRange } = props; const dataPrototype = props.tableDataPrototype; let tableElements = Array(Math.max((displayRRange-displayLRange) * 2 - 1, 0)); if (tableData.length > 0) { const tableMultiples = dataPrototype.getData().length; const tableIds = dataPrototype.constructor.getIds; for (let i = displayLRange; i < Math.min(displayRRange, tableData.length); i++) { tableElements[2 * i] = ( <TableRow rowIds={tableIds} rowData={tableData[i].getData()} rowNumber={tableData[i].num} key={`tableRow${props.tableType}${tableData[i].dbid}`} rowHighlighted={tableData[i].selected} rowSelectIdentifier={{ tableType: props.tableType, tableIndex: i, }} processClick={props.processClick} /> ); if (i !== Math.min(displayRRange, tableData.length) - 1) { tableElements[2 * i + 1] = <TableSeparator multiples={tableMultiples + 3} key={`tableSeparator${tableData[i].dbid}`} />; } } } else { tableElements = [ <tr key="NoDataTableTr"> <td id="NoData" colSpan={dataPrototype.getData().length + 1}> {props.isInSearch ? "No Results" : "No Data"} </td> </tr>, ]; } return ( <div id="tableContainer"> <div id="TableShadow" /> <table id="MainTable"> <thead> <TableHeader headerData={dataPrototype} sortedColumn={props.sortedColumn} sortMethodAscending={props.sortMethodAscending} handleHeaderClick={props.handleHeaderClick} isInSearch={props.isInSearch} searchColumn={props.searchColumn} /> </thead> <tbody> {tableElements} </tbody> </table> </div> ); } MainTable.propTypes = { displayData: PropTypes.arrayOf(PropTypes.object).isRequired, displayLRange: PropTypes.number.isRequired, displayRRange: PropTypes.number.isRequired, tableDataPrototype: PropTypes.object.isRequired, tableType: PropTypes.string.isRequired, processClick: PropTypes.func.isRequired, sortedColumn: PropTypes.string.isRequired, sortMethodAscending: PropTypes.bool.isRequired, handleHeaderClick: PropTypes.func.isRequired, isInSearch: PropTypes.bool.isRequired, searchColumn: PropTypes.string.isRequired, }; <file_sep>export default class ModesData { constructor(dbid, failname, code, description) { this.dbid = dbid; this.failname = failname; this.code = code; this.description = description; } static get describe() { return ['Fail Name', 'Fail Code', 'Description']; } static get getIds() { return ['name', 'code', 'description']; } static get types() { return ['string', 'string', 'string']; } static get constraints() { return [{ canBeEmpty: false }, { canBeEmpty: false }, { canBeEmpty: false }]; } getData() { return [this.failname, this.code, this.description]; } } <file_sep>// eslint-disable-next-line import/prefer-default-export export const rootURL = 'http://127.0.0.1:5000'; // eslint-disable-next-line import/prefer-default-export export const eachPage = 15;
03f21af4320ebf4647e16b79e93a15ca6e8922a8
[ "JavaScript", "Markdown" ]
16
JavaScript
LegitMichel777/tesladata
0d479e691daa5d05d4c61d086732f70927d01216
90e95a838065cf774eaed8349ba06c331d382275
refs/heads/main
<repo_name>AmilaDissanayake/PythonCal<file_sep>/main.py import math def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def factorial(x): return 1 if (x == 1 or x == 0) else x * factorial(x - 1); print("Select operation -") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") print("5.Factorial") print("6.Sin") print("7.Cos") print("8.Tan") print("9.Square root") print("10.Power of a number") print("11.Logarithm Value") print("12.Natural logarithm") while True: choice = input("Enter choice(1/2/3...): ") if choice in ('1', '2', '3', '4', '10'): val1 = float(input("Enter first number: ")) val2 = float(input("Enter second number: ")) if choice == '1': print(val1, "+", val2, "=", add(val1, val2)) elif choice == '2': print(val1, "-", val2, "=", subtract(val1, val2)) elif choice == '3': print(val1, "*", val2, "=", multiply(val1, val2)) elif choice == '4': print(val1, "/", val2, "=", divide(val1, val2)) elif choice == '10': print(val1, "^", val2, "=", val1**val2) next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break elif choice in ('5', '6', '7', '8', '9', '12'): val1 = float(input("Enter number: ")) if choice == '5': print('Factorial of',val1,"is", factorial(val1)) elif choice == '6': print('Sin value of',val1,'is', math.sin(val1)) elif choice == '7': print('Cos value of',val1,'is', math.cos(val1)) elif choice == '8': print('Tan value of',val1,'is', math.tan(val1)) elif choice == '9': print('Square root of',val1,'is', math.sqrt(val1)) elif choice == '12': print('Natural logarithm of',val1,'is', math.log(val1)) next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break elif choice in ('11'): val1 = float(input("Enter Base: ")) val2 = float(input("Enter number: ")) print("Logarithm base",val1,"of",val2,"is", math.log(val2,val1)) next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break else: print("Invalid Input")
57fffe20e4f53b45e87e324e065b3aac1a32d2e1
[ "Python" ]
1
Python
AmilaDissanayake/PythonCal
0a44d8fd73b0a6e7b5199a983eea973527d12a78
34f888440caf3ddabd93cad0dbf177e194602142
refs/heads/master
<repo_name>fmontoy/web-components-bc<file_sep>/help.md # Card Styles ``` .todos-li { border: 2px dashed white; height: 200px; list-style-type: none; padding: 15px; width: 250px; position: relative; background-image: repeating-linear-gradient(-24deg, transparent, transparent 4px, white 0, white 5px); } .card { position: absolute; transform: translate(10px, 10px); background-color: white; height: 200px; width: 260px; padding: 10px; } .card-title { font-weight: bold; font-size: 32px; } .card-bottom { position: absolute; bottom: 0; left: 0; height: 40px; width: 260px; padding: 0 10px; display: flex; justify-content: space-between; border-top: 2px dashed black; align-items: center; } ``` # Card HTML ``` <li class="todos-li"> <div class="card"> <h2 class="card-title">Title</h2> <div class="card-bottom"> <a href="" class="article-link">Go to article</a> <input type="checkbox" /> </div> </div> </li> ``` <file_sep>/src/components/Article.js class Article extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.render(); } render = () => { this.readed = this.attributes.readed.value == 'true'; this.id = this.attributes.id.value; this.shadowRoot.innerHTML = ` <style> a { color: black; text-decoration: none; } .todos-li { border: 2px dashed white; height: 200px; list-style-type: none; padding: 15px; width: 250px; position: relative; background-image: repeating-linear-gradient(-24deg, transparent, transparent 4px, white 0, white 5px); } .card { position: absolute; transform: translate(10px, 10px); background-color: white; height: 200px; width: 260px; padding: 10px; } .card-title { font-weight: bold; font-size: 32px; } .card--checked { background-color: #E0B64B; } .card-bottom { position: absolute; bottom: 0; left: 0; height: 40px; width: 260px; padding: 0 10px; display: flex; justify-content: space-between; border-top: 2px dashed black; align-items: center; } </style> <div class="todos-li"> <div class="card"> <h2 class="card-title">${this.attributes.title.value}</h2> <div class="card-bottom"> <a href="${this.attributes.url.value}" target="_blank" class="article-link">Go to article</a> <input type="checkbox" class="checkbox-readed"/> </div> </div> </div> `; this.setChecked(); }; setChecked = () => { this.checkbox = this.shadowRoot.querySelector('.checkbox-readed'); this.checkbox.checked = this.readed; this.checkbox.addEventListener('change', this.setColor); if (this.checkbox.checked) { this.checkbox.parentElement.parentElement.classList.add('card--checked'); } }; setColor = () => { this.dispatchEvent(new CustomEvent('article-changed', { detail: { id: Number(this.id), checked: this.checkbox.checked }, bubbles: true })) this.checkbox.parentElement.parentElement.classList.toggle('card--checked'); }; } customElements.define('article-item', Article); export default Article;
f3982e569977abbcbc639b6b6acce726dfaff2c6
[ "Markdown", "JavaScript" ]
2
Markdown
fmontoy/web-components-bc
c4b7aaf47d06e9c33ad7ca388884b66c340b3ebf
52fa9458124020aabf30c5d0f6b9cde7f2c5fc60
refs/heads/main
<file_sep>using System; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IServiceRepository : IRepository<DataModels.Services> { DataModels.Services GetServiceById(Guid serviceGuid); } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class AppointmentsService { private IAppointmentRepository appointmentRepository; public AppointmentsService(IAppointmentRepository appointmentRepository) { this.appointmentRepository = appointmentRepository; } public Appointment GetAppointmentById(string appointmentId) { Guid appointmentGuid = Guid.Empty; if (!Guid.TryParse(appointmentId, out appointmentGuid)) throw new Exception("Invalid guid format"); var appointment = appointmentRepository.GetAppointmentById(appointmentGuid); if (appointment == null) throw new EntityNotFoundException(appointmentGuid); return appointment; } } } <file_sep>using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IDoctorsRepository : IRepository<Doctor> { Doctor GetDoctorById(Guid id); } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class ClinicsServicesService { private IClinicServiceRepository clinicserviceRepository; public ClinicsServicesService(IClinicServiceRepository clinicserviceRepository) { this.clinicserviceRepository = clinicserviceRepository; } public ClinicServices GetClinicServiceById(string clinicserviceId) { Guid clinicserviceGuid = Guid.Empty; if (!Guid.TryParse(clinicserviceId, out clinicserviceGuid)) throw new Exception("Invalid guid format"); var clinicservice = clinicserviceRepository.GetServicesByClinicId(clinicserviceGuid); if (clinicservice == null) throw new EntityNotFoundException(clinicserviceGuid); return (ClinicServices)clinicservice; } } } <file_sep>using System; using Microsoft.EntityFrameworkCore.Migrations; namespace ShiningLight.DataAccess.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Services", columns: table => new { ID = table.Column<Guid>(nullable: false), Price = table.Column<decimal>(nullable: false), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Services", x => x.ID); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { ID = table.Column<Guid>(nullable: false), Name = table.Column<string>(nullable: true), Password = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.ID); }); migrationBuilder.CreateTable( name: "Invoices", columns: table => new { ID = table.Column<Guid>(nullable: false), UserID = table.Column<Guid>(nullable: true), Price = table.Column<decimal>(nullable: false), PaymentMethod = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Invoices", x => x.ID); table.ForeignKey( name: "FK_Invoices_Users_UserID", column: x => x.UserID, principalTable: "Users", principalColumn: "ID", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Clinics", columns: table => new { ID = table.Column<Guid>(nullable: false), AppointmentID = table.Column<Guid>(nullable: true), Address = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Clinics", x => x.ID); }); migrationBuilder.CreateTable( name: "ClinicsServices", columns: table => new { ID = table.Column<Guid>(nullable: false), ServicesID = table.Column<Guid>(nullable: false), ClinicID = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClinicsServices", x => x.ID); table.ForeignKey( name: "FK_ClinicsServices_Clinics_ClinicID", column: x => x.ClinicID, principalTable: "Clinics", principalColumn: "ID", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_ClinicsServices_Services_ServicesID", column: x => x.ServicesID, principalTable: "Services", principalColumn: "ID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Doctors", columns: table => new { ID = table.Column<Guid>(nullable: false), ClinicID = table.Column<Guid>(nullable: true), Name = table.Column<string>(nullable: true), Qualification = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Doctors", x => x.ID); table.ForeignKey( name: "FK_Doctors_Clinics_ClinicID", column: x => x.ClinicID, principalTable: "Clinics", principalColumn: "ID", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Appointments", columns: table => new { ID = table.Column<Guid>(nullable: false), UserID = table.Column<Guid>(nullable: true), DoctorsID = table.Column<Guid>(nullable: true), Type = table.Column<string>(nullable: true), Prices = table.Column<decimal>(nullable: false), ClinicID = table.Column<Guid>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Appointments", x => x.ID); table.ForeignKey( name: "FK_Appointments_Clinics_ClinicID", column: x => x.ClinicID, principalTable: "Clinics", principalColumn: "ID", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Appointments_Doctors_DoctorsID", column: x => x.DoctorsID, principalTable: "Doctors", principalColumn: "ID", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Appointments_Users_UserID", column: x => x.UserID, principalTable: "Users", principalColumn: "ID", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Appointments_ClinicID", table: "Appointments", column: "ClinicID"); migrationBuilder.CreateIndex( name: "IX_Appointments_DoctorsID", table: "Appointments", column: "DoctorsID"); migrationBuilder.CreateIndex( name: "IX_Appointments_UserID", table: "Appointments", column: "UserID"); migrationBuilder.CreateIndex( name: "IX_Clinics_AppointmentID", table: "Clinics", column: "AppointmentID"); migrationBuilder.CreateIndex( name: "IX_ClinicsServices_ClinicID", table: "ClinicsServices", column: "ClinicID"); migrationBuilder.CreateIndex( name: "IX_ClinicsServices_ServicesID", table: "ClinicsServices", column: "ServicesID"); migrationBuilder.CreateIndex( name: "IX_Doctors_ClinicID", table: "Doctors", column: "ClinicID"); migrationBuilder.CreateIndex( name: "IX_Invoices_UserID", table: "Invoices", column: "UserID"); migrationBuilder.AddForeignKey( name: "FK_Clinics_Appointments_AppointmentID", table: "Clinics", column: "AppointmentID", principalTable: "Appointments", principalColumn: "ID", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Appointments_Clinics_ClinicID", table: "Appointments"); migrationBuilder.DropForeignKey( name: "FK_Doctors_Clinics_ClinicID", table: "Doctors"); migrationBuilder.DropTable( name: "ClinicsServices"); migrationBuilder.DropTable( name: "Invoices"); migrationBuilder.DropTable( name: "Services"); migrationBuilder.DropTable( name: "Clinics"); migrationBuilder.DropTable( name: "Appointments"); migrationBuilder.DropTable( name: "Doctors"); migrationBuilder.DropTable( name: "Users"); } } } <file_sep>using Microsoft.EntityFrameworkCore; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Text; namespace ShiningLight.DataAccess { public class ShiningLightDBContext : DbContext { public ShiningLightDBContext (DbContextOptions<ShiningLightDBContext> options): base(options) { } public DbSet<Appointment> Appointments { get; set; } public DbSet<Clinic> Clinics { get; set; } public DbSet<ClinicServices> ClinicsServices { get; set; } public DbSet<Services> Services { get; set; } public DbSet<Doctor> Doctors { get; set; } public DbSet<Invoice> Invoices { get; set; } public DbSet<User> Users { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class Services { public Guid ID { get; set; } public decimal Price { get; set; } public string Name { get; set; } public ICollection<ClinicServices> ClientServices { get; set; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class BaseRepository <T> : IRepository<T> where T : class,new() { protected readonly ShiningLightDBContext dbContext; public BaseRepository(ShiningLightDBContext dbContext) { this.dbContext = dbContext; } public T Add(T item) { var entity = dbContext.Add<T>(item); dbContext.SaveChanges(); return entity.Entity; } public bool Delete(T item) { dbContext.Remove<T>(item); dbContext.SaveChanges(); return true; } public IEnumerable<T> GetAll() { return dbContext.Set<T>() .AsEnumerable(); } public T Update(T item) { var entity = dbContext.Update<T>(item); dbContext.SaveChanges(); return entity.Entity; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class Invoice { public Guid ID { get; set; } public User User { get; set; } public decimal Price { get; set; } public string PaymentMethod { get; set; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class ServicesRepository : BaseRepository<Services>, IServiceRepository { public ServicesRepository(ShiningLightDBContext dbContext) : base(dbContext) { } public Services GetServiceById(Guid serviceGuid) { return dbContext.Services.Where(service => service.ID == serviceGuid).SingleOrDefault(); } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class UsersRepository : BaseRepository<User>, IUserRepository { public UsersRepository(ShiningLightDBContext dbContext) : base(dbContext) { } public User GetUserById(Guid userGuid) { return dbContext.Users.Where(user => user.ID == userGuid).SingleOrDefault(); } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class UsersService { private IUserRepository userRepository; public UsersService(IUserRepository userRepository) { this.userRepository = userRepository; } public User GetUserById(string userId) { Guid userGuid = Guid.Empty; if (!Guid.TryParse(userId, out userGuid)) throw new Exception("Invalid guid format"); var user = userRepository.GetUserById(userGuid); if (user == null) throw new EntityNotFoundException(userGuid); return user; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class InvoicesService { private IInvoiceRepository invoiceRepository; public InvoicesService(IInvoiceRepository invoiceRepository) { this.invoiceRepository = invoiceRepository; } public Invoice GetInvoiceById(string invoiceId) { Guid invoiceGuid = Guid.Empty; if (!Guid.TryParse(invoiceId, out invoiceGuid)) throw new Exception("Invalid guid format"); var invoice = invoiceRepository.GetInvoicesById(invoiceGuid); if (invoice == null) throw new EntityNotFoundException(invoiceGuid); return invoice; } } } <file_sep>using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IUserRepository : IRepository<User> { User GetUserById(Guid id); } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class DoctorsService { private IDoctorsRepository doctorRepository; public DoctorsService(IDoctorsRepository doctorRepository) { this.doctorRepository = doctorRepository; } public Doctor GetDoctorById(string doctorId) { Guid doctorGuid = Guid.Empty; if (!Guid.TryParse(doctorId, out doctorGuid)) throw new Exception("Invalid guid format"); var doctor = doctorRepository.GetDoctorById(doctorGuid); if (doctor == null) throw new EntityNotFoundException(doctorGuid); return doctor; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class Appointment { public Guid ID { get; set; } public User User { get; set; } public Doctor Doctors { get; set; } public string Type { get; set; } public decimal Prices { get; set; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class ClinicRepository : BaseRepository<Clinic>, IClinicRepository { public ClinicRepository(ShiningLightDBContext dbContext) : base(dbContext) { } public Clinic GetClinicById(Guid id) { return dbContext.Clinics .Where(clinic => clinic.ID == id) .SingleOrDefault(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class ClinicServices { public Guid ID { get; set; } public Guid ServicesID { get; set; } public Guid ClinicID { get; set; } public Services Services { get; set; } public Clinic Clinic { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class Doctor { public Guid ID { get; set; } public Clinic Clinic { get; set; } public string Name { get; set; } public string Qualification { get; set; } public ICollection<Appointment> Appointments { get; set; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class ServicesService { private IServiceRepository serviceRepository; public ServicesService(IServiceRepository serviceRepository) { this.serviceRepository = serviceRepository; } public DataModels.Services GetServiceById(string serviceId) { Guid serviceGuid = Guid.Empty; if (!Guid.TryParse(serviceId, out serviceGuid)) throw new Exception("Invalid guid format"); var service = serviceRepository.GetServiceById(serviceGuid); if (service == null) throw new EntityNotFoundException(serviceGuid); return service; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class AppointmentRepository : BaseRepository <Appointment>, IAppointmentRepository { public AppointmentRepository(ShiningLightDBContext dbContext): base(dbContext) { } public Appointment GetAppointmentById(Guid id) { return dbContext.Appointments .Where(appointment => appointment.ID == id) .SingleOrDefault(); } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class DoctorRepository : BaseRepository<Doctor>, IDoctorsRepository { public DoctorRepository(ShiningLightDBContext dbContext) : base(dbContext) { } public Doctor GetDoctorById(Guid id) { return dbContext.Doctors.Where(doctor => doctor.ID == id).SingleOrDefault(); } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using ShinigLight.ApplicationLogic.Exceptions; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Services { public class ClinicsService { private IClinicRepository clinicRepository; public ClinicsService(IClinicRepository clinicRepository) { this.clinicRepository = clinicRepository; } public Clinic GetClinicById(string clinicId) { Guid clinicGuid = Guid.Empty; if (!Guid.TryParse(clinicId, out clinicGuid)) throw new Exception("Invalid guid format"); var clinic = clinicRepository.GetClinicById(clinicGuid); if (clinic == null) throw new EntityNotFoundException(clinicGuid); return clinic; } } } <file_sep># ShiningLight Detist website <file_sep>using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IClinicServiceRepository : IRepository<ClinicServices> { IEnumerable<ClinicServices> GetServicesByClinicId(Guid clinicId); } } <file_sep>using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IClinicRepository : IRepository<Clinic> { Clinic GetClinicById(Guid id); } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class Clinic { public Guid ID { get; set; } public Appointment Appointment { get; set; } public string Address { get; set; } public ICollection<Appointment> Appointments { get; set; } public ICollection<ClinicServices> Client_Services { get; set; } public ICollection<Doctor> Doctors { get; set; } } } <file_sep>using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IInvoiceRepository : IRepository<Invoice> { Invoice GetInvoicesById(Guid id); } } <file_sep>using ShinigLight.ApplicationLogic.DataModels; using System; namespace ShinigLight.ApplicationLogic.Abstractions { public interface IAppointmentRepository : IRepository<Appointment> { Appointment GetAppointmentById(Guid id); } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShinigLight.ApplicationLogic.DataModels { public class User { public Guid ID { get; set; } public string Name { get; set; } public string Password { get; set; } public string Email { get; set; } public ICollection<Appointment> Appointments { get; set; } public ICollection<Invoice> Invoices { get; set; } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class InvoicesRepository : BaseRepository<Invoice>, IInvoiceRepository { public InvoicesRepository(ShiningLightDBContext dbContext) : base(dbContext) { } public Invoice GetInvoicesById(Guid id) { return dbContext.Invoices.Where(invoice => invoice.ID == id).SingleOrDefault(); } } } <file_sep>using ShinigLight.ApplicationLogic.Abstractions; using ShinigLight.ApplicationLogic.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShiningLight.DataAccess { public class ClinicServicesRepository : BaseRepository<ClinicServices>, IClinicServiceRepository { public ClinicServicesRepository(ShiningLightDBContext dbContext) : base(dbContext) { } public IEnumerable<ClinicServices> GetServicesByClinicId(Guid clinicId) { return dbContext.ClinicsServices .Where(clinicServices => clinicServices.ClinicID == clinicId) .AsEnumerable(); } } }
56b7de060e066a561559961ac9b1fc21cfa20659
[ "Markdown", "C#" ]
32
C#
bombecuhidrogen/ShiningLight
41ef4da1f3738e1adfff6b58239a8fa303fe3505
c0dad7e6a4f47b421e6570c450afecdea53b088f
refs/heads/master
<file_sep>""" Main entry point for service """ from flask import Flask, jsonify, request from Util import database_upload, local_upload, print_to_screen app = Flask(__name__) app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True @app.route("/") def root(): return jsonify({ "message": "welcome to my file microservice", "author": "<NAME>", "company": "availity" }), 200 @app.route("/add-file", methods=["POST"]) def file_intake(): data = dict() provider_codes = { "provider1" : "database", "provider2" : "local", "provider3" : "print" } files = request.files provider_type = request.args.get("provider") if len(files) == 0: return jsonify({"error": "files not found"}), 404 print() print("Thank you for the files.") print("Provider type of", provider_type) for f in files: data[f] = request.files[f] if provider_type == "provider1": database_upload(data) if provider_type == "provider2": local_upload(data) if provider_type == "provider3": print_to_screen(data) return jsonify({"type": provider_codes[provider_type]}), 200 if __name__ == "__main__": app.run(debug=False, use_reloader=True)<file_sep>""" Utility for saving files """ import os from tinydb import TinyDB, Query from flask import jsonify def database_upload(data): db = TinyDB("db.json") for d in data: db.insert({ d: data[d].read().decode("latin-1") }) print() print("Files uploaded to database.") def local_upload(data): current_path = os.path.dirname(os.path.abspath(__file__)) location = current_path + "/local_storage/" for d in data: save_location = location + d with open(save_location, 'w') as f: f.write(data[d].read().decode("latin-1")) print() print("Files saved to local storage.") def print_to_screen(data): print() print("Printing data to screen...") for d in data: print("File:", d) print("Data:\n", data[d].read().decode("latin-1"))<file_sep>## File microservice Python 3. Used Flask for the API and TinyDB for the database - for a lightweight architecture. "Write an app in your programming language of choice that takes as input a list of files and a provider parameter. Depending on the provider parameter either write the files to a database, the file system, or print the files to console or popup window. The parameter values are “provider1” for database, “provider2” for file system, “provider3” for console/popup." #### Install To install dependecies, make sure pip is installed and run the following command. ```pip install requirements.txt``` #### Run the app To run, use the following command. ``` $ python app.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat ``` Use the url to test locally. http://127.0.0.1:5000/ To test, use the provider parameters below in the request URL. Use a header of Content-Type=multipart/form-data Attach files to the body of your request as formdata. Example of the files in the body of request, in Postman. <img src="postman.png" /> - Database ``` http://1172.16.31.10:5000/add-file?provider=provider1 ``` - Local ``` http://127.0.0.1:5000/add-file?provider=provider2 ``` - Print ``` http://127.0.0.1:5000/add-file?provider=provider3 ```
746913e1db089b4128aecec7fc1d9d10a44f96ec
[ "Markdown", "Python" ]
3
Python
navonf/availity-challenge
988ee5997d585bcd4fb063a2668cb7b9c9030602
81714356b7a9916b97cf6af5733e70434158aeff
refs/heads/main
<file_sep>cmake_minimum_required(VERSION 3.0.0) project(ast-bcrypt VERSION 0.1.0) # specify the C++ standard set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) include(CTest) enable_testing() add_executable(ast-bcrypt main.cpp) target_link_libraries (${PROJECT_NAME} -lbcrypt) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) <file_sep>#include "bcrypt/BCrypt.hpp" #include <iostream> #include <vector> #include <utility> int main(int, char**) { std::cout << "Testing libbcrypt." << std::endl; std::vector<std::pair<std::string, std::string>> testPasswordsAndHashesVector; testPasswordsAndHashesVector.push_back({"abc", "$2a$10$8iRRL3xhamstsVQayC04aeO1NRZ0Hm4ycv2S5qgMtDV3SxCy8/qPK"}); testPasswordsAndHashesVector.push_back({"superStrongPass", "$2a$10$2CowvhDtaXQWzt6Ia4Dv.Or3Mv7gjTbOW2kZcXdB/p2Oj92mYI47e"}); testPasswordsAndHashesVector.push_back({"cba", "$2a$10$vg8Z3MaVd/Yy2bzOcn/HYeWaY78K5c3jo8NVsri1i1UqyLOzNzIJm"}); testPasswordsAndHashesVector.push_back({"dasd'dasd!@", "$2a$10$VlLE1pXWuFI6i0YDJPD.tuJ9Qb5fqFjja3r9xto650qtU10/i2Y/K"}); testPasswordsAndHashesVector.push_back({"sdasd1WS)SD<KI*@", "$2a$10$HK25GYXyedcnb9XV8uv1EegRVKHaL/luF16/PbwrgnX96CAHH5uce"}); testPasswordsAndHashesVector.push_back({"sdasd1WS)SD<KI*@", "$2a$10$HK25GYXyedcnb9XV8uv1EegRVKHaL/lu666/PbwrgnX16CAHH5555"}); //WRONG HASH FOR TEST std::cout << "password ----- generated hash ----- check gen hash " << std::endl << " ----- test hash ----- check test hash" << std::endl; std::vector<std::string> generatedHashes; int numberOfHashingPasses = 10; //same as jbcrypt, increase for complexity, must be in range 4 - 30 for(auto testPassAndHash : testPasswordsAndHashesVector) { std::string hash = BCrypt::generateHash(testPassAndHash.first, numberOfHashingPasses); BCrypt::validatePassword(testPassAndHash.first, testPassAndHash.second); std::cout << testPassAndHash.first << " ----- " << hash << std::endl << " ----- " << BCrypt::validatePassword(testPassAndHash.first, hash) << " ----- " << testPassAndHash.second << " ----- " << BCrypt::validatePassword(testPassAndHash.first, testPassAndHash.second) << std::endl; } } <file_sep># bcrypt ## Prerequsites Build and install https://github.com/trusch/libbcrypt
e7a587bec43b1957fb74a0496ef1372b29684d3e
[ "Markdown", "CMake", "C++" ]
3
CMake
astepanov83/bcrypt
f39d2ad3835b060f718b402b3a9bf129fa26e3ec
a043071a50098ae3538887aebdff3051c4b2d8dd
refs/heads/master
<file_sep>import unittest from common import HTMLTestRunner_cn pathCase = 'D:\\all_test_dir\\my_test_for_web_1\\case' rule = 'test*.py' discover = unittest.defaultTestLoader.discover(start_dir=pathCase,pattern=rule) print(discover) report = "D:\\all_test_dir\\my_test_for_web_1\\report\\"+'report.html' fp = open(report,'wb') runner = HTMLTestRunner_cn.HTMLTestRunner(stream=fp,title='我日报告',description='好了吧秒速') runner.run(discover) <file_sep># coding:utf-8 from time import sleep from pykeyboard import PyKeyboard from selenium import webdriver from pages.login_page import LoginPage driver = webdriver.Firefox() a = LoginPage(driver) a.login() driver.get('https://leisongwei.5upm.com/bug-create-1-0-moduleID=0.html') sleep(2) # 点击上传图片文件 driver.find_element_by_css_selector('.ke-toolbar-icon.ke-toolbar-icon-url.ke-icon-image').click() sleep(2) # 点击本地上传 driver.find_element_by_xpath('/html/body/div[3]/div[1]/div[2]/div/div[1]/ul/li[2]').click() # 点击浏览 driver.find_element_by_css_selector('.ke-inline-block.ke-upload-button').click() k = PyKeyboard() s = r"‪C:\users\administrator\desktop\11.txt" for i in s: k.tap_key(i) sleep(1) k.tap_key(k.enter_key) <file_sep># coding: utf-8 from time import sleep import time from selenium import webdriver from case.login_zentao import Login from base.base import Base class AddBug(Base): loc_test = ('css selector', '#navbar>.nav.nav-default>li:nth-child(4)>a') loc_bug = ('css selector', '[data-id="bug"]>a') loc_add_bug = ('css selector', '.btn.btn-primary>.icon.icon-plus') loc_version = ('css selector', '#openedBuild_chosen>.chosen-choices') loc_version_add = ('css selector', '.active-result') loc_title = ('id', 'title') # 需要切换iframe loc_body = ('class name', 'article-content') loc_submit = ('id', 'submit') # loc_bug_name = ('xpath', "/html/body/main/div/div[3]/div[2]/form/div[2]/table/tbody/tr[1]/td[5]/span") loc_bug_name1 = ('xpath', "/html/body/main/div/div[3]/div[2]/form/div[2]/table/tbody/tr[1]/td[3]/a") def add_bug(self, title='title'): self.click(self.loc_test) self.click(self.loc_bug) self.click(self.loc_add_bug) self.click(self.loc_version) self.click(self.loc_version_add) self.sendText(self.loc_title, title) sleep(2) self.driver.switch_to.frame(1) self.sendText(self.loc_body, '一二三呢女') self.driver.switch_to.default_content() self.click(self.loc_submit) def is_add_success(self, title): # a = self.findElement(self.loc_bug_name).get_attribute('class') # b = self.findElement(self.loc_bug_name).text # a1 = self.findElement(self.loc_bug_name1).get_attribute('class') b1 = self.findElement(self.loc_bug_name1).text print(b1) # print(a, b) # print(a1,b1) if title == b1: return True else: return False if __name__ == '__main__': profile_directory=r'C:\Users\Administrator\AppData\Roaming\Mozilla\Firefox\Profiles\s6qtifzn.default' profile = webdriver.FirefoxProfile(profile_directory) driver = webdriver.Firefox() driver.get('https://leisongwei.5upm.com/user-login-Lw==.html') LOGIN = Login(driver) LOGIN.login() a = AddBug(driver) strTime = time.strftime('%Y_%m_%d_%H_%M_%S') title = '测试bug' + strTime a.add_bug(title) sleep(2) b =a.is_add_success(title) print(b) <file_sep># coding:utf-8 from time import sleep from selenium import webdriver profile_directory = r'C:\Users\Administrator\AppData\Roaming\Mozilla\Firefox\Profiles\s6qtifzn.default' profile = webdriver.FirefoxProfile(profile_directory) driver = webdriver.Firefox(profile) # driver.get('https://mail.126.com/') # myframe = driver.find_element_by_css_selector(3) # driver.switch_to.frame(2) # driver.find_element_by_css_selector('.j-inputtext.dlemail').send_keys('123456') # driver.switch_to.default_content() # print(driver.title) # try: # sleep(2) # driver.find_element_by_partial_link_text('你的专业电子邮局') # print(driver.title) # except: # driver.quit() driver.get('http://bj.ganji.com/') driver.find_element_by_css_selector('.tab-category:nth-child(7) .dd>a:nth-child(1)').click() all_handle = driver.window_handles print(all_handle) driver.close() driver.switch_to.window(all_handle[1]) a = driver.title print(a) <file_sep>from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys # driver = webdriver.Firefox() # driver.get('http://www.baidu.com') # driver.find_element_by_xpath('//*[@class="s_ipt"]').send_keys('百度一下。你就知道') # driver.find_element_by_id('su').click() # mouse = driver.find_element_by_link_text('设置') # print(mouse) # ActionChains(driver).move_to_element(mouse).perform() # sleep(2) # driver.find_element_by_css_selector('.setpref') # sleep(2) # driver.find_element_by_css_selector('#kw').send_keys('我爱你M') # sleep(2) # driver.find_element_by_css_selector('#kw').send_keys(Keys.BACK_SPACE) # sleep(2) # driver.find_element_by_css_selector('#kw').send_keys('琉璃神社') # sleep(2) # driver.find_element_by_css_selector('#kw').send_keys(Keys.CONTROL, 'a') # driver.find_element_by_css_selector('#kw').send_keys(Keys.CONTROL, 'c') # sleep(2) # driver.find_element_by_css_selector('#kw').clear() # sleep(2) # driver.find_element_by_css_selector('#kw').send_keys(Keys.CONTROL, 'v') # sleep(1) # driver.find_element_by_css_selector('#kw').send_keys(Keys.ENTER) # sleep(2) # driver.quit() # 乘法口诀 for i in range(1,10): for j in range(1,10): if j>i : pass else: print("%d*%d=%d" % (i,j,i*j), end=' ') print('') for i in range(1,10): for j in range(1,i+1): print("%d*%d=%2d" % (i,j,i*j),end=" ") print(" ") # 水仙数字 for i in range(100,1000): a = i//100 b = i % 100//10 c = i % 10 if i == pow(a, 3)+pow(b, 3)+pow(c, 3): print(i) <file_sep>from selenium import webdriver driver = webdriver.Firefox() driver.get('https://kyfw.12306.cn/otn/index/init') js = ''' document.getElementById('train_date').value='2137-12'; document.getElementById('fromStationText').value='01-17-12'; document.getElementById('search_one').click() ''' driver.execute_script(js)<file_sep>#-*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait class Base(): def __init__(self, driver:webdriver.Firefox): self.driver = driver self.timeout = 10 self.t = 0.5 def findElement(self, loctor): ele = WebDriverWait(self.driver, self.timeout, self.t).until(lambda x: x.find_element(*loctor)) return ele def click(self, locator): self.findElement(locator).click() def sendText(self, locator, text): self.findElement(locator).send_keys(text) def is_alert(self): try: return self.driver.switch_to.alert except: return False def is_alert_new(self): try: return WebDriverWait(self.driver, self.timeout, self.t).until(EC.alert_is_present) except: return False def get_text(self, locator): try: a = self.findElement(locator).text print('获取文本成功,返回文本:%s' % a) return a except: print('获取文本失败,返回空') return '' if __name__ == '__main__': driver = webdriver.Firefox() driver.get('https://leisongwei.5upm.com/my/') a = Base(driver) loc1 = (By.ID, 'account') a.sendText(loc1,'admin') loc2=('id', 'submit') a.click(loc2) <file_sep># coding: utf-8 from time import sleep import time from selenium import webdriver from case.add_bug_zentao import AddBug import unittest from case.login_zentao import Login class TestAddBug(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.get('https://leisongwei.5upm.com/my/') self.a = Login(self.driver) self.a.login() self.b = AddBug(self.driver) def test1(self): str = time.strftime('%Y_%m_%d_%H_%M_%S') title = '标题'+str self.b.add_bug(title) sleep(2) a = self.b.is_add_success(title) self.assertTrue(a) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()<file_sep> def login(driver,user='admin123',password='<PASSWORD>'): driver.find_element_by_id('account').send_keys(user) driver.find_element_by_name('password').send_keys(<PASSWORD>) driver.find_element_by_id('submit').click()<file_sep>import unittest class CeShiEqual(unittest.TestCase): def test01(self): self.a = 3 self.b = 3 self.assertTrue(self.a == self.b) if __name__ == '__main__': unittest.main()<file_sep>from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.support.select import Select driver = webdriver.Firefox() driver.get('http://www.baidu.com') mouse = driver.find_element_by_css_selector("#u1 [name = 'tj_settingicon']") ActionChains(driver).move_to_element(mouse).perform() driver.find_element_by_css_selector('.setpref').click() sleep(1) driver.find_element_by_css_selector('#nr').find_element_by_css_selector("option[value='50']").click() driver.find_element_by_id('nr').click() sleep(2) driver.find_element_by_css_selector('#nr').find_element_by_css_selector("option[value='20']").click() driver.find_element_by_id('nr').click() sleep(2) driver.find_element_by_css_selector('.prefpanelgo').click() a = driver.switch_to.alert a.accept() sleep(3) driver.quit() <file_sep>#-*- coding: utf-8 -*- from time import sleep from selenium import webdriver class Login(): def __init__(self, driver): self.driver = driver def login(self, user='admin123', password='<PASSWORD>'): self.driver.find_element_by_id('account').send_keys(user) self.driver.find_element_by_name('password').send_keys(<PASSWORD>) self.driver.find_element_by_id('submit').click() def is_alert(self): try: sleep(2) self.driver.switch_to.alert.accept() except: return '' def get_user_name(self): try: a = self.driver.find_element_by_css_selector('.user-name').text return a except: return '' def is_login_success(self): try: a = self.driver.find_element_by_css_selector('.user-name').text print("登录成功,账号:%s" % a) return a except: print('没有登录成功') return '' if __name__ == '__main__': driver = webdriver.Firefox() driver.get('https://leisongwei.5upm.com/user-login-Lw==.html') a = Login(driver) a.login() a.is_login_success() a.is_alert()<file_sep>import ddt from time import sleep import xlrd from selenium import webdriver import unittest from pages.login_page import LoginPage from common.read_excel import ExcelUtil path = xlrd .open_workbook('D:\\all_test_dir\\my_test_for_web_1\\common\\databases.xls') datas = ExcelUtil(path) testdatas = datas.dict_data() @ddt.ddt class Test_login(unittest.TestCase): def login_case(self, user, password, expect): self.login.send_user(user) self.login.send_password(<PASSWORD>) self.login.click_submit() result = self.login.get_user_name() print(result) self.assertTrue(result == expect) @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() cls.login = LoginPage(cls.driver) def setUp(self): self.driver.get('https://leisongwei.5upm.com/my/') @ddt.data(*testdatas) def test1(self,data): self.login_case(data['user'],data['password'], data['expect']) def tearDown(self): sleep(1) self.login.is_alert() self.driver.delete_all_cookies() sleep(1) @classmethod def tearDownClass(cls): cls.driver.quit() if __name__ == '__main__': unittest.main()<file_sep>#-*- coding: utf-8 -*- from selenium import webdriver from base.base import Base class LoginPage(Base): loc_user = ('id', 'account') loc_password = ('<PASSWORD>', '<PASSWORD>') loc_submit = ('id', 'submit') loc_login_name = ('css selector', '.user-name') def send_user(self, user): self.sendText(self.loc_user, user) def send_password(self, password): self.sendText(self.loc_password, password) def click_submit(self): self.click(self.loc_submit) def confirm_alert(self): a = self.is_alert_new() if a: a.accept() def get_user_name(self): return self.get_text(self.loc_login_name) def login(self, user='admin123', password='<PASSWORD>'): self.driver.get('https://leisongwei.5upm.com/user-login.html') self.send_user(user) self.send_password(password) self.click_submit() if __name__ == '__main__': driver = webdriver.Firefox() driver.get('https://leisongwei.5upm.com/user-login.html') login = LoginPage(driver) login.send_user('admin123') login.send_password('<PASSWORD>') login.click_submit() login.get_user_name()<file_sep>from time import sleep from selenium import webdriver driver = webdriver.Firefox() driver.get('https://www.baidu.com') a = driver.find_element_by_xpath('html/body/div[1]/div[1]/div/div[3]/a[8]').text b = driver.find_element_by_xpath('html/body/div[1]/div[1]/div/div[3]/a[8]').get_attribute('name') print(a, b)<file_sep> from time import sleep from selenium import webdriver import unittest class Test_login(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() def setUp(self): self.driver.get('https://leisongwei.5upm.com/my/') def is_login_success(self): try: a = self.driver.find_element_by_css_selector('.user-name').text print("登录成功,账号:%s"% a) return a except: print('没有登录成功') return '' def test1(self): self.driver.find_element_by_id('account').send_keys('admin123') self.driver.find_element_by_name('password').send_keys('<PASSWORD>') self.driver.find_element_by_id('submit').click() sleep(3) a = self.is_login_success() self.assertTrue(a == 'admin123') def test2(self): self.driver.find_element_by_id('account').send_keys('<PASSWORD>') self.driver.find_element_by_name('password').send_keys('a') self.driver.find_element_by_id('submit').click() sleep(3) a = self.is_login_success() self.assertTrue(a == '') def tearDown(self): sleep(1) self.driver.delete_all_cookies() self.driver.refresh() sleep(1) @classmethod def tearDownClass(cls): cls.driver.quit() if __name__ == '__main__': unittest.main()<file_sep># coding:utf-8 from time import sleep from selenium import webdriver # 加载插件 profile_directory = r'C:\Users\Administrator\AppData\Roaming\Mozilla\Firefox\Profiles\s6qtifzn.default' profile = webdriver.FirefoxProfile(profile_directory) # 打开浏览器 driver = webdriver.Firefox(profile) driver.get("http://gz.ganji.com/") sleep(1) # 滚动到底部 js = 'window.scrollTo(0,document.body.scrollHeight)' driver.execute_script(js) # 滚动到顶部 sleep(1) driver.execute_script("window.scrollTo(0, 0)") sleep(1) # 滚动到指定位置 ele = driver.find_element_by_link_text('新车') js = 'arguments[0].scrollIntoView();' driver.execute_script(js, ele) sleep(1) driver.quit()
186896f85bed038963d60d5905bae7bc4a7bf275
[ "Python" ]
17
Python
leisongwei/auto_repository_name
fdd3ada52063b88755497c7696dacdeffa29eeca
fcb8c7df2c20ba6c97c03d8fe7473857000d3e0c
refs/heads/master
<file_sep><main> <h1 class = "ueberschrift"> Falsche Daten</h1> <?php //Überprüfen ob das Formular auch wirklich ausgefüllt wurde if(!empty($_POST['submit']) && $_POST['submit'] === 'Registrieren') { //herausholen der Daten aus dem Post $data = $_POST; //Prüfvariable $invalid = false; //Überprüfen ob name grösser als 40 oder kleiner als 5 ist if(strlen($data['name']) > 40 || strlen($data['name']) < 5) {?> <p><?php echo 'Benutzername muss zwischen 5 und 40 Zeichen lang sein!<br/>'; $invalid = true; } //Email regex für eine Valide Emailadresse if(!preg_match('/^(\w{2,}|\w{2,}[\.\-]\w{2,})@(\w{2,}\.\w{2,}|\w{2,}[\.\-]\w{2,}\.\w{2,})$/', $data['email'])) { echo 'Email ist ung&uuml;ltig!<br/>'; $invalid = true; } //Prüfen ob beide Passwörter gleich sind. if($data['pw1'] === $data['pw2']) { if(!preg_match('/^[\w@#%&$£]{8,}$/', $data['pw1'])) {?> <p><?php echo 'Passwort muss folgendes erf&uuml;llen:' ?> </p> <p> Mindestens 8 Zeichen lang!<br> </p> <p>Mindestens eine Zahl!<br> </p> <p>Mindestens ein Sonderzeichen!<br></p> <?php $invalid = true; } } else { ?><p><?php echo 'Passw&ouml;rter stimmen nicht &uuml;berein!<br/>';?> </p> <?php $invalid = true; } //überprüfen ob alles richtig if($invalid == false) { //Speichern der Daten in Session $db = connect(); $stmt = $db->prepare( "INSERT INTO Profil (name, email, benutzername, passwort) VALUES (?, ?, ?, ?)"); // Das Passwort wird gehasht $password = hash('<PASSWORD>', $data['pw1']); $stmt->bind_param("ssss", $_POST["name"], $_POST["email"], $_POST["username"], $password); $stmt->execute(); if (isset($_SESSION['username'])){} $_SESSION['data'] = $data; $db->close(); //Weiterleitung zum insert-File header("Location: login"); } } else { //Hinweis, dass das Formular nicht ausgefüllt ist echo 'F&uuml;llen Sie bitte zuerst das <a href="signup">Formular</a> aus!<br/>'; } ?> </main><file_sep><!-- Hier wird die Webseite für das Produkt gemacht, auf welches man klickt. Das Produkt wird gross mit allen Angeben dargestellt. --> <?php //Verbindung zur Datenbank $db = connect();; ?> <!-- <main class = "nachsuche"> --> <?php // Select Anfrage wird vorbereitet. $id = $_GET['p']; $sql = "SELECT Preis, Bild, Bild2, Name, Beschreibung, Kategorie_ID from Artikel join Kategorie on ID_Kategorie = Kategorie_ID WHERE ID_Artikel = $id "; $result = $db->query($sql); if($result->num_rows >= 1) { while($row = $result->fetch_assoc()) { ?> <main class = "mainprodukt"> <div> <h1 class = "ueberschrift"><?PHP echo $row['Name']?></h1> <p></p> <div class = "anzeigeProdukt"> <div class="ui grid"> <div class="ten wide column"> <div class="slideshow-container"> <div class="mySlides"> <!-- Hier werden die Img's für den Slide eingefügt.--> <img class = "imgprodukt"src="pictures/<?php echo $row['Bild']?>" alt="Das Bild kann nicht angekeit werden."> </div> <div class="mySlides"> <img class = "imgprodukt" src="pictures/<?php echo $row['Bild2']?>" alt="Das Bild kann nicht angekeit werden."> </div> </div> </div> <!-- Hier wird das Grid vorbereitet --> <div class="six wide column"><h2 class = "beschreibung">Grösse:</h2> <form action="home"> <select class = "groesse" name="groesse"> <?php // Je nach Kategorie werden verschiedene Grössen angezeit. Hier sind es die Schuhe. if ($row['Kategorie_ID'] == 1){ ?> <option value="42" seleced> Grösse wählen</option> <option value="42">42</option> <option value="42.5">42.5</option> <option value="43" >43</option> <option value="43.5">43.5</option> <?php // Hier sind es die Kleider } Else if ($row['Kategorie_ID'] == 2){ ?> <option value="S" seleced> Grösse wählen</option> <option value="S">S</option> <option value="M">M</option> <option value="L" >L</option> <?php // Hier sind es die anderen Sachen wie Caps oder Rucksäcke. } else { ?> <option value="42" seleced> Grösse wählen</option> <option value="1">One Size</option> <?php } ?> </select> </form> <!-- Hier werden die Daten für den Preis und Info eingfügt --> <h2 class = "beschreibung">Preis: <span class = "anzeige"> <?php echo $row['Preis'] ?> . -</span></h2> <h2 class = "beschreibung">infos: <span class = "anzeige"> <?php echo $row['Beschreibung']?></span></h2> <a href="https://www.stadiumgoods.com" target="_blank"><button class="ui inverted green button">Kaufen</button></a> </div> </div> </div> </div> <?php } } ?> <script> // Hier wird dei Slideschow erstellt, wo die Produkte gezeigt werden. var slideIndex = 0; showSlides(); function showSlides() { var slides = document.getElementsByClassName("mySlides"); for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slides[slideIndex].style.display = "block"; slideIndex = slideIndex + 1; if (slideIndex >= slides.length) { slideIndex = 0; } setTimeout(showSlides, 2500); } </script> </main> <?php $db->close(); ?><file_sep><?php //Verbindung zur Datenbank $db = connect(); ?> <main class = "nachsuche"> <?php $suche = $_POST['suche']; ?> <h1 class = "ueberschrift"><?php echo $suche?></h1> <?php $i = 1; // Es nach dem Produkt gesucht, welches man sucht $sql = "SELECT ID_Artikel,Preis, Bild, Name from Artikel WHERE name like '%$suche%'"; $result = $db->query($sql); if($result->num_rows >= 1) { ?> <!-- Es wird im dem Grid die einzelnen Produkte aufgelistet--> <div class="ui grid"> <?php //Es erstellt solange neue grideinträge bis es keine Produkte hat, welche dem Suchbegriff entsprechen. while($row = $result->fetch_assoc()) { ?> <div class="four wide column"><a href="produkt?p=<?php echo $row['ID_Artikel']?>"><img class="img" src="pictures/<?php echo $row['Bild'] ?>" alt="Das Bild kann nicht angekeit werden."> <br></a><p><?php echo $row['Name'] ?></p> <br> <p><?php echo $row['Preis'] ?> . -</p> </div> <?php } }else { ?> <!-- Diese Seite wird geladen, wenn es keien Ergebnisse hat--> <div class = "keienErgebnisse"> <img class = "umgekehrt" src="pictures/Ergebnisse.png" alt=""><img class = "umgekehrt" src="pictures/Ergebnisse.png" alt="Das Bild kann nicht angekeigt werden."> <h1 class = "ueberschrift">Keine Ergebnisse gefunden!</h1> <img class = "normal" src="pictures/Ergebnisse.png" alt=""><img class = "normal" src="pictures/Ergebnisse.png" alt="Das Bild kann nicht angezeigt werden."> </div> <?php } $db->close(); ?> </main><file_sep><?php /*Hier wird die verbindung auf die DB in eine Funktion gepakt.*/ function connect(){ $db = new Mysqli("srv108", "hoogj", "<PASSWORD>$", "<PASSWORD>"); return $db; } ?><file_sep><!-- Hier wird geschaut ob alles mit dem Login inordnug ist.--> <?php //Verbindung zur Datenbank $db = connect(); //holen der Daten $data = $_POST; $name= $data["username"]; $password = hash('<PASSWORD>', $data['pw']); //Definieren des Queries $sql = "SELECT ID_Profil, Benutzername, Email, Name FROM Profil WHERE Benutzername = ? AND Passwort = ?;"; $statement = $db->prepare($sql); $statement->bind_param('ss', $name, $password); $statement->execute(); $statement->bind_result($id_user, $username, $email, $name); // die Daten in das User array schreiben while($statement->fetch()){ $user = array('ID_Profil' => $id_user, 'Benutzername' => $username, 'Email' => $email, 'Name' => $name); } // Die daten in das Userdata schreiben, aber nur wenn user schon gefüllt ist. if(!empty($user)){ $_SESSION['userdata'] = array("ID_Profil" => $user['ID_Profil'], "Benutzername" => $user['Benutzername'], "Email" => $user['Email'], "login" => true); $_SESSION['name']= $name; header("Location: myaccountreg"); // es wird eine error gespeichet, welcher wird dann im Home brauchen }else{ $_SESSION['error']='login'; header("Location: login"); } $db->close(); ?><file_sep><!-- Hier wird die myAccount Seite gemacht, wenn man eingelogt ist--> <main> <h1 class = "ueberschrift"><?php echo $_SESSION['userdata']['Benutzername']?></h1> <p>Name: <?php echo $_SESSION['name']?></p> <p>Email: <?php echo $_SESSION['userdata']['Email']?></p> <p>Passwort ändern kannst du <a href="passwort">Hier</a> </p> <p>Deinen Account löschen kannst du <a href="delete">Hier</a></p> <img class = "normal" src="pictures/Suche.png" alt=""><img class = "normal" src="pictures/Suche.png" alt="Das Bild kann nicht angezeigt werden."> </main><file_sep><!-- Hier wird die Seite zusammengebaut je nach request--> <?php function build($page) { ?> <!DOCTYPE html> <html> <?php require_once 'head.php'; ?> <body> <header> <?php require_once 'header.php'; ?> </header> <?php /*Hier wird geschaut ob der User sich schon eingeloggt hat, wenn ja dann wird die navigationreg genommen wenn nein dann die normaile Navigaion.*/ if(isset($_SESSION['userdata'])){ ?> <nav> <?php require_once 'navigationreg.php';?> </nav> <?php } else{ ?> <nav> <?php require_once 'navigation.php';?> </nav> <?php } ?> <main> <?php require_once './views/'.$page; require_once './views/BackToTop.php'; ?> </main> <footer> <?php require_once 'footer.php'; ?> </footer> </body> </html> <?php } ?><file_sep><!-- Hier wird der Account gelöscht--> <?php //Verbindung zur Datenbank $db = connect(); //holen der Daten $data = $_POST; //Definieren des Queries $sql = "delete FROM Profil WHERE ID_Profil = ?;"; $statement = $db->prepare($sql); var_dump( $_SESSION["userdata"]["ID_profil"]); $statement->bind_param('i', $_SESSION["userdata"]["ID_Profil"]); $statement->execute(); header("Location: logout"); $db->close(); ?> <file_sep><!-- Hier wird der Button erstellt, mit welchen man zurück zu dem Anfang kommt erstellt.--> <main> <button onclick="topFunction()" id="myBtn" title="Go to top">Zum Seitenanfang</button> <script> // Wenn 30px nach unten gescrollt werden, erscheint der button window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 30 || document.documentElement.scrollTop > 23) { document.getElementById("myBtn").style.display = "block"; } else { document.getElementById("myBtn").style.display = "none"; } } // Wenn auf den Button geklickt wird, zurück zum Anfang des Dokuments function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } </script> </main><file_sep><!-- Hier wrid das Login zusammen gebaut.--> <main> <h1 class = "ueberschrift">Login</h1> <form class = "formular" action="checklogin" method = "post" > <input class = "form" type="text" placeholder = "Username*" name = "username"required> <br> <input class = "form" type="password" placeholder = "Passwort*" name = "pw"required> <br> <input class = "SigninSubmit" type="submit"> </form> <!-- Es wird geschaut ob in der Session ein error gespeichert wurde--> <?php if(isset($_SESSION['error']) && $_SESSION['error' =='login']){ ?> <!-- Es wird eine Error ausgegeben--> <p class = "error"> Das Passwort oder der Benutzernmae ist falsch!</p> <?php } ?> <div class="divImgSignin"> </div> </main> <file_sep><!-- Hier wird die Home Seite erstellt.--> <?php //Verbindung zur Datenbank $db = connect(); ?> <!-- Das Grid vorbereiten--> <main class = "mainhome"> <h1 class = "ueberschrift">Home</h1> <div class="ui grid"> <?php $i = 1; // 20 Mal das Select Statement ausführen um 20 Produkte aus der DB zu lesen while($i <= 20){ $sql = "SELECT ID_Artikel, Preis, Bild, Name from Artikel where ID_Artikel= $i;"; $result = $db->query($sql); if($result->num_rows >= 1) { // Für jedes Produkt das Grid zusammenbauen while($row = $result->fetch_assoc()) { ?> <div class="four wide column"><a href="produkt?p=<?php echo $row['ID_Artikel']?>"><img class="img" src="pictures/<?php echo $row['Bild'] ?>" alt="Das Bild kann nicht angekeit werden."> <br></a><p class = "p"><?php echo $row['Name'] ?> </p> <br><p class = "p"><?php echo $row['Preis'] ?> . -</p> </div> <?php } }$i = $i + 1; } $db->close(); ?> </div> </main> <file_sep><!-- Es wird die Sessin abgebrochen, daher wird man ausgelogt--> <?php session_destroy(); header("Location: Login"); ?><file_sep><!-- Hier wird die das Passwort überprüft und geändert. --> <?php //Überprüfen ob das Formular auch wirklich ausgefüllt wurde if(!empty($_POST['submit']) && $_POST['submit'] === 'ändern') { //herausholen der Daten aus dem Post $data = $_POST; //Prüfvariable $invalid = false; $pw1= $data['pw1']; $pw2 = $data['pw2']; //Prüfen ob beide Passwörter gleich sind. //Prüfen ob es den Anforderungen entspricht if($pw1 === $pw2) { if(!preg_match('/^[\w@#%&$£]{8,}$/', $pw1)) {?> <h1 class = "ueberschrift">Falsche Daten.</h1> <p><?php echo 'Passwort muss folgendes erf&uuml;llen:' ?> </p> <p> Mindestens 8 Zeichen lang!<br> </p> <p> Mindestens eine Zahl!</li><br> <p> Mindestens ein Sonderzeichen!<br></p> <img class = "normal" src="pictures/Suche.png" alt=""><img class = "normal" src="pictures/Suche.png" alt="Das Bild kann nicht angezeigt werden."> <?php $invalid = true; } } else { ?><h1 class = "ueberschrift">Die Passwörter sind nicht gleich.</h1> <p><?php echo 'Passw&ouml;rter stimmen nicht &uuml;berein!<br/>';?> </p> <img class = "normal" src="pictures/Suche.png" alt=""><img class = "normal" src="pictures/Suche.png" alt="Das Bild kann nicht angezeigt werden."><?php $invalid = true; } //überprüfen ob alles richtig if($invalid == false) { $pw1= hash('sha256', $data['pw1']); $pw2 = hash('sha256', $data['pw2']); //Speichern der Daten in Session $db = connect(); $stmt = $db->prepare("update Profil set Passwort = ? where ID_Profil = ?;"); $stmt->bind_param("ss", $pw1, $_SESSION["userdata"]['ID_Profil']); $stmt->execute(); $_SESSION['data'] = $data; $db->close(); //Weiterleitung zum home-File header("Location: home"); } } ?><file_sep><?php session_start(); //Builder laden include_once "resources/builder.php"; include_once "resources/Database.php"; /* Die Wichtchtigsten Befehle: *Explode() --> Teilt einen String anhand eriner Zeichenkette *trim() --> eintfernt Whitespaces (ider andere Zeichen) am Anfang und End eines Strings *$-serve['Request_uri] --> Der URI, der angegeben wurde, um auf die akuelle Seite zuzugreiffen *strstr --> Findet das erste Vorkommen eines Strings */ //Die URL Teilen $temp = trim($_SERVER['REQUEST_URI'], '/'); $url = explode('/', $temp); if (isset($url[2])){ $url = explode('?', trim($url[2])); } else { $url[0] = $url[2]; } if(!empty($url[0])) { // alles zu Kleinbuchstaben umformtieren $url[0] = strtolower($url[0]); switch($url[0]) { case 'home': build('home.php'); break; case 'login': build('login.php'); break; case 'search': build('search.php'); break; case 'produkt': build('produkt.php'); break; case 'impressum'; build('impressum.php'); break; case 'search': build('search.php'); break; case 'nachsuche': build('nachSuche.php'); break; case 'signup': build('signup.php'); break; case 'validate': build('validate.php'); break; case 'checklogin': build('checklogin.php'); break; case 'myaccountreg': build('myAccountreg.php'); break; case 'insert': build('insert.php'); break; case 'logout': build('logout.php'); break; case 'passwort': build('passwort.php'); break; case 'passwortaendern': build('passwortaendern.php'); break; case 'delete': build('delete.php'); break; case 'deleteaccount': build('deleteaccount.php'); break; } }//Ist der Wert nicht gesetzt wird die Standartseite (home) aufgerufen. else { build('home.php'); } ?>
a60062ed2efbde434053e80245300df9c5e71369
[ "PHP" ]
14
PHP
nicola22/depost
7312526026894a0de47fd7f3a28fec391714943c
3bb984412e3c07ab839a7f5bcc74b316473177b5
refs/heads/master
<repo_name>seanholahan/seanholahan-assignment-web<file_sep>/public/assignment/services/website.service.client.js (function(){ angular .module("WebAppMaker") .factory("WebsiteService", WebsiteService); function WebsiteService($http) { var api = { findWebsitesForUser: findWebsitesForUser, findWebsiteById: findWebsiteById, createWebsite: createWebsite, updateWebsite: updateWebsite, removeWebsite: removeWebsite }; return api; function removeWebsite(websiteId) { var url = "/api/website/"+ websiteId; $http.delete(url); } function updateWebsite(websiteId, website) { var url = "/api/website/"+websiteId; $http.put(url, website); } function createWebsite(uid, website) { var url = "/api/user/"+uid+"/website"; $http.post(url, website); } function findWebsiteById(wid) { var url = "/api/website/"+wid; return $http.get(url); } function findWebsitesForUser(uid) { var url = "/api/user/"+uid+"/website"; return $http.get(url, uid); } } })();<file_sep>/public/assignment/views/website/website-list.controller.js (function (angular) { var WebAppMaker = angular.module("WebAppMaker") .controller("WebsiteListController", WebsiteListController) function WebsiteListController($routeParams, WebsiteService) { var vm = this; vm.userId = parseInt($routeParams.uid); function init() { var promise = WebsiteService.findWebsitesForUser(vm.userId); promise .success(function(websites){ vm.websites = websites; }); } init(); } })(window.angular);<file_sep>/public/assignment/views/page/page-new.controller.client.js (function (angular) { var WebAppMaker = angular.module("WebAppMaker") .controller("PageNewController", PageNewController) function PageNewController($routeParams, PageService, $location) { var vm = this; vm.userId = parseInt($routeParams.uid); vm.websiteId = parseInt($routeParams.wid); vm.pageId = parseInt($routeParams.pid); vm.userId = parseInt($routeParams.uid); vm.websiteId = parseInt($routeParams.wid); vm. widgetId = parseInt($routeParams.wgid); vm.updatePage = updatePage; vm.deletePage = deletePage; vm.createPage = createPage; vm.paged = { "_id": 0, "name": "", "websiteId": "", "description": ""}; function init() { vm.pages = PageService.findPageByWebsiteId(vm.websiteId); vm.page = PageService.findPageById(vm.pageId); } init(); function updatePage(page) { PageService.updatePage(page); $location.url("/user/" + vm.userId + "/website/" +vm.websiteId + "/page"); } function deletePage(pid) { PageService.deletePage(vm.pageId); $location.url("/user/" +vm.userId + "/website/"+vm.websiteId + "/page"); } function createPage(paged) { vm.paged._id = (new Date()).getTime(); vm.paged.websiteId = this.websiteId; PageService.createPage(vm.paged); $location.url("/user/" + vm.userId + "/website/" + vm.websiteId + "/page"); // vm.pages = PageService.findWebsitesForUser(vm.userId); } } })(window.angular);<file_sep>/public/assignment/views/page/page-list.controller.client.js (function (angular) { var WebAppMaker = angular.module("WebAppMaker") .controller("PageListController", PageListController) function PageListController($routeParams, PageService) { var vm = this; vm.websiteId = parseInt($routeParams.wid); vm.uid = $routeParams.uid; vm.wid = $routeParams.wid; vm.pid = $routeParams.pid; vm.wgid = $routeParams.wgid; /* vm.updatePage = updatePage; vm.removePage = removePage;*/ function init() { var promise = PageService.findPagesByWebsiteId(vm.websiteId); promise .success(function(pages){ vm.pages = pages; }); } init(); } })(window.angular); <file_sep>/public/assignment/views/website/website-edit.controller.client.js (function () { angular .module("WebAppMaker") .controller("WebsiteEditController", WebsiteEditController); function WebsiteEditController($routeParams, WebsiteService) { var vm = this; vm.userId = parseInt($routeParams.uid); vm.uid = $routeParams.uid; vm.wid = $routeParams.wid; vm.pid = $routeParams.pid; vm.wgid = $routeParams.wgid; function init() { var promise = WebsiteService.findWebsitesForUser(vm.userId); promise .success(function(websites){ vm.websites = websites; }); } init(); } })(window.angular);
eb2ce93c459e59eaf2b43ec265fc2a5707502c1b
[ "JavaScript" ]
5
JavaScript
seanholahan/seanholahan-assignment-web
778c25ea25b256b1240588079672fa34f5c44e40
dcebd69ff680a0036ac5efa038e364705c62c399
refs/heads/master
<file_sep><?php // Free html5 templates : www.zerotheme.com $text = "<span style='color:red; font-size: 35px; line-height: 40px; magin: 10px;'>Error! Please try again.</span>"; if(isset($_POST['submitContact'])) { $name=$_POST['name']; $email=$_POST['email']; $subject = $_POST['subject']; $message=$_POST['message']; $to = "<EMAIL>"; $subject = "Zerotheme - Testing Contact Form"; $message = " Name: " . $name ."\r\n Email: " . $email . "\r\n Message:\r\n" . $message; $from = "Zerotheme"; $headers = "From:" . $from . "\r\n"; $headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n"; if(@mail($to,$subject,$message,$headers)) { $text = "<span style='color:blue; font-size: 35px; line-height: 40px; margin: 10px;'>Your Message was sent successfully !</span>"; } } ?> <!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]--> <head> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8"> <title>zKingMan</title> <meta name="description" content="Free Responsive Html5 Css3 Templates | zerotheme.com"> <meta name="author" content="www.zerotheme.com"> <!-- Mobile Specific Metas ================================================== --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- CSS ================================================== --> <link rel="stylesheet" href="css/zerogrid.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/lightbox.css"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="css/menu.css"> <script src="js/jquery1111.min.js" type="text/javascript"></script> <script src="js/script.js"></script> <!-- Owl Carousel Assets --> <link href="owl-carousel/owl.carousel.css" rel="stylesheet"> <!-- <link href="owl-carousel/owl.theme.css" rel="stylesheet"> --> <!--[if lt IE 8]> <div style=' clear: both; text-align:center; position: relative;'> <a href="http://windows.microsoft.com/en-US/internet-explorer/Items/ie/home?ocid=ie6_countdown_bannercode"> <img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." /> </a> </div> <![endif]--> <!--[if lt IE 9]> <script src="js/html5.js"></script> <script src="js/css3-mediaqueries.js"></script> <![endif]--> </head> <body> <div class="wrap-body"> <div class="header"> <div id='cssmenu' class="align-right"> <ul> <li class="active"><a href='index.html'><span>zKingMan</span></a></li> <li class=' has-sub'><a href='archive.html'><span>Blog</span></a> <ul> <li class='has-sub'><a href='#'><span>Item 1</span></a> <ul> <li><a href='#'><span>Sub Item</span></a></li> <li class='last'><a href='#'><span>Sub Item</span></a></li> </ul> </li> <li class='has-sub'><a href='#'><span>Item 2</span></a> <ul> <li><a href='#'><span>Sub Item</span></a></li> <li class='last'><a href='#'><span>Sub Item</span></a></li> </ul> </li> </ul> </li> <li><a href='#'><span>Gallery</span></a></li> <li><a href='single.html'><span>About</span></a></li> <li class='last'><a href='contact.html'><span>Contact</span></a></li> </ul> </div> </div> <!--////////////////////////////////////Container--> <section id="container"> <div class="wrap-container"> <div class="zerogrid"> <div class="row"> <div class="row"> <div class="col-1-2"> <a href="index.html"><img src="images/logo.png" /></a> </div> <div class="col-1-2"> <form id="form-container" action="" class="f-right"> <!--<input type="submit" id="searchsubmit" value="" />--> <a class="search-submit-button" href="javascript:void(0)"> <i class="fa fa-search"></i> </a> <div id="searchtext"> <input type="text" id="s" name="s" placeholder="Search Something..."> </div> </form> </div> </div> <div class="crumbs"> <ul> <li><a href="index.html">Home</a></li> <li><a href="gallery.html">Contact</a></li> </ul> </div> <h1 class="color-red" style="margin: 20px 0">Contact</h1> <div class="col-full"> <div class='embed-container maps'> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3164.289259162295!2d-120.7989351!3d37.5246781!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8091042b3386acd7%3A0x3b4a4cedc60363dd!2sMain+St%2C+Denair%2C+CA+95316%2C+Hoa+K%E1%BB%B3!5e0!3m2!1svi!2s!4v1434016649434" width="100%" height="450" frameborder="0" style="border:0"></iframe> </div> </div> <div class="col-1-3"> <div class="wrap-col"> <h3 class="color-blue" style="margin: 20px 0">Contact Info</h3> <span>SED UT PERSPICIATIS UNDE OMNIS ISTE NATUS ERROR SIT VOLUPTATEM ACCUSANTIUM DOLOREMQUE LAUDANTIUM, TOTAM REM APERIAM.</span> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque la udantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia.</p> <p>JL.Kemacetan timur no.23. block.Q3<br> Jakarta-Indonesia</p> <p>+6221 888 888 90 <br> +6221 888 88891</p> <p><EMAIL></p> </div> </div> <div class="col-2-3"> <div class="wrap-col"> <div class="contact"> <h3 class="color-green" style="margin: 20px 0 20px 30px">Contact Form</h3> <!--Warning--> <center><?php echo $text;?></center> <!----> <div id="contact_form"> <form name="form1" id="ff" method="post" action="contact.php"> <label class="row"> <div class="col-1-2"> <div class="wrap-col"> <input type="text" name="name" id="name" placeholder="Enter name" required="required" /> </div> </div> <div class="col-1-2"> <div class="wrap-col"> <input type="email" name="email" id="email" placeholder="Enter email" required="required" /> </div> </div> </label> <label class="row"> <div class="wrap-col"> <input type="text" name="subject" id="subject" placeholder="Subject" required="required" /> </div> </label> <label class="row"> <div class="wrap-col"> <textarea name="message" id="message" class="form-control" rows="4" cols="25" required="required" placeholder="Message"></textarea> </div> </label> <center><input class="sendButton" type="submit" name="submitContact" value="Submit"></center> </form> </div> </div> </div> </div> </div> </div> </div> </section> <!--////////////////////////////////////Footer--> <footer> <div class="wrap-footer"> <div class="zerogrid"> <div class="row"> <div class="col-1-3"> <div class="wrap-col"> <p>Copyright - Designed by <a href="https://www.zerotheme.com" title="free website templates">ZEROTHEME</a></p> </div> </div> <div class="col-1-3"> <div class="wrap-col"> <ul class="social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a href="#"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> <div class="col-1-3"> <div class="wrap-col"> <ul class="quick-link"> <li><a href="#">Privacy Policy</a></li> <li><a href="#">Terms of Use</a></li> </ul> </div> </div> </div> </div> </div> </footer> </div> </body> <!-- Google Map --> <script> $('.maps').click(function () { $('.maps iframe').css("pointer-events", "auto"); }); $( ".maps" ).mouseleave(function() { $('.maps iframe').css("pointer-events", "none"); }); </script> </html> </html>
21d2fa53425ba5aaab74f79f90b8748e14d36bf8
[ "PHP" ]
1
PHP
CarsBlog/CarsBlog.github.io
4e0e291e72abfa83de5f66cd2959b19d5eb4fd41
18b1c7f2bc903813acf544b9ab93110b21c7e0dd
refs/heads/master
<repo_name>hzxc/material-angular-demo<file_sep>/src/app/other/timeago-demo/jq-plugin.directive.ts import { Directive, ElementRef, AfterViewInit, OnInit } from '@angular/core'; import { AfterViewChecked, OnChanges } from '@angular/core/src/metadata/lifecycle_hooks'; @Directive({ // tslint:disable-next-line:directive-selector selector: '[jq-plugin]' }) export class JqPluginDirective implements OnInit, OnChanges, AfterViewInit, AfterViewChecked { constructor( private _element: ElementRef ) { } ngOnInit() { } ngOnChanges() { } ngAfterViewChecked() { } ngAfterViewInit(): void { console.log('ngAfterViewChecked'); const $element = $(this._element.nativeElement); const pluginName = $element.attr('jq-plugin'); const options = $element.attr('jq-options'); if (!options) { $element.timeago(); // $element[pluginName](); } else { // tslint:disable-next-line:no-eval $element[pluginName](eval('(' + options + ')')); } } } <file_sep>/src/app/ng-chart-demo/ng-chart-demo.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { NgChartDemoComponent } from './ng-chart-demo.component'; import { ChartModule } from 'angular-highcharts'; import { NgChartDemoRoutingModule } from './ng-chart-demo-routing.module'; @NgModule({ imports: [ CommonModule, ChartModule, NgChartDemoRoutingModule ], declarations: [NgChartDemoComponent] }) export class NgChartDemoModule { } <file_sep>/src/app/check-box/check-box.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-check-box', templateUrl: './check-box.component.html', styleUrls: ['./check-box.component.scss'] }) export class CheckBoxComponent implements OnInit { foods = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' } ]; languages: LanguageDto[] = [ { 'name': 'de', 'displayName': 'Deutsch', 'icon': 'flag-icon flag-icon-de', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'en', 'displayName': 'English', 'icon': 'flag-icon flag-icon-gb', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'es-MX', 'displayName': 'Español (México)', 'icon': 'flag-icon flag-icon-mx', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'es', 'displayName': 'Español (Spanish)', 'icon': 'flag-icon flag-icon-es', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'fr', 'displayName': 'Français', 'icon': 'flag-icon flag-icon-fr', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'it', 'displayName': 'Italiano', 'icon': 'flag-icon flag-icon-it', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'pt-BR', 'displayName': 'Português (Brasil)', 'icon': 'flag-icon flag-icon-br', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'ru', 'displayName': 'Pусский', 'icon': 'flag-icon flag-icon-ru', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'tr', 'displayName': 'Türkçe', 'icon': 'flag-icon flag-icon-tr', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': false }, { 'name': 'ar', 'displayName': 'العربية', 'icon': 'flag-icon flag-icon-sa', 'isDefault': false, 'isDisabled': false, 'isRightToLeft': true }, { 'name': 'zh-CN', 'displayName': '简体中文', 'icon': 'flag-icon flag-icon-cn', 'isDefault': true, 'isDisabled': false, 'isRightToLeft': false } ]; private selectedItem: LanguageDto = new LanguageDto(); constructor() { this.selectedItem.name = 'zh-CN'; this.selectedItem.displayName = '简体中文'; this.selectedItem.icon = 'flag-icon flag-icon-cn'; this.selectedItem.isDefault = true; this.selectedItem.isDisabled = false; this.selectedItem.isRightToLeft = false; } ngOnInit() { } } class LanguageDto { name: string; 'displayName': string; 'icon': string; 'isDefault': boolean; 'isDisabled': boolean; 'isRightToLeft': boolean; } <file_sep>/src/app/rxjs-demo/rxjs-demo.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RxjsDemoComponent } from './rxjs-demo.component'; import { RxjsDemoRoutingModule } from './rxjs-demo-routing.module'; import { MaterialModule } from '../shared/material/material.module'; @NgModule({ imports: [ CommonModule, RxjsDemoRoutingModule, MaterialModule ], declarations: [RxjsDemoComponent] }) export class RxjsDemoModule { } <file_sep>/src/app/autocomplete/filter/filter.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'app-filter', templateUrl: './filter.component.html', styleUrls: ['./filter.component.scss'] }) export class FilterComponent implements OnInit { myControl: FormControl = new FormControl(); options = [ 'One', 'Two', 'Three' ]; filteredOptions: Observable<string[]>; ngOnInit() { this.filteredOptions = this.myControl.valueChanges .startWith(null) .map(val => val ? this.filter(val) : this.options.slice()); } filter(val: string): string[] { return this.options.filter(option => option.toLowerCase().indexOf(val.toLowerCase()) === 0); } } <file_sep>/src/app/ng-chart-demo/ng-chart-demo-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { NgChartDemoComponent } from './ng-chart-demo.component'; const routes: Routes = [ { path: '', component: NgChartDemoComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class NgChartDemoRoutingModule { } <file_sep>/src/app/table/retrieving-data-through-http/retrieving-data-through-http.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; import { Http } from '@angular/http'; import { DataSource } from '@angular/cdk/collections'; import { MatPaginator, MatSort } from '@angular/material'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/finally'; @Component({ selector: 'app-retrieving-data-through-http', templateUrl: './retrieving-data-through-http.component.html', styleUrls: ['./retrieving-data-through-http.component.scss'] }) export class RetrievingDataThroughHttpComponent implements OnInit { displayedColumns = ['created_at', 'state', 'number', 'title']; exampleDatabase: ExampleHttpDao | null; dataSource: ExampleDataSource | null; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; constructor(private http: Http) { } ngOnInit() { this.exampleDatabase = new ExampleHttpDao(this.http); this.dataSource = new ExampleDataSource( this.exampleDatabase, this.paginator, this.sort); } } export interface GithubApi { items: GithubIssue[]; total_count: number; } export interface GithubIssue { created_at: string; number: string; state: string; title: string; } export class ExampleHttpDao { constructor(private http: Http) { } getRepoIssues(sort: string, order: string, page: number): Observable<GithubApi> { const href = 'https://api.github.com/search/issues'; const requestUrl = `${href}?q=repo:angular/material2&sort=${sort}&order=${order}&page=${page + 1}`; return this.http.get(requestUrl) .map(response => response.json() as GithubApi); } } export class ExampleDataSource extends DataSource<GithubIssue> { // The number of issues returned by github matching the query. resultsLength = 0; isLoadingResults = true; isRateLimitReached = false; constructor(private exampleDatabase: ExampleHttpDao, private paginator: MatPaginator, private sort: MatSort) { super(); } /** Connect function called by the table to retrieve one stream containing the data to render. */ connect(): Observable<GithubIssue[]> { const displayDataChanges = [ this.sort.sortChange, this.paginator.page ]; // If the user changes the sort order, reset back to the first page. this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); return Observable.merge(...displayDataChanges) .startWith(null) .do(_ => { this.isLoadingResults = true; }) .switchMap(() => { return this.exampleDatabase.getRepoIssues( this.sort.active, this.sort.direction, this.paginator.pageIndex); }) .map(data => { // Flip flag to show that loading has finished. this.isLoadingResults = false; this.isRateLimitReached = false; this.resultsLength = data.total_count; return data.items; }) .catch(() => { this.isLoadingResults = false; // Catch if the GitHub API has reached its rate limit. Return empty data. this.isRateLimitReached = true; return Observable.of([]); }); } disconnect() { } } <file_sep>/src/app/other/timeago-demo/timeago-demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-timeago-demo', templateUrl: './timeago-demo.component.html', styleUrls: ['./timeago-demo.component.scss'] }) export class TimeagoDemoComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/src/app/reg-exp/reg-exp.component.ts import { Component, OnInit } from '@angular/core'; import { ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-reg-exp', templateUrl: './reg-exp.component.html', styleUrls: ['./reg-exp.component.scss'] }) export class RegExpComponent implements OnInit { private msg: string; @ViewChild('ele') ele: ElementRef; constructor() { } ngOnInit() { } test() { const re = /apples/gi; // const re = /\d/i; const str = 'Apples are round, and apples are juicy.'; if (str.search(re) === -1) { this.msg = 'Does not contain Apples'; } else { this.msg = 'Contains Apples'; } console.log(str.match(re)); } otherTest() { const value = undefined; const value1 = null; const value2 = ''; console.log(value ? true : false); if (value) { console.log(true); } else { console.log(false); } console.log(value1 ? true : false); if (value1) { console.log(true); } else { console.log(false); } console.log(value2 ? true : false); if (value2) { console.log(true); } else { console.log(false); } } elementTest() { $(this.ele.nativeElement).html('123123'); } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path: 'autocomplete', loadChildren: './autocomplete/autocomplete.module#AutocompleteModule', }, { path: 'rxjs', loadChildren: './rxjs-demo/rxjs-demo.module#RxjsDemoModule', }, { path: 'checkBox', loadChildren: './check-box/check-box.module#CheckBoxModule', }, { path: 'datepicker', loadChildren: './datepicker/datepicker.module#DatepickerModule', }, { path: 'table', loadChildren: './table/table.module#TableModule', }, { path: 'chips', loadChildren: './chips/chips.module#ChipsModule', }, { path: 'dialog', loadChildren: './dialog/dialog.module#DialogModule', }, { path: 'select', loadChildren: './select/select.module#SelectModule', }, { path: 'tabs', loadChildren: './tabs/tabs.module#TabsModule', }, { path: 'progress', loadChildren: './progress/progress.module#ProgressModule', }, { path: 'regExp', loadChildren: './reg-exp/reg-exp.module#RegExpModule', }, { path: 'menu', loadChildren: './menu/menu.module#MenuModule', }, { path: 'other', loadChildren: './other/other.module#OtherModule', }, { path: 'e-ngx-print-demo', loadChildren: './e-ngx-print-demo/e-ngx-print-demo.module#ENgxPrintDemoModule', }, { path: 'charts', loadChildren: './ng-chart-demo/ng-chart-demo.module#NgChartDemoModule', } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/dialog/dialog.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DialogComponent } from './dialog.component'; import { DialogRoutingModule } from './dialog-routing.module'; import { MaterialModule } from '../shared/material/material.module'; import { SimpleComponent } from './simple/simple.component'; import { FormsModule } from '@angular/forms'; import { FlexLayoutModule } from '@angular/flex-layout'; @NgModule({ imports: [ CommonModule, DialogRoutingModule, MaterialModule, FormsModule, FlexLayoutModule ], entryComponents: [ SimpleComponent ], declarations: [ DialogComponent, SimpleComponent ] }) export class DialogModule { } <file_sep>/src/app/datepicker/datepicker.module.ts import { MaterialModule } from './../shared/material/material.module'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DatepickerComponent } from './datepicker.component'; import { DatepickerRoutingModule } from './datepicker-routing.module'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; @NgModule({ imports: [ CommonModule, DatepickerRoutingModule, MaterialModule, ReactiveFormsModule, FormsModule ], declarations: [DatepickerComponent] }) export class DatepickerModule { } <file_sep>/src/app/autocomplete/autocomplete.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AutocompleteRoutingModule } from './autocomplete-routing.module'; import { SimpleComponent } from './simple/simple.component'; import { MaterialModule } from '../shared/material/material.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { OverviewComponent } from './overview/overview.component'; import { AutocompleteComponent } from './autocomplete.component'; import { SetDisplayValueComponent } from './set-display-value/set-display-value.component'; import { FilterComponent } from './filter/filter.component'; @NgModule({ imports: [ CommonModule, AutocompleteRoutingModule, MaterialModule, FormsModule, ReactiveFormsModule ], declarations: [ SimpleComponent, OverviewComponent, AutocompleteComponent, SetDisplayValueComponent, FilterComponent ] }) export class AutocompleteModule { } <file_sep>/src/app/select/select.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-select', templateUrl: './select.component.html', styleUrls: ['./select.component.scss'] }) export class SelectComponent implements OnInit { animalControl = new FormControl('Fox', [Validators.required]); selectValue = 'Fox'; animals = [ { name: 'Dog', sound: 'Woof!' }, { name: 'Cat', sound: 'Meow!' }, { name: 'Cow', sound: 'Moo!' }, { name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!' }, ]; constructor() { } ngOnInit() { } } <file_sep>/src/app/rxjs-demo/rxjs-demo.component.ts import { element } from 'protractor'; import { Observable } from 'rxjs/Observable'; import { Component, OnInit, ViewChild } from '@angular/core'; import 'rxjs/add/observable/of'; import 'rxjs/add/observable/from'; import 'rxjs/add/observable/interval'; import 'rxjs/add/observable/fromEvent'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/switch'; import 'rxjs/add/operator/delay'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/first'; import 'rxjs/add/operator/last'; import 'rxjs/add/operator/switchMap'; import { MatButton } from '@angular/material'; @Component({ selector: 'app-rxjs-demo', templateUrl: './rxjs-demo.component.html', styleUrls: ['./rxjs-demo.component.scss'] }) export class RxjsDemoComponent implements OnInit { items: Array<Item> = new Array(); @ViewChild('switchButton') switchButton: MatButton; constructor() { } swithTest() { // var result = clicks.switchMap((ev) => Rx.Observable.interval(1000)); // result.subscribe(x => console.log(x)); } ngOnInit() { console.log(this.switchButton); const clicks = Observable.fromEvent(this.switchButton._elementRef.nativeElement, 'click'); // const result = clicks.switchMap((ev) => Observable.interval(1000)); const higherOrder = clicks.map((ev) => Observable.interval(1000)); const result = higherOrder.switch(); result.subscribe(x => console.log(x)); } trigger() { const obj1$ = Observable.from([1, 2, 3, 4, 5]).filter(x => x > 3); const obj2$ = Observable.of<Item>( { isFree: null, value: '-1', displayText: '- All -', isSelected: false }, { isFree: null, value: '', displayText: 'Not assigned', isSelected: false }, { isFree: true, value: '1', displayText: 'Standard', isSelected: false } ); const obj3$ = Observable.from<Item>( [ { isFree: null, value: '-1', displayText: '- All -', isSelected: false }, { isFree: null, value: '', displayText: 'Not assigned', isSelected: false }, { isFree: true, value: '1', displayText: 'Standard', isSelected: false } ] ); // obj1$.subscribe(val => console.log(val)); obj2$.filter(v => v.value === '1').subscribe(val => console.log(val)); obj3$.subscribe(val => this.items.push(val)); console.log(this.items); } } export class Item { public isFree?: boolean; public value: string; public displayText: string; public isSelected: boolean; constructor(data?: Item) { if (data) { for (const property in data) { if (data.hasOwnProperty(property)) { (<any>this)[property] = (<any>data)[property]; } } } } } <file_sep>/src/app/progress/configurable-progress-spinner/configurable-progress-spinner.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-configurable-progress-spinner', templateUrl: './configurable-progress-spinner.component.html', styleUrls: ['./configurable-progress-spinner.component.scss'] }) export class ConfigurableProgressSpinnerComponent implements OnInit { color = 'primary'; mode = 'determinate'; value = 50; constructor() { } ngOnInit() { } valueChange(value) { console.log(value); } progressChange(progress) { console.log(progress); } } <file_sep>/src/app/other/other.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Ot1Component } from './ot1/ot1.component'; import { OtherRoutingModule } from './other-routing.module'; import { TimeagoDemoComponent } from './timeago-demo/timeago-demo.component'; import { OtherComponent } from './other.component'; import { MaterialModule } from '../shared/material/material.module'; import { JqPluginDirective } from './timeago-demo/jq-plugin.directive'; @NgModule({ imports: [ CommonModule, OtherRoutingModule, MaterialModule, ], declarations: [ Ot1Component, TimeagoDemoComponent, OtherComponent, JqPluginDirective] }) export class OtherModule { } <file_sep>/src/app/reg-exp/reg-exp.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RegExpComponent } from './reg-exp.component'; import { RegExpRoutingModule } from './reg-exp-routing.module'; import { MaterialModule } from '../shared/material/material.module'; @NgModule({ imports: [ CommonModule, RegExpRoutingModule, MaterialModule ], declarations: [RegExpComponent] }) export class RegExpModule { } <file_sep>/src/app/autocomplete/set-display-value/set-display-value.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/from'; @Component({ selector: 'app-set-display-value', templateUrl: './set-display-value.component.html', styleUrls: ['./set-display-value.component.scss'] }) export class SetDisplayValueComponent implements OnInit { private displayGroup: FormGroup; options = [ new User('Mary', 'Mary1'), new User('Shelley', 'Shelley1'), new User('Igor', 'Igor1') ]; filteredOptions: Observable<User[]>; constructor(fb: FormBuilder) { this.displayGroup = fb.group({ username: [], } ); } ngOnInit() { // this.filteredOptions = Observable.from(this.options).map(_ => _); this.filteredOptions = this.displayGroup.controls['username'].valueChanges .startWith(null) .map(user => user && typeof user === 'object' ? user.name : user) .map(name => name ? this.filter(name) : this.options.slice()); console.log(this.filteredOptions); } filter(name: string): User[] { return this.options.filter(option => option.name.toLowerCase().indexOf(name.toLowerCase()) === 0); } displayFn(user: User): string { return user ? ' <span class="flag-icon flag-icon-cn"></span>' + user.name : null; } } export class User { constructor(public name: string, public text: string) { } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatButtonModule} from '@angular/material/button'; import { MatMomentDateModule } from '@angular/material-moment-adapter'; import { SelectComponent } from './select/select.component'; import { MatCardModule } from '@angular/material'; import { ChartModule } from 'angular-highcharts'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatButtonModule, MatMomentDateModule, MatCardModule, ChartModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/menu/menu.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { BaseMenuComponent } from './base-menu/base-menu.component'; import { MaterialModule } from '../shared/material/material.module'; import { FlexLayoutModule } from '@angular/flex-layout'; import { MenuRoutingModule } from './menu-routing.module'; @NgModule({ imports: [ CommonModule, MaterialModule, FlexLayoutModule, MenuRoutingModule ], declarations: [BaseMenuComponent] }) export class MenuModule { } <file_sep>/src/app/table/table.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TableComponent } from './table.component'; import { RetrievingDataThroughHttpComponent } from './retrieving-data-through-http/retrieving-data-through-http.component'; import { SortingPaginationFilteringComponent } from './sorting-pagination-filtering/sorting-pagination-filtering.component'; import { TableRoutingModule } from './table-routing.module'; import { MaterialModule } from '../shared/material/material.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MatTableModule, MatPaginatorModule, MatSortModule } from '@angular/material'; @NgModule({ imports: [ CommonModule, TableRoutingModule, MaterialModule, MatTableModule, MatPaginatorModule, MatSortModule, FormsModule, ReactiveFormsModule, HttpModule ], declarations: [ TableComponent, RetrievingDataThroughHttpComponent, SortingPaginationFilteringComponent ] }) export class TableModule { } <file_sep>/src/app/datepicker/datepicker.component.ts import { Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core'; import * as moment from 'moment'; import { FormGroup, FormBuilder } from '@angular/forms'; import { MatInput, MatDatepickerToggle } from '@angular/material'; @Component({ selector: 'app-datepicker', templateUrl: './datepicker.component.html', styleUrls: ['./datepicker.component.scss'] }) export class DatepickerComponent implements OnInit { @ViewChildren(MatInput) matInputs: QueryList<MatInput>; @ViewChild(MatInput) matInput: MatInput; disabledState = false; dp1Value: moment.Moment; private dpGroup: FormGroup; result: { dp1Value: moment.Moment, dp2Value: moment.Moment, dp3Value: moment.Moment, } = <any>[]; constructor( fb: FormBuilder ) { this.dpGroup = fb.group({ dp1Value: [] }); } change() { // this.matInputs.forEach(element => { // element.value = moment().startOf('day'); // }); this.matInputs.last.value = moment().startOf('day').toString(); this.matInput.value = moment().startOf('day').toString(); this.matInput.readonly = !this.matInput.readonly; this.disabledState = !this.disabledState; console.log(this.dpGroup.controls['dp1Value'].value); } ngOnInit() { } }
b79b306e39e50a6f99d0902635e49fb95de888ea
[ "TypeScript" ]
23
TypeScript
hzxc/material-angular-demo
e5bc9ddbe99bcc7768d93227187e09f444c1454d
79ae58f65c8ad8349ac412072a91df93ad2e33c8
refs/heads/main
<file_sep>//import {Mobile} from './Mobile'; // let movil_1:Mobile = new Mobile('movil 1','nokia 3210', 'nokia', 150,'gris',false,5545,3); // let movil_2:Mobile = new Mobile('movil 2','iphone 3g', 'apple', 300,'blanco',false,6978,40); // let movil_3:Mobile = new Mobile('movil 3','samsung galaxy', 'samsung', 500,'azul',true,9854,120); // console.log(movil_1); // console.log(movil_2); // console.log(movil_3); // movil_1.is5G = true; // movil_1.cameraNumber = 4; // console.log(movil_1);<file_sep># OOPReview clase de prueba <file_sep>import {Mobile} from './Mobile'; import {MobileLibrary} from './MobileLibrary'; let movil_1:Mobile = new Mobile('movil 1', 'nokia 3210', 'nokia', 1, 'gris', false, 0, 3); let movil_2:Mobile = new Mobile('movil 2', 'iphone 3g', 'apple', 3,'blanco',false, 1, 40); let movil_3:Mobile = new Mobile('movil 3', 'samsung galaxy', 'samsung', 3,'azul', true, 1, 120); let movil_4:Mobile = new Mobile('movil 4', 'huawei mate 40 pro', 'huawei', 5, 'negro', true, 2, 1199); let moviles:Mobile[] = [movil_1, movil_2, movil_3, movil_4]; let library:MobileLibrary = new MobileLibrary('library', 'madrid', moviles); let p_print = ():void => { console.log(library.getName()); console.log(library.getLocation()); console.log(library.getMobiles()); console.log(library.getTotalPrice()); console.log(''); } p_print(); library.setName('<NAME>'); library.setLocation('teruel'); library.setMobiles([movil_1,movil_2]); library.setTotalPrice(123); p_print(); library.printLibrary();//el precio total es 123 porque antes lo he cambiado con el setter.<file_sep>import {Mobile} from './Mobile'; export class MobileLibrary { private name:string; private location:string; private mobiles:Mobile[]; private totalPrice:number; constructor(name:string, location:string, mobiles:Mobile[]) { this.name = name; this.location = location; this.mobiles = mobiles; this.totalPrice = this.totalPriceCalculation(); } public getName():string { return this.name; } public getLocation():string { return this.location; } public getMobiles():Mobile[] { return this.mobiles; } public getTotalPrice():number { return this.totalPrice; } public setName(name:string):void { this.name = name; } public setLocation(location:string):void { this.location = location; } public setMobiles(mobiles:Mobile[]):void { this.mobiles = mobiles; } public setTotalPrice(totalPrice:number):void { this.totalPrice = totalPrice; } private totalPriceCalculation():number { let totalPrice = 0; for(let i=0;i<this.mobiles.length;i++) { totalPrice += this.mobiles[i].getPrice(); } return totalPrice; } public printLibrary():void { console.log('This is all my mobiles'); for(let i=0;i<this.mobiles.length;i++) { this.mobiles[i].printMobile(); } console.log('..........................'); console.log(`Price overall: ${this.totalPrice}`); } }<file_sep>import {Mobile} from './Mobile'; let movil_1:Mobile = new Mobile('movil 1','nokia 3210', 'nokia', 150,'gris',false,5545,3); let movil_2:Mobile = new Mobile('movil 2','iphone 3g', 'apple', 300,'blanco',false,6978,40); let movil_3:Mobile = new Mobile('movil 3','samsung galaxy', 'samsung', 500,'azul',true,9854,120); console.log(movil_1); console.log(movil_2); console.log(movil_3); movil_1.setIs5G(true); movil_1.setCameraNumber(4); console.log(movil_1); let moviles:Mobile[] = [movil_1,movil_2,movil_3]; for(let i=0;i<moviles.length;i++) { moviles[i].printMobile(); }
bc5e5a0f5823a335588918af42f8962e5dd8bac6
[ "Markdown", "TypeScript" ]
5
TypeScript
JaviRamosDev/OOPReview
226debd20f0083b4677f71b6a4714a079c593f97
bd2da60661911ef07ab7bf09ab8cec73a4457c0e
refs/heads/main
<file_sep>class KshellDataStructureError(Exception): """ Raise when KSHELL data file has unexpected structure / syntax. """<file_sep># kshell-utilities Handy utilities for processing nuclear shell model data from `KSHELL`. Se the [KSHELL repository](https://github.com/GaffaSnobb/kshell) for installation and usage instructions for `KSHELL`. ## Installation Install from the PyPi repository ``` bash pip install kshell-utilities ``` Or, for the very latest version, clone this repository to your downloads directory. cd to the root directory of this repository and run ``` pip install . ``` ## Usage Please see the *How to use the output from KSHELL* section of the Wiki in the `KSHELL` repository for an introduction on how to use `kshell-utilities`: https://github.com/GaffaSnobb/kshell/wiki/How-to-use-the-output-from-KSHELL ## Credits KSHELL is created by <NAME> https://arxiv.org/abs/1310.5431. Code in this repository is built upon tools created by <NAME>: https://github.com/jorgenem/kshell_public. <file_sep>from __future__ import annotations import time, sys, ast, warnings from fractions import Fraction from typing import TextIO import numpy as np from .kshell_exceptions import KshellDataStructureError from .data_structures import ( Interaction, Partition, OrbitalParameters, Configuration ) from .parameters import ( spectroscopic_conversion, shell_model_order, flags ) from .partition_tools import ( _calculate_configuration_parity, _sanity_checks, configuration_energy ) def load_interaction( filename_interaction: str, interaction: Interaction, ): interaction.name = filename_interaction with open(filename_interaction, "r") as infile: """ Extract information from the interaction file about the orbitals in the model space. """ for line in infile: """ Example ------- ! GXPF1A pf-shell ! <NAME>, <NAME>, <NAME>, and <NAME>, ! Eur. Phys. J. A 25, Suppl. 1, 499 (2005). ! ! default input parameters !namelist eff_charge = 1.5, 0.5 !namelist orbs_ratio = 2, 3, 4, 6, 7, 8 ! ! model space 4 4 20 20 ... """ if line[0] != "!": tmp = line.split() interaction.model_space_proton.n_orbitals = int(tmp[0]) interaction.model_space_neutron.n_orbitals = int(tmp[1]) interaction.model_space.n_orbitals = ( interaction.model_space_proton.n_orbitals + interaction.model_space_neutron.n_orbitals ) interaction.n_core_protons = int(tmp[2]) interaction.n_core_neutrons = int(tmp[3]) break for line in infile: """ Example ------- 4 4 20 20 1 0 3 7 -1 ! 1 = p 0f_7/2 2 1 1 3 -1 ! 2 = p 1p_3/2 3 0 3 5 -1 ! 3 = p 0f_5/2 4 1 1 1 -1 ! 4 = p 1p_1/2 5 0 3 7 1 ! 5 = n 0f_7/2 6 1 1 3 1 ! 6 = n 1p_3/2 7 0 3 5 1 ! 7 = n 0f_5/2 8 1 1 1 1 ! 8 = n 1p_1/2 ! interaction ... """ if line[0] == "!": break idx, n, l, j, tz = [int(i) for i in line.split("!")[0].split()] idx -= 1 nucleon = "p" if tz == -1 else "n" name = f"{n}{spectroscopic_conversion[l]}{j}" tmp_orbital = OrbitalParameters( idx = idx, n = n, l = l, j = j, tz = tz, nucleon = nucleon, name = f"{nucleon}{name}", parity = (-1)**l, order = shell_model_order[name], ho_quanta = 2*n + l ) interaction.model_space.orbitals.append(tmp_orbital) interaction.model_space.major_shell_names.add(shell_model_order[name].major_shell_name) if tz == -1: interaction.model_space_proton.orbitals.append(tmp_orbital) interaction.model_space_proton.major_shell_names.add(shell_model_order[name].major_shell_name) elif tz == +1: interaction.model_space_neutron.orbitals.append(tmp_orbital) interaction.model_space_neutron.major_shell_names.add(shell_model_order[name].major_shell_name) else: msg = f"Valid values for tz are -1 and +1, got {tz=}" raise ValueError(msg) for line in infile: """ Example ------- ! GCLSTsdpfsdgix5pn.int ! p-n formalism 24 0 ... """ if line[0] != "!": tmp = line.split() if int(tmp[1]) != 0: raise NotImplementedError interaction.n_spe = int(tmp[0]) break for line in infile: """ Example ------- 1 1 -8.62400 2 2 -5.67930 3 3 -1.38290 4 4 -4.13700 5 5 -8.62400 6 6 -5.67930 7 7 -1.38290 8 8 -4.13700 518 1 42 -0.30000 ... """ tmp = line.split() if len(tmp) != 3: break interaction.spe.append(float(tmp[2])) try: interaction.n_tbme = int(tmp[0]) interaction.fmd_mass = int(tmp[2]) interaction.fmd_power = float(tmp[3]) except IndexError: """ I dont really know what this is yet. """ msg = "Interactions with no mass dependence have not yet been implemented." raise NotImplementedError(msg) for line in infile: """ NOTE: This way of structuring the TBMEs is taken from espe.py. """ i0, i1, i2, i3, j, tbme = line.split() i0 = int(i0) - 1 i1 = int(i1) - 1 i2 = int(i2) - 1 i3 = int(i3) - 1 j = int(j) tbme = float(tbme) if (i0, i1, i2, i3, j) in interaction.tbme: """ I dont yet understand why I should check the TBME value when I already know that the indices are the same. This is how it is done in espe.py (why check > 1.e-3 and not < 1.e-3?): if (i,j,k,l,J) in vtb: if abs( v - vtb[i,j,k,l,J] )>1.e-3: print( 'WARNING duplicate TBME', i+1,j+1,k+1,l+1,J,v,vtb[(i,j,k,l,J)] ) """ warnings.warn(f"Duplicate TBME! {i0 + 1}, {i1 + 1}, {i2 + 1}, {i3 + 1}, {j}, {tbme}, {interaction.tbme[(i0, i1, i2, i3, j)]}") interaction.tbme[(i0, i1, i2, i3, j)] = tbme s01 = (-1)**((interaction.model_space.orbitals[i0].j + interaction.model_space.orbitals[i1].j)/2 - j + 1) s23 = (-1)**((interaction.model_space.orbitals[i2].j + interaction.model_space.orbitals[i3].j)/2 - j + 1) if i0 != i1: interaction.tbme[(i1, i0, i2, i3, j)] = tbme*s01 if i2 != i3: interaction.tbme[(i0, i1, i3, i2, j)] = tbme*s23 if (i0 != i1) and (i2 != i3): interaction.tbme[(i1, i0, i3, i2, j)] = tbme*s01*s23 if (i0, i1) != (i2, i3): interaction.tbme[(i2, i3, i0, i1, j)] = tbme if i0 != i1: interaction.tbme[(i2, i3, i1, i0, j)] = tbme*s01 if i2 != i3: interaction.tbme[(i3, i2, i0, i1, j)] = tbme*s23 if (i0 != i1) and (i2!=i3): interaction.tbme[(i3, i2, i1, i0, j)] = tbme*s01*s23 assert len(interaction.spe) == interaction.n_spe # assert len(interaction.tbme) == interaction.n_tbme interaction.vm = np.zeros((interaction.model_space.n_orbitals, interaction.model_space.n_orbitals), dtype=float) for i0 in range(interaction.model_space.n_orbitals): """ Non-diagonal. TODO: Make a better description when I figure out what vm is. """ for i1 in range(interaction.model_space.n_orbitals): j_min = abs(interaction.model_space.orbitals[i0].j - interaction.model_space.orbitals[i1].j)//2 j_max = (interaction.model_space.orbitals[i0].j + interaction.model_space.orbitals[i1].j)//2 skip = 2 if (i0 == i1) else 1 v: float = 0.0 d: int = 0 for j in range(j_min, j_max + 1, skip): """ Using j_max + 1, not j_max + skip, because when i0 == i1 both nucleons are in the same orbital and they cannot both have the same angular momentum z component. skip = 2 when i0 == i1 because only even numbered j are allowed when identical particles are in the same orbital. """ try: tbme = interaction.tbme[(i0, i1, i0, i1, j)] except KeyError: """ I am unsure if this should be allowed at all and should rather raise an exception. """ warnings.warn(f"TBME entry not found! ({i0 + 1}, {i1 + 1}, {i0 + 1}, {i1 + 1}, {j})") tbme = 0.0 degeneracy = 2*j + 1 v += degeneracy*tbme d += degeneracy interaction.vm[i0, i1] = v/d interaction.model_space.n_major_shells = len(interaction.model_space.major_shell_names) interaction.model_space_proton.n_major_shells = len(interaction.model_space_proton.major_shell_names) interaction.model_space_neutron.n_major_shells = len(interaction.model_space_neutron.major_shell_names) if not all(orb.idx == i for i, orb in enumerate(interaction.model_space.orbitals)): """ Make sure that the list indices are the same as the orbit indices. """ msg = ( "The orbitals in the model space are not indexed correctly!" ) raise KshellDataStructureError(msg) def load_partition( filename_partition: str, interaction: Interaction, partition_proton: Partition, partition_neutron: Partition, partition_combined: Partition, ) -> str: header: str = "" with open(filename_partition, "r") as infile: # truncation_info: str = infile.readline() # Eg. hw trucnation, min hw = 0 , max hw = 1 # hw_min, hw_max = [int(i.split("=")[1].strip()) for i in truncation_info.split(",")[1:]] # NOTE: No idea what happens if no hw trunc is specified. for line in infile: """ Extract the information from the header before partitions are specified. Example: # hw trucnation, min hw = 0 , max hw = 1 # partition file of gs8.snt Z=20 N=31 parity=-1 20 31 -1 # num. of proton partition, neutron partition 86 4 # proton partition ... """ if "#" not in line: tmp = [int(i) for i in line.split()] try: """ For example: 20 31 -1 """ n_valence_protons, n_valence_neutrons, parity_partition = tmp partition_proton.parity = parity_partition partition_neutron.parity = parity_partition partition_combined.parity = parity_partition interaction.model_space.n_valence_nucleons = n_valence_protons + n_valence_neutrons interaction.model_space_proton.n_valence_nucleons = n_valence_protons interaction.model_space_neutron.n_valence_nucleons = n_valence_neutrons except ValueError: """ For example: 86 4 """ n_proton_configurations, n_neutron_configurations = tmp infile.readline() # Skip header. break header += line ho_quanta_min: int = +1000 # The actual number of harmonic oscillator quanta will never be smaller or larger than these values. ho_quanta_max: int = -1000 for line in infile: """ Extract proton configurations. """ if "# neutron partition" in line: break configuration = [int(i) for i in line.split()[1:]] parity_tmp = _calculate_configuration_parity( configuration = configuration, model_space = interaction.model_space_proton.orbitals ) if parity_tmp == -1: partition_proton.n_existing_negative_configurations += 1 elif parity_tmp == +1: partition_proton.n_existing_positive_configurations += 1 assert len(interaction.model_space_proton.orbitals) == len(configuration) ho_quanta_tmp = sum([ # The number of harmonic oscillator quanta for each configuration. n*orb.ho_quanta for n, orb in zip(configuration, interaction.model_space_proton.orbitals) ]) ho_quanta_min = min(ho_quanta_min, ho_quanta_tmp) ho_quanta_max = max(ho_quanta_max, ho_quanta_tmp) partition_proton.configurations.append( Configuration( configuration = configuration, parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = None, is_original = True, ) ) partition_proton.ho_quanta_min_this_parity = ho_quanta_min partition_proton.ho_quanta_max_this_parity = ho_quanta_max ho_quanta_min: int = +1000 # Reset for neutrons. ho_quanta_max: int = -1000 for line in infile: """ Extract neutron configurations. """ if "# partition of proton and neutron" in line: break configuration = [int(i) for i in line.split()[1:]] parity_tmp = _calculate_configuration_parity( configuration = configuration, model_space = interaction.model_space_neutron.orbitals ) if parity_tmp == -1: partition_neutron.n_existing_negative_configurations += 1 elif parity_tmp == +1: partition_neutron.n_existing_positive_configurations += 1 assert len(interaction.model_space_neutron.orbitals) == len(configuration) ho_quanta_tmp = sum([ # The number of harmonic oscillator quanta for each configuration. n*orb.ho_quanta for n, orb in zip(configuration, interaction.model_space_neutron.orbitals) ]) ho_quanta_min = min(ho_quanta_min, ho_quanta_tmp) ho_quanta_max = max(ho_quanta_max, ho_quanta_tmp) partition_neutron.configurations.append( Configuration( configuration = configuration, parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = None, is_original = True, ) ) partition_neutron.ho_quanta_min_this_parity = ho_quanta_min partition_neutron.ho_quanta_max_this_parity = ho_quanta_max ho_quanta_min: int = +1000 # Reset for combined. ho_quanta_max: int = -1000 n_combined_configurations = int(infile.readline()) for line in infile: """ Extract the combined pn configurations. """ proton_idx, neutron_idx = line.split() proton_idx = int(proton_idx) - 1 neutron_idx = int(neutron_idx) - 1 parity_tmp = partition_proton.configurations[proton_idx].parity*partition_neutron.configurations[neutron_idx].parity assert parity_partition == parity_tmp if parity_tmp == -1: partition_combined.n_existing_negative_configurations += 1 elif parity_tmp == +1: partition_combined.n_existing_positive_configurations += 1 ho_quanta_tmp = ( partition_proton.configurations[proton_idx].ho_quanta + partition_neutron.configurations[neutron_idx].ho_quanta ) ho_quanta_min = min(ho_quanta_min, ho_quanta_tmp) ho_quanta_max = max(ho_quanta_max, ho_quanta_tmp) energy = configuration_energy( interaction = interaction, proton_configuration = partition_proton.configurations[proton_idx], neutron_configuration = partition_neutron.configurations[neutron_idx], ) partition_combined.configurations.append( Configuration( configuration = [proton_idx, neutron_idx], parity = parity_partition, ho_quanta = ho_quanta_tmp, energy = energy, is_original = True, ) ) partition_combined.ho_quanta_min_this_parity = ho_quanta_min partition_combined.ho_quanta_max_this_parity = ho_quanta_max partition_combined.ho_quanta_min = min(ho_quanta_min, partition_combined.ho_quanta_min_opposite_parity) partition_combined.ho_quanta_max = max(ho_quanta_max, partition_combined.ho_quanta_max_opposite_parity) energies = [configuration.energy for configuration in partition_combined.configurations] partition_combined.min_configuration_energy = min(energies) partition_combined.max_configuration_energy = max(energies) partition_combined.max_configuration_energy_original = partition_combined.max_configuration_energy _sanity_checks( partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, interaction = interaction, ) assert len(partition_proton.configurations) == n_proton_configurations assert len(partition_neutron.configurations) == n_neutron_configurations assert len(partition_combined.configurations) == n_combined_configurations assert ( partition_proton.n_existing_negative_configurations + partition_proton.n_existing_positive_configurations + partition_proton.n_new_negative_configurations + partition_proton.n_new_positive_configurations ) == n_proton_configurations assert ( partition_neutron.n_existing_negative_configurations + partition_neutron.n_existing_positive_configurations + partition_neutron.n_new_negative_configurations + partition_neutron.n_new_positive_configurations ) == n_neutron_configurations assert ( partition_combined.n_existing_negative_configurations + partition_combined.n_existing_positive_configurations + partition_combined.n_new_negative_configurations + partition_combined.n_new_positive_configurations ) == n_combined_configurations return header def _parity_string_to_integer(parity: str): if parity == "+": res = 1 elif parity == "-": res = -1 else: msg = f"Invalid parity read from file. Got: '{parity}'." raise KshellDataStructureError(msg) return res def _load_energy_levels(infile: TextIO) -> tuple[list, int]: """ Load excitation energy, spin and parity into a list of structure: levels = [[energy, spin, parity], ...]. Parameters ---------- infile : TextIO The KSHELL summary file at the starting position of the level data. Returns ------- levels : list List of level data. negative_spin_counts : int The number of negative spin levels encountered. Example ------- Energy levels N J prty N_Jp T E(MeV) Ex(MeV) log-file 1 5/2 + 1 3/2 -16.565 0.000 log_O19_sdpf-mu_m1p.txt 2 3/2 + 1 3/2 -15.977 0.588 log_O19_sdpf-mu_m1p.txt 3 1/2 + 1 3/2 -15.192 1.374 log_O19_sdpf-mu_m1p.txt 4 9/2 + 1 3/2 -13.650 2.915 log_O19_sdpf-mu_m1p.txt 5 7/2 + 1 3/2 -13.267 3.298 log_O19_sdpf-mu_m1p.txt 6 5/2 + 2 3/2 -13.074 3.491 log_O19_sdpf-mu_m1p.txt """ levels = [] negative_spin_counts = 0 for _ in range(3): infile.readline() for line in infile: try: tmp = line.split() if tmp[1] == "-1": """ -1 spin states in the KSHELL data file indicates bad states which should not be included. """ negative_spin_counts += 1 # Debug. continue parity = 1 if tmp[2] == "+" else -1 energy = float(tmp[5]) spin = 2*float(Fraction(tmp[1])) idx = int(tmp[3]) levels.append([energy, spin, parity, idx]) except IndexError: """ End of energies. """ break return levels, negative_spin_counts def _load_transition_probabilities_old(infile: TextIO) -> tuple[list, int]: """ For summary files with old syntax (pre 2021-11-24). Parameters ---------- infile : TextIO The KSHELL summary file at the starting position of either of the transition probability sections. Returns ------- transitions : list List of transition data. negative_spin_counts : int The number of negative spin levels encountered. """ negative_spin_counts = 0 transitions = [] for _ in range(2): infile.readline() for line in infile: try: """ Example of possible lines in file: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 2+(11) 18.393 2+(10) 17.791 0.602 0.1( 0.0) 0.1( 0.0) 3/2+( 1) 0.072 5/2+( 1) 0.000 0.071 0.127( 0.07) 0.084( 0.05) 2+(10) 17.791 2+( 1) 5.172 12.619 0.006( 0.00) 0.006( 0.00) 3+( 8) 19.503 2+(11) 18.393 1.111 0.000( 0.00) 0.000( 0.00) 1+( 7) 19.408 2+( 9) 16.111 3.297 0.005( 0.00) 0.003( 0.00) 5.0+(60) 32.170 4.0+(100) 31.734 0.436 0.198( 0.11) 0.242( 0.14) 4.0-( 3) 3.191 3.0+(10) 3.137 0.054 0.0( 0.0) 0.0( 0.0) 0.0+(46)', '47.248', '1.0+(97)', '45.384', '1.864', '23.973(13.39)', '7.991(', '4.46) """ tmp = line.split() len_tmp = len(tmp) case_ = None # Used for identifying which if-else case reads wrong. # Location of initial parity is common for all cases. parity_idx = tmp[0].index("(") - 1 # Find index of initial parity. parity_initial = 1 if tmp[0][parity_idx] == "+" else -1 parity_initial_symbol = tmp[0][parity_idx] # Location of initial spin is common for all cases. spin_initial = float(Fraction(tmp[0][:parity_idx])) if (tmp[1][-1] != ")") and (tmp[3][-1] != ")") and (len_tmp == 9): """ Example: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 2+(11) 18.393 2+(10) 17.791 0.602 0.1( 0.0) 0.1( 0.0) 5.0+(60) 32.170 4.0+(100) 31.734 0.436 0.198( 0.11) 0.242( 0.14) """ case_ = 0 E_gamma = float(tmp[4]) Ex_initial = float(tmp[1]) reduced_transition_prob_decay = float(tmp[5][:-1]) reduced_transition_prob_excite = float(tmp[7][:-1]) parity_final_symbol = tmp[2].split("(")[0][-1] spin_final = float(Fraction(tmp[2].split(parity_final_symbol)[0])) Ex_final = float(tmp[3]) idx_initial = int(tmp[0].split("(")[1].split(")")[0]) idx_final = int(tmp[2].split("(")[1].split(")")[0]) elif (tmp[1][-1] != ")") and (tmp[3][-1] == ")") and (len_tmp == 10): """ Example: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 2+(10) 17.791 2+( 1) 5.172 12.619 0.006( 0.00) 0.006( 0.00) """ case_ = 1 E_gamma = float(tmp[5]) Ex_initial = float(tmp[1]) reduced_transition_prob_decay = float(tmp[6][:-1]) reduced_transition_prob_excite = float(tmp[8][:-1]) parity_final_symbol = tmp[2].split("(")[0][-1] # spin_final = float(Fraction(tmp[2][:-2])) spin_final = float(Fraction(tmp[2].split(parity_final_symbol)[0])) Ex_final = float(tmp[4]) idx_initial = int(tmp[0].split("(")[1].split(")")[0]) idx_final = int(tmp[3][0]) elif (tmp[1][-1] == ")") and (tmp[4][-1] != ")") and (len_tmp == 10): """ Example: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 3+( 8) 19.503 2+(11) 18.393 1.111 0.000( 0.00) 0.000( 0.00) 1.0+( 1) 5.357 0.0+(103) 0.000 5.357 0.002( 0.00) 0.007( 0.00) 4.0-( 3) 3.191 3.0+(10) 3.137 0.054 0.0( 0.0) 0.0( 0.0) """ case_ = 2 E_gamma = float(tmp[5]) Ex_initial = float(tmp[2]) reduced_transition_prob_decay = float(tmp[6][:-1]) reduced_transition_prob_excite = float(tmp[8][:-1]) parity_final_symbol = tmp[3].split("(")[0][-1] spin_final = float(Fraction(tmp[3].split(parity_final_symbol)[0])) Ex_final = float(tmp[4]) idx_initial = int(tmp[1][0]) idx_final = int(tmp[3].split("(")[1].split(")")[0]) elif (tmp[1][-1] == ")") and (tmp[4][-1] == ")") and (len_tmp == 11): """ Example: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 1+( 7) 19.408 2+( 9) 16.111 3.297 0.005( 0.00) 0.003( 0.00) """ case_ = 3 E_gamma = float(tmp[6]) Ex_initial = float(tmp[2]) reduced_transition_prob_decay = float(tmp[7][:-1]) reduced_transition_prob_excite = float(tmp[9][:-1]) parity_final_symbol = tmp[3].split("(")[0][-1] # spin_final = float(Fraction(tmp[3][:-2])) spin_final = float(Fraction(tmp[3].split(parity_final_symbol)[0])) Ex_final = float(tmp[5]) idx_initial = int(tmp[1][0]) idx_final = int(tmp[4][0]) elif (tmp[5][-1] == ")") and (tmp[2][-1] == ")") and (len_tmp == 8): """ Example: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 0.0+(46) 47.248 1.0+(97) 45.384 1.864 23.973(13.39) 7.991( 4.46) """ case_ = 4 E_gamma = float(tmp[4]) Ex_initial = float(tmp[1]) reduced_transition_prob_decay = float(tmp[5].split("(")[0]) reduced_transition_prob_excite = float(tmp[6][:-1]) parity_final_symbol = tmp[2].split("(")[0][-1] spin_final = float(Fraction(tmp[2].split(parity_final_symbol)[0])) Ex_final = float(tmp[3]) idx_initial = int(tmp[0].split("(")[1].split(")")[0]) idx_final = int(tmp[2].split("(")[1].split(")")[0]) else: msg = "ERROR: Structure not accounted for!" msg += f"\n{line=}" raise KshellDataStructureError(msg) if parity_final_symbol == "+": parity_final = 1 elif parity_final_symbol == "-": parity_final = -1 else: msg = f"Could not properly read the final parity! {case_=}" raise KshellDataStructureError(msg) if (spin_final == -1) or (spin_initial == -1): """ -1 spin states in the KSHELL data file indicates bad states which should not be included. """ negative_spin_counts += 1 # Debug. continue # reduced_transition_prob_decay_list.append([ # 2*spin_initial, parity_initial, Ex_initial, 2*spin_final, # parity_final, Ex_final, E_gamma, reduced_transition_prob_decay, # reduced_transition_prob_excite # ]) transitions.append([ 2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, reduced_transition_prob_decay, reduced_transition_prob_excite ]) except ValueError as err: """ One of the float conversions failed indicating that the structure of the line is not accounted for. """ msg = "\n" + err.__str__() + f"\n{case_=}" + f"\n{line=}" raise KshellDataStructureError(msg) except IndexError: """ End of probabilities. """ break return transitions, negative_spin_counts def _load_transition_probabilities(infile: TextIO) -> tuple[list, int]: """ For summary files with new syntax (post 2021-11-24). Parameters ---------- infile : TextIO The KSHELL summary file at the starting position of either of the transition probability sections. Returns ------- transitions : list List of transition data. negative_spin_counts : int The number of negative spin levels encountered. Example ------- B(E2) ( > -0.0 W.u.) mass = 50 1 W.u. = 10.9 e^2 fm^4 e^2 fm^4 (W.u.) J_i pi_i idx_i Ex_i J_f pi_f idx_f Ex_f dE B(E2)-> B(E2)->[wu] B(E2)<- B(E2)<-[wu] 5 + 1 0.036 6 + 1 0.000 0.036 70.43477980 6.43689168 59.59865983 5.44660066 4 + 1 0.074 6 + 1 0.000 0.074 47.20641983 4.31409897 32.68136758 2.98668391 """ negative_spin_counts = 0 transitions = [] for _ in range(2): infile.readline() for line in infile: line_split = line.split() if not line_split: break spin_initial = float(Fraction(line_split[0])) parity_initial = _parity_string_to_integer(line_split[1]) idx_initial = int(line_split[2]) Ex_initial = float(line_split[3]) spin_final = float(Fraction(line_split[4])) parity_final = _parity_string_to_integer(line_split[5]) idx_final = int(line_split[2]) Ex_final = float(line_split[7]) E_gamma = float(line_split[8]) reduced_transition_prob_decay = float(line_split[9]) reduced_transition_prob_excite = float(line_split[11]) if (spin_final < 0) or (spin_initial < 0): """ -1 spin states in the KSHELL data file indicates bad states which should not be included. """ negative_spin_counts += 1 # Debug. continue # reduced_transition_prob_decay_list.append([ # 2*spin_initial, parity_initial, Ex_initial, 2*spin_final, # parity_final, Ex_final, E_gamma, reduced_transition_prob_decay, # reduced_transition_prob_excite # ]) transitions.append([ 2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, reduced_transition_prob_decay, reduced_transition_prob_excite ]) return transitions, negative_spin_counts def _generic_loader(arg_list: list) -> tuple[list, int]: """ Constructed for parallel loading, but can be used in serial as well. """ fname, condition, loader, thread_idx = arg_list if flags["parallel"]: print(f"Thread {thread_idx} loading {condition} values...") else: print(f"Loading {condition} values...") load_time = time.perf_counter() with open(fname, "r") as infile: for line in infile: if condition in line: ans = loader(infile) break else: ans = [], 0 load_time = time.perf_counter() - load_time if not ans[0]: print(f"No {condition} transitions found in {fname}") else: print(f"Thread {thread_idx} finished loading {condition} values in {load_time:.2f} s") return ans def _load_transition_probabilities_jem(infile: TextIO) -> tuple[list, int]: """ JEM has modified the summary files from KSHELL with a slightly different syntax. This function reads that syntax. Note also that these summary files have 2*J, not J. Parameters ---------- infile : TextIO The KSHELL summary file at the starting position of either of the transition probability sections. Returns ------- transitions : list List of transition data. negative_spin_counts : int The number of negative spin levels encountered. Example ------- B(M1) larger than 1e-08 mu_N^2 2Ji Ei 2Jf Ef Ex B(M1)-> B(M1)<- 2 - ( 1) -35.935 0 - ( 8) -35.583 0.352 0.00428800 0.01286400 0 - ( 8) -35.583 2 - ( 2) -35.350 0.233 0.45171030 0.15057010 0 - ( 8) -35.583 2 - ( 3) -34.736 0.847 0.04406500 0.01468830 """ negative_spin_counts = 0 transitions = [] infile.readline() # Skip header line. for line in infile: line_split = line.split() if not line_split: break spin_initial = int(line_split[0]) parity_initial = _parity_string_to_integer(line_split[1]) idx_initial = int(line_split[3].strip(")")) Ex_initial = float(line_split[4]) spin_final = int(line_split[5]) parity_final = _parity_string_to_integer(line_split[6]) idx_final = int(line_split[8].strip(")")) Ex_final = float(line_split[9]) E_gamma = float(line_split[10]) reduced_transition_prob_decay = float(line_split[11]) reduced_transition_prob_excite = float(line_split[12]) if (spin_final < 0) or (spin_initial < 0): """ -1 spin states in the KSHELL data file indicates bad states which should not be included. """ negative_spin_counts += 1 # Debug. continue transitions.append([ spin_initial, parity_initial, idx_initial, Ex_initial, spin_final, parity_final, idx_final, Ex_final, E_gamma, reduced_transition_prob_decay, reduced_transition_prob_excite ]) return transitions, negative_spin_counts <file_sep>from __future__ import annotations import os, sys, multiprocessing, hashlib, ast, time, re from fractions import Fraction from typing import Union, Callable, Tuple, Iterable from itertools import chain import numpy as np import numba import matplotlib.pyplot as plt import seaborn as sns from .collect_logs import collect_logs from .kshell_exceptions import KshellDataStructureError from .parameters import atomic_numbers, flags from .general_utilities import ( level_plot, level_density, gamma_strength_function_average, porter_thomas, isotope ) from .loaders import ( _generic_loader, _load_energy_levels, _load_transition_probabilities, _load_transition_probabilities_old, _load_transition_probabilities_jem ) def _generate_unique_identifier(path: str) -> str: """ Generate a unique identifier based on the shell script and the save_input file from KSHELL. Parameters ---------- path : str The path to a summary file or a directory with a summary file. """ shell_file_content = "" save_input_content = "" msg = "Not able to generate unique identifier!" if os.path.isfile(path): """ If a file is specified, extract the directory from the path. """ directory = path.rsplit("/", 1)[0] if directory == path: """ Example: path is 'summary.txt' """ directory = "." elif os.path.isdir(path): directory = path for elem in os.listdir(directory): """ Loop over all elements in the directory and find the shell script and save_input file. """ try: if elem.endswith(".sh"): with open(f"{directory}/{elem}", "r") as infile: shell_file_content += infile.read() elif "save_input_ui.txt" in elem: with open(f"{directory}/{elem}", "r") as infile: save_input_content += infile.read() except UnicodeDecodeError: msg = f"Skipping {elem} for tmp file unique identifier due to UnicodeDecodeError." msg += " Are you sure this file is supposed to be in this directory?" print(msg) continue if (shell_file_content == "") and (save_input_content == ""): print(msg) return hashlib.sha1((shell_file_content + save_input_content).encode()).hexdigest() class ReadKshellOutput: """ Read `KSHELL` data files and store the values as instance attributes. Attributes ---------- levels : np.ndarray Array containing energy, spin, and parity for each excited state. [[E, 2*spin, parity, idx], ...]. idx counts how many times a state of that given spin and parity has occurred. The first 0+ state will have an idx of 1, the second 0+ will have an idx of 2, etc. transitions_BE1 : np.ndarray Transition data for BE1 transitions. Structure: NEW: [2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] OLD NEW: [2*spin_initial, parity_initial, Ex_initial, 2*spin_final, parity_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] OLD: Mx8 array containing [2*spin_final, parity_initial, Ex_final, 2*spin_initial, parity_initial, Ex_initial, E_gamma, B(.., i->f)]. transitions_BM1 : np.ndarray Transition data for BM1 transitions. Same structure as BE1. transitions_BE2 : np.ndarray Transition data for BE2 transitions. Same structure as BE1. """ def __init__(self, path: str, load_and_save_to_file: bool, old_or_new: str): """ Parameters ---------- path : string Path of `KSHELL` output file directory, or path to a specific `KSHELL` data file. load_and_save_to_file : bool Toggle saving data as `.npy` files on / off. If `overwrite`, saved `.npy` files are overwritten. old_or_new : str Choose between old and new summary file syntax. All summary files generated pre 2021-11-24 use old style. New: J_i pi_i idx_i Ex_i J_f pi_f idx_f Ex_f dE B(E2)-> B(E2)->[wu] B(E2)<- B(E2)<-[wu] 5 + 1 0.036 6 + 1 0.000 0.036 70.43477980 6.43689168 59.59865983 5.44660066 Old: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 2+(11) 18.393 2+(10) 17.791 0.602 0.1( 0.0) 0.1( 0.0) """ self.path = path.rstrip("/") # Just in case, prob. not necessary. self.load_and_save_to_file = load_and_save_to_file self.old_or_new = old_or_new # Some attributes might not be altered, depending on the input file. # self.fname_ptn = None # I'll fix .pnt reading when the functionality is actually needed. # self.fname_summary = None # self.proton_partition = None # self.neutron_partition = None # self.truncation = None self.nucleus = None self.interaction = None self.levels = None self.transitions_BM1 = None self.transitions_BE2 = None self.transitions_BE1 = None self.npy_path = "tmp" # Directory for storing .npy files. # Debug. self.negative_spin_counts = np.array([0, 0, 0, 0]) # The number of skipped -1 spin states for [levels, BM1, BE2, BE1]. if isinstance(self.load_and_save_to_file, str) and (self.load_and_save_to_file != "overwrite"): msg = "Allowed values for 'load_and_save_to_file' are: 'True', 'False', 'overwrite'." msg += f" Got '{self.load_and_save_to_file}'." raise ValueError(msg) if os.path.isdir(self.path): """ If input 'path' is a directory. Look for summaries. """ summaries = [i for i in os.listdir(self.path) if "summary" in i] if not summaries: """ No summaries found, call collect_logs. """ self.fname_summary = collect_logs( path = self.path, old_or_new = "both" ) self.path_summary = f"{self.path}/{self.fname_summary}" elif len(summaries) > 1: msg = f"Several summaries found in {self.path}. Please specify path" msg += " directly to the summary file you want to load." raise RuntimeError(msg) else: self.fname_summary = summaries[0] # Just filename. self.path_summary = f"{self.path}/{summaries[0]}" # Complete path (maybe relative). elif os.path.isfile(self.path): """ 'path' is a single file, not a directory. """ self.fname_summary = path.split("/")[-1] # Just filename. self.path_summary = self.path # Complete path (maybe relative). else: msg = f"{self.path} is not a file or a directory!" tmp_directory = self.path.rsplit('/', 1)[0] if os.path.isdir(tmp_directory): summaries = [i for i in os.listdir(tmp_directory) if "summary" in i] if summaries: msg += f" {len(summaries)} summary files were found in {tmp_directory}." msg += f" {summaries}" logs = [i for i in os.listdir(tmp_directory) if i.startswith("log_")] if logs and (not summaries): msg += f" Logs found in '{tmp_directory}'. Set path to '{tmp_directory}'" msg += " to collect logs and load the summary file." raise RuntimeError(msg) self.base_fname = self.fname_summary.split(".")[0] # Base filename for .npy tmp files. self.unique_id = _generate_unique_identifier(self.path) # Unique identifier for .npy files. self._extract_info_from_summary_fname() self._read_summary() self.mixing_pairs_BM1_BE2 = self._mixing_pairs(B_left="M1", B_right="E2") self.ground_state_energy = self.levels[0, 0] try: self.A = int("".join(filter(str.isdigit, self.nucleus))) self.Z, self.N = isotope( name = "".join(filter(str.isalpha, self.nucleus)).lower(), A = self.A ) except ValueError: """ Prob. because the summary filename does not contain the name of the isotope. """ self.A = None self.Z = None self.N = None self.check_data() def _extract_info_from_ptn_fname(self): """ Extract nucleus and model space name. """ fname_split = self.fname_ptn.split("/")[-1] fname_split = fname_split.split("_") self.nucleus = fname_split[0] self.interaction = fname_split[1] def _read_ptn(self): """ Read `KSHELL` partition file (.ptn) and extract proton partition, neutron partition, and particle-hole truncation data. Save as instance attributes. """ line_number = 0 line_number_inner = 0 self.truncation = [] with open(self.fname_ptn, "r") as infile: for line in infile: line_number += 1 if line.startswith("# proton partition"): for line_inner in infile: """ Read until next '#'. """ line_number_inner += 1 if line_inner.startswith("#"): line = line_inner break self.proton_partition = np.loadtxt( fname = self.fname_ptn, skiprows = line_number, max_rows = line_number_inner ) line_number += line_number_inner line_number_inner = 0 if line.startswith("# neutron partition"): for line_inner in infile: """ Read until next '#'. """ line_number_inner += 1 if line_inner.startswith("#"): line = line_inner break self.neutron_partition = np.loadtxt( fname = self.fname_ptn, skiprows = line_number, max_rows = line_number_inner ) line_number += line_number_inner line_number_inner = 0 if line.startswith("# particle-hole truncation"): for line_inner in infile: """ Loop over all particle-hole truncation lines. """ line_number += 1 line_inner_split = line_inner.split() if (len(line_inner_split) < 2): """ Condition will probably not get fulfilled. Safety precaution due to indexing in this loop. """ break if (line_inner_split[1]).startswith("["): """ '[' indicates that 'line_inner' is still containing truncation information. """ for colon_index, elem in enumerate(line_inner_split): """ Find the index of the colon ':' to decide the orbit numbers and occupation numbers. """ if (elem == ":"): break occupation = [int(occ) for occ in line_inner_split[colon_index + 1:]] # [min, max]. orbit_numbers = "".join(line_inner_split[1:colon_index]) orbit_numbers = orbit_numbers.replace("[", "") orbit_numbers = orbit_numbers.replace("]", "") orbit_numbers = orbit_numbers.replace(" ", "") # This can prob. be removed because of the earlier split. orbit_numbers = orbit_numbers.split(",") orbit_numbers = [int(orbit) for orbit in orbit_numbers] for orbit in orbit_numbers: self.truncation.append((orbit, occupation)) else: """ Line does not contain '[' and thus does not contain truncation information. """ break def _extract_info_from_summary_fname(self): """ Extract nucleus and model space name. """ fname_split = self.fname_summary.split("/")[-1] # Remove path. fname_split = fname_split.split(".")[0] # Remove .txt. fname_split = fname_split.split("_") self.nucleus = fname_split[1] self.interaction = fname_split[2] def _read_summary(self): """ Read energy level data, transition probabilities and transition strengths from `KSHELL` output files. Raises ------ KshellDataStructureError If the `KSHELL` file has unexpected structure / syntax. """ # npy_path = "tmp" # base_fname = self.path.split("/")[-1][:-4] # unique_id = _generate_unique_identifier(self.path) if self.load_and_save_to_file: try: os.mkdir(self.npy_path) except FileExistsError: pass with open(f"{self.npy_path}/README.txt", "w") as outfile: msg = "This directory contains binary numpy data of KSHELL summary data." msg += " The purpose is to speed up subsequent runs which use the same summary data." msg += " It is safe to delete this entire directory if you have the original summary text file, " msg += "though at the cost of having to read the summary text file over again which may take some time." msg += " The ksutil.loadtxt parameter load_and_save_to_file = 'overwrite' will force a re-write of the binary numpy data." outfile.write(msg) levels_fname = f"{self.npy_path}/{self.base_fname}_levels_{self.unique_id}.npy" transitions_BM1_fname = f"{self.npy_path}/{self.base_fname}_transitions_BM1_{self.unique_id}.npy" transitions_BE2_fname = f"{self.npy_path}/{self.base_fname}_transitions_BE2_{self.unique_id}.npy" transitions_BE1_fname = f"{self.npy_path}/{self.base_fname}_transitions_BE1_{self.unique_id}.npy" debug_fname = f"{self.npy_path}/{self.base_fname}_debug_{self.unique_id}.npy" fnames = [ levels_fname, transitions_BE2_fname, transitions_BM1_fname, transitions_BE1_fname, debug_fname ] if self.load_and_save_to_file != "overwrite": """ Do not load files if overwrite parameter has been passed. """ if all([os.path.isfile(fname) for fname in fnames]) and self.load_and_save_to_file: """ If all files exist, load them. If any of the files do not exist, all will be generated. """ self.levels = np.load(file=levels_fname, allow_pickle=True) self.transitions_BM1 = np.load(file=transitions_BM1_fname, allow_pickle=True) self.transitions_BE2 = np.load(file=transitions_BE2_fname, allow_pickle=True) self.transitions_BE1 = np.load(file=transitions_BE1_fname, allow_pickle=True) self.debug = np.load(file=debug_fname, allow_pickle=True) msg = "Summary data loaded from .npy!" msg += " Use loadtxt parameter load_and_save_to_file = 'overwrite'" msg += " to re-read data from the summary file." print(msg) return parallel_args = [ [self.path_summary, "Energy", "replace_this_entry_with_loader", 0], [self.path_summary, "B(E1)", "replace_this_entry_with_loader", 1], [self.path_summary, "B(M1)", "replace_this_entry_with_loader", 2], [self.path_summary, "B(E2)", "replace_this_entry_with_loader", 3], ] if self.old_or_new == "new": parallel_args[0][2] = _load_energy_levels parallel_args[1][2] = _load_transition_probabilities parallel_args[2][2] = _load_transition_probabilities parallel_args[3][2] = _load_transition_probabilities elif self.old_or_new == "old": parallel_args[0][2] = _load_energy_levels parallel_args[1][2] = _load_transition_probabilities_old parallel_args[2][2] = _load_transition_probabilities_old parallel_args[3][2] = _load_transition_probabilities_old elif self.old_or_new == "jem": parallel_args[0][2] = _load_energy_levels parallel_args[1][2] = _load_transition_probabilities_jem parallel_args[2][2] = _load_transition_probabilities_jem parallel_args[3][2] = _load_transition_probabilities_jem if flags["parallel"]: with multiprocessing.Pool() as pool: pool_res = pool.map(_generic_loader, parallel_args) self.levels, self.negative_spin_counts[0] = pool_res[0] self.transitions_BE1, self.negative_spin_counts[1] = pool_res[1] self.transitions_BM1, self.negative_spin_counts[2] = pool_res[2] self.transitions_BE2, self.negative_spin_counts[3] = pool_res[3] else: self.levels, self.negative_spin_counts[0] = _generic_loader(parallel_args[0]) self.transitions_BE1, self.negative_spin_counts[1] = _generic_loader(parallel_args[1]) self.transitions_BM1, self.negative_spin_counts[2] = _generic_loader(parallel_args[2]) self.transitions_BE2, self.negative_spin_counts[3] = _generic_loader(parallel_args[3]) self.levels = np.array(self.levels) self.transitions_BE1 = np.array(self.transitions_BE1) self.transitions_BM1 = np.array(self.transitions_BM1) self.transitions_BE2 = np.array(self.transitions_BE2) self.debug = "DEBUG\n" self.debug += f"skipped -1 states in levels: {self.negative_spin_counts[0]}\n" self.debug += f"skipped -1 states in BE1: {self.negative_spin_counts[1]}\n" self.debug += f"skipped -1 states in BM1: {self.negative_spin_counts[2]}\n" self.debug += f"skipped -1 states in BE2: {self.negative_spin_counts[3]}\n" self.debug = np.array(self.debug) if self.old_or_new == "jem": """ 'jem style' summary syntax lists all initial and final excitation energies in transitions as absolute values. Subtract the ground state energy to get the relative energies to match the newer KSHELL summary file syntax. """ msg = "The issue of E_final > E_initial must be figured out before" msg += " JEM style syntax can be used!" raise NotImplementedError(msg) E_gs = abs(self.levels[0, 0]) # Can prob. just use ... -= E_gs try: self.transitions_BM1[:, 3] = E_gs - np.abs(self.transitions_BM1[:, 3]) self.transitions_BM1[:, 7] = E_gs - np.abs(self.transitions_BM1[:, 7]) except IndexError: """ No BM1 transitions. """ pass try: self.transitions_BE1[:, 3] = E_gs - np.abs(self.transitions_BE1[:, 3]) self.transitions_BE1[:, 7] = E_gs - np.abs(self.transitions_BE1[:, 7]) except IndexError: """ No BE1 transitions. """ pass try: self.transitions_BE2[:, 3] = E_gs - np.abs(self.transitions_BE2[:, 3]) self.transitions_BE2[:, 7] = E_gs - np.abs(self.transitions_BE2[:, 7]) except IndexError: """ No BE2 transitions. """ pass self.levels[:, 1] /= 2 # JEM style syntax has 2*J already. Without this correction it would be 4*J. if self.load_and_save_to_file: np.save(file=levels_fname, arr=self.levels, allow_pickle=True) np.save(file=transitions_BM1_fname, arr=self.transitions_BM1, allow_pickle=True) np.save(file=transitions_BE2_fname, arr=self.transitions_BE2, allow_pickle=True) np.save(file=transitions_BE1_fname, arr=self.transitions_BE1, allow_pickle=True) np.save(file=debug_fname, arr=self.debug, allow_pickle=True) def level_plot(self, include_n_levels: int = 1000, filter_spins: Union[None, list] = None, filter_parity: Union[None, str] = None, color: Union[None, str] = "black" ): """ Wrapper method to include level plot as an attribute to this class. Generate a level plot for a single isotope. Angular momentum on the x axis, energy on the y axis. Parameters ---------- include_n_levels : int The maximum amount of states to plot for each spin. Default set to a large number to indicate ≈ no limit. filter_spins : Union[None, list] Which spins to include in the plot. If `None`, all spins are plotted. Defaults to `None` color : Union[None, str] Set the color of the level lines. """ level_plot( levels = self.levels, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parity = filter_parity, color = color, ) def level_density_plot(self, bin_width: Union[int, float] = 0.2, include_n_levels: Union[None, int] = None, filter_spins: Union[None, int, list] = None, filter_parity: Union[None, str, int] = None, return_counts: bool = False, E_min: Union[float, int] = 0, E_max: Union[float, int] = np.inf, plot: bool = True, save_plot: bool = False ): """ Wrapper method to include level density plotting as an attribute to this class. Generate the level density with the input bin size. Parameters ---------- See level_density in general_utilities.py for parameter information. """ bins, density = level_density( levels = self.levels, bin_width = bin_width, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parity = filter_parity, return_counts = return_counts, E_min = E_min, E_max = E_max, plot = plot, save_plot = save_plot ) return bins, density def nld(self, bin_width: Union[int, float] = 0.2, include_n_levels: Union[None, int] = None, filter_spins: Union[None, int, list] = None, filter_parity: Union[None, str, int] = None, E_min: Union[float, int] = 0, E_max: Union[float, int] = np.inf, return_counts: bool = False, plot: bool = True, save_plot: bool = False ): """ Wrapper method to level_density_plot. """ return self.level_density_plot( bin_width = bin_width, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parity = filter_parity, E_min = E_min, E_max = E_max, return_counts = return_counts, plot = plot, save_plot = save_plot ) def gamma_strength_function_average_plot(self, bin_width: Union[float, int] = 0.2, Ex_min: Union[float, int] = 5, Ex_max: Union[float, int] = 50, multipole_type: str = "M1", prefactor_E1: Union[None, float] = None, prefactor_M1: Union[None, float] = None, prefactor_E2: Union[None, float] = None, initial_or_final: str = "initial", partial_or_total: str = "partial", include_only_nonzero_in_average: bool = True, include_n_levels: Union[None, int] = None, filter_spins: Union[None, list] = None, filter_parities: str = "both", return_n_transitions: bool = False, plot: bool = True, save_plot: bool = False ): """ Wrapper method to include gamma ray strength function calculations as an attribute to this class. Includes saving of GSF data to .npy files. Parameters ---------- See gamma_strength_function_average in general_utilities.py for parameter descriptions. """ transitions_dict = { "M1": self.transitions_BM1, "E2": self.transitions_BE2, "E1": self.transitions_BE1 } is_loaded = False gsf_unique_string = f"{bin_width}{Ex_min}{Ex_max}{multipole_type}" gsf_unique_string += f"{prefactor_E1}{prefactor_M1}{prefactor_E2}" gsf_unique_string += f"{initial_or_final}{partial_or_total}{include_only_nonzero_in_average}" gsf_unique_string += f"{include_n_levels}{filter_spins}{filter_parities}" gsf_unique_id = hashlib.sha1((gsf_unique_string).encode()).hexdigest() gsf_fname = f"{self.npy_path}/{self.base_fname}_gsf_{gsf_unique_id}_{self.unique_id}.npy" bins_fname = f"{self.npy_path}/{self.base_fname}_gsfbins_{gsf_unique_id}_{self.unique_id}.npy" n_transitions_fname = f"{self.npy_path}/{self.base_fname}_gsfntransitions_{gsf_unique_id}_{self.unique_id}.npy" fnames = [gsf_fname, bins_fname] if return_n_transitions: fnames.append(n_transitions_fname) if all([os.path.isfile(fname) for fname in fnames]) and self.load_and_save_to_file and (self.load_and_save_to_file != "overwrite"): """ If all these conditions are met, all arrays will be loaded from file. If any of these conditions are NOT met, all arrays will be re-calculated. """ gsf = np.load(file=gsf_fname, allow_pickle=True) bins = np.load(file=bins_fname, allow_pickle=True) if return_n_transitions: n_transitions = np.load(file=n_transitions_fname, allow_pickle=True) msg = f"{self.nucleus} {multipole_type} GSF data loaded from .npy!" print(msg) is_loaded = True else: tmp = gamma_strength_function_average( levels = self.levels, transitions = transitions_dict[multipole_type], bin_width = bin_width, Ex_min = Ex_min, Ex_max = Ex_max, multipole_type = multipole_type, prefactor_E1 = prefactor_E1, prefactor_M1 = prefactor_M1, prefactor_E2 = prefactor_E2, initial_or_final = initial_or_final, partial_or_total = partial_or_total, include_only_nonzero_in_average = include_only_nonzero_in_average, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parities = filter_parities, return_n_transitions = return_n_transitions, # plot = plot, # save_plot = save_plot ) if return_n_transitions: bins, gsf, n_transitions = tmp else: bins, gsf = tmp if self.load_and_save_to_file and not is_loaded: np.save(file=gsf_fname, arr=gsf, allow_pickle=True) np.save(file=bins_fname, arr=bins, allow_pickle=True) if return_n_transitions: np.save(file=n_transitions_fname, arr=n_transitions, allow_pickle=True) if plot: unit_exponent = 2*int(multipole_type[-1]) + 1 fig, ax = plt.subplots() ax.plot(bins, gsf, label=multipole_type.upper(), color="black") ax.legend() ax.grid() ax.set_xlabel(r"E$_{\gamma}$ [MeV]") ax.set_ylabel(f"$\gamma$SF [MeV$^-$$^{unit_exponent}$]") if save_plot: fname = f"gsf_{multipole_type}.png" print(f"GSF saved as '{fname}'") fig.savefig(fname=fname, dpi=300) plt.show() if return_n_transitions: return bins, gsf, n_transitions else: return bins, gsf def gsf(self, bin_width: Union[float, int] = 0.2, Ex_min: Union[float, int] = 5, Ex_max: Union[float, int] = 50, multipole_type: str = "M1", prefactor_E1: Union[None, float] = None, prefactor_M1: Union[None, float] = None, prefactor_E2: Union[None, float] = None, initial_or_final: str = "initial", partial_or_total: str = "partial", include_only_nonzero_in_average: bool = True, include_n_levels: Union[None, int] = None, filter_spins: Union[None, list] = None, filter_parities: str = "both", return_n_transitions: bool = False, plot: bool = True, save_plot: bool = False ): """ Alias for gamma_strength_function_average_plot. See that docstring for details. """ return self.gamma_strength_function_average_plot( bin_width = bin_width, Ex_min = Ex_min, Ex_max = Ex_max, multipole_type = multipole_type, prefactor_E1 = prefactor_E1, prefactor_M1 = prefactor_M1, prefactor_E2 = prefactor_E2, initial_or_final = initial_or_final, partial_or_total = partial_or_total, include_only_nonzero_in_average = include_only_nonzero_in_average, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parities = filter_parities, return_n_transitions = return_n_transitions, plot = plot, save_plot = save_plot ) def porter_thomas(self, multipole_type: str, **kwargs): """ Wrapper for general_utilities.porter_thomas. See that docstring for details. Parameters ---------- multipole_type : str Choose the multipolarity of the transitions. 'E1', 'M1', 'E2'. """ transitions_dict = { "E1": self.transitions_BE1, "M1": self.transitions_BM1, "E2": self.transitions_BE2, } return porter_thomas(transitions_dict[multipole_type], **kwargs) def porter_thomas_Ei_plot(self, Ei_range_min: float = 5, Ei_range_max: float = 9, Ei_values: Union[list, None] = None, Ei_bin_width: float = 0.2, BXL_bin_width: float = 0.1, multipole_type: Union[str, list] = "M1", set_title: bool = True ): """ Porter-Thomas analysis of the reduced transition probabilities for different initial excitation energies. Produces a figure very similar to fig. 3.3 in JEM PhD thesis: http://urn.nb.no/URN:NBN:no-79895. Parameters ---------- Ei_range_min : float Minimum value of the initial energy range. Three equally spaced intervals will be chosen from this range. Be sure to choose this value to be above the discrete region. MeV. Ei_range_max : float Maximum value of the initial energy range. Three equally spaced intervals will be chosen from this range. The neutron separation energy is a good choice. MeV. Ei_values : Union[list, None] List of initial energies to be used. If None, the initial energies will be chosen from the Ei_range_min and Ei_range_max. Values in a bin around Ei_values of size Ei_bin_width will be used. Max 3 values allowed. MeV. Ei_bin_width : float Width of the initial energy bins. MeV. BXL_bin_width : float Width of the BXL bins when the BXL/mean(BXL) values are counted. Unitless. multipole_type : str Choose the multipolarity of the transitions. 'E1', 'M1', 'E2'. set_title: bool Toggle figure title on / off. Defaults to True (on). """ if Ei_values is None: """ Defaults to a range defined by Ei_range_min and Ei_range_max. """ Ei_values = np.linspace(Ei_range_min, Ei_range_max, 3) if len(Ei_values) > 3: raise ValueError("Ei_values must be a list of length <= 3.") if isinstance(multipole_type, str): multipole_type = [multipole_type] elif isinstance(multipole_type, list): pass else: msg = f"multipole_type must be str or list. Got {type(multipole_type)}." raise TypeError(msg) colors = ["blue", "royalblue", "lightsteelblue"] Ei_range = np.linspace(Ei_range_min, Ei_range_max, 4) if len(multipole_type) == 1: fig, axd = plt.subplot_mosaic( [['upper'], ['middle'], ['lower']], gridspec_kw = dict(height_ratios=[1, 1, 0.7]), figsize = (6.4, 8), constrained_layout = True, sharex = True ) for Ei, color in zip(Ei_values, colors): """ Calculate in a bin size of 'Ei_bin_width' around given Ei values. """ bins, counts, chi2 = self.porter_thomas( multipole_type = multipole_type[0], Ei = Ei, BXL_bin_width = BXL_bin_width, Ei_bin_width = Ei_bin_width, return_chi2 = True ) idx = np.argmin(np.abs(bins - 10)) # Slice the arrays at approx 10. bins = bins[:idx] counts = counts[:idx] chi2 = chi2[:idx] axd["upper"].step( bins, counts, label = r"$E_i = $" + f"{Ei:.2f}" + r" $\pm$ " + f"{Ei_bin_width/2:.2f} MeV", color = color ) axd["upper"].plot( bins, chi2, color = "tab:green", label = r"$\chi_{\nu = 1}^2$" ) axd["upper"].legend(loc="upper right") axd["upper"].set_ylabel(r"Normalised counts") for i, color in enumerate(colors): """ Calculate in the specified range of Ei values. """ bins, counts, chi2 = self.porter_thomas( multipole_type = multipole_type[0], Ei = [Ei_range[i], Ei_range[i+1]], BXL_bin_width = BXL_bin_width, return_chi2 = True ) idx = np.argmin(np.abs(bins - 10)) bins = bins[:idx] counts = counts[:idx] chi2 = chi2[:idx] axd["middle"].step( bins, counts, color = color, label = r"$E_i = $" + f"[{Ei_range[i]:.2f}, {Ei_range[i+1]:.2f}] MeV" ) axd["lower"].step( bins, counts/chi2, color = color, label = r"($E_i = $" + f"[{Ei_range[i]:.2f}, {Ei_range[i+1]:.2f}] MeV)" + r"$/\chi_{\nu = 1}^2$", ) axd["middle"].plot(bins, chi2, color="tab:green", label=r"$\chi_{\nu = 1}^2$") axd["middle"].legend(loc="upper right") axd["middle"].set_ylabel(r"Normalised counts") axd["lower"].hlines(y=1, xmin=bins[0], xmax=bins[-1], linestyle="--", color="black") axd["lower"].set_xlabel(r"$B(M1)/\langle B(M1) \rangle$") axd["lower"].legend(loc="upper left") axd["lower"].set_ylabel(r"Relative error") axd["lower"].set_xlabel( r"$B(" + f"{multipole_type[0]}" + r")/\langle B(" + f"{multipole_type[0]}" + r") \rangle$" ) if set_title: axd["upper"].set_title( f"{self.nucleus_latex}, {self.interaction}, " + r"$" + f"{multipole_type[0]}" + r"$" ) fig.savefig(fname=f"{self.nucleus}_porter_thomas_Ei_{multipole_type[0]}.png", dpi=300) elif len(multipole_type) == 2: fig, axd = plt.subplot_mosaic([ ['upper left', 'upper right'], ['middle left', 'middle right'], ['lower left', 'lower right'] ], gridspec_kw = dict(height_ratios=[1, 1, 0.7]), figsize = (10, 8), constrained_layout = True, sharex = True ) for multipole_type_, loc in zip(multipole_type, ["left", "right"]): for Ei, color in zip(Ei_values, colors): """ Calculate in a bin size of 'Ei_bin_width' around given Ei values. """ bins, counts, chi2 = self.porter_thomas( multipole_type = multipole_type_, Ei = Ei, BXL_bin_width = BXL_bin_width, Ei_bin_width = Ei_bin_width, return_chi2 = True ) idx = np.argmin(np.abs(bins - 10)) # Slice the arrays at approx 10. bins = bins[:idx] counts = counts[:idx] chi2 = chi2[:idx] axd["upper " + loc].step( bins, counts, label = r"$E_i = $" + f"{Ei:.2f}" + r" $\pm$ " + f"{Ei_bin_width/2:.2f} MeV", color = color ) axd["upper " + loc].plot( bins, chi2, color = "tab:green", label = r"$\chi_{\nu = 1}^2$" ) for i, color in enumerate(colors): """ Calculate in the specified range of Ei values. """ bins, counts, chi2 = self.porter_thomas( multipole_type = multipole_type_, Ei = [Ei_range[i], Ei_range[i+1]], BXL_bin_width = BXL_bin_width, return_chi2 = True ) idx = np.argmin(np.abs(bins - 10)) bins = bins[:idx] counts = counts[:idx] chi2 = chi2[:idx] axd["middle " + loc].step( bins, counts, color = color, label = r"$E_i = $" + f"[{Ei_range[i]:.2f}, {Ei_range[i+1]:.2f}] MeV" ) axd["lower " + loc].step( bins, counts/chi2, color = color, label = r"($E_i = $" + f"[{Ei_range[i]:.2f}, {Ei_range[i+1]:.2f}] MeV)" + r"$/\chi_{\nu = 1}^2$", ) axd["middle " + loc].plot(bins, chi2, color="tab:green", label=r"$\chi_{\nu = 1}^2$") axd["lower " + loc].hlines(y=1, xmin=bins[0], xmax=bins[-1], linestyle="--", color="black") # axd["lower " + loc].set_xlabel(r"$B(M1)/\langle B(M1) \rangle$") axd["lower " + loc].set_xlabel( r"$B(" + f"{multipole_type_}" + r")/\langle B(" + f"{multipole_type_}" + r") \rangle$" ) if set_title: axd["upper " + loc].set_title( f"{self.nucleus_latex}, {self.interaction}, " + r"$" + f"{multipole_type_}" + r"$" ) axd["lower left"].legend(loc="upper left") axd["middle left"].legend(loc="upper right") axd["middle left"].set_ylabel(r"Normalised counts") axd["lower left"].set_ylabel(r"Relative error") axd["upper left"].legend(loc="upper right") axd["upper left"].set_ylabel(r"Normalised counts") axd["upper right"].set_yticklabels([]) axd["upper right"].set_ylim(axd["upper left"].get_ylim()) axd["middle right"].set_yticklabels([]) axd["middle right"].set_ylim(axd["middle left"].get_ylim()) axd["lower right"].set_yticklabels([]) axd["lower right"].set_ylim(axd["lower left"].get_ylim()) fig.savefig(fname=f"{self.nucleus}_porter_thomas_Ei_{multipole_type[0]}_{multipole_type[1]}.png", dpi=300) else: msg = "Only 1 or 2 multipole types may be given at the same time!" msg += f" Got {len(multipole_type)}." raise ValueError(msg) plt.show() def _porter_thomas_j_plot_calculator(self, Ex_min: float, Ex_max: float, j_lists: Union[list, None], BXL_bin_width: float, multipole_type: str, ): """ Really just a wrapper to self.porter_thomas with j checks. Parameters ---------- Ex_min : float Minimum value of the initial energy. MeV. Ex_max : float Maximum value of the initial energy. MeV. j_lists : Union[list, None] Either a list of j values to compare, a list of lists of j values to compare, or None where all j values available will be used. BXL_bin_width : float Width of the BXL bins when the BXL/mean(BXL) values are counted. Unitless. multipole_type : str Choose the multipolarity of the transitions. 'E1', 'M1', 'E2'. """ if isinstance(j_lists, list): if not j_lists: msg = "Please provide a list of j values or a list of lists of j values." raise ValueError(msg) else: msg = f"j_lists must be a list. Got {type(j_lists)}." raise TypeError(msg) if all(isinstance(j, list) for j in j_lists): """ All entries in j_lists are lists. """ pass elif any(isinstance(j, list) for j in j_lists): """ Only some of the entries are lists. The case where all entries are lists will be captured by the previous check. """ msg = "j_lists cant contain a mix of lists and numbers!" raise TypeError(msg) else: """ None of the entries are lists. Combine all numbers as a single list inside j_lists. """ if all(isinstance(j, (int, float)) for j in j_lists): j_lists = [j_lists] else: msg = "All entries in j_lists must either all be lists or all be numbers!" raise TypeError(msg) if (j_lists_len := len(j_lists)) > 3: msg = f"j_lists cannot contain more than 3 ranges of j values. Got {j_lists_len}." raise ValueError(msg) if Ex_min > Ex_max: msg = "Ex_min cannot be larger than Ex_max!" raise ValueError(msg) if (Ex_min < 0) or (Ex_max < 0): msg = "Ex_min and Ex_max cannot be negative!" raise ValueError(msg) binss = [] countss = [] chi2s = [] for j_list in j_lists: """ Calculate for the j values in j_list (note: not in j_lists). """ bins, counts, chi2 = self.porter_thomas( multipole_type = multipole_type, j_list = j_list, Ei = [Ex_min, Ex_max], BXL_bin_width = BXL_bin_width, return_chi2 = True ) idx = np.argmin(np.abs(bins - 10)) # Slice the arrays at approx 10. # bins = bins[:idx] # counts = counts[:idx] # chi2 = chi2[:idx] binss.append(bins[:idx]) countss.append(counts[:idx]) chi2s.append(chi2[:idx]) return binss, countss, chi2s def porter_thomas_j_plot(self, Ex_min: float = 5, Ex_max: float = 9, j_lists: Union[list, None] = None, BXL_bin_width: float = 0.1, multipole_type: Union[str, list] = "M1", include_relative_difference: bool = True, set_title: bool = True ): """ Porter-Thomas analysis of the reduced transition probabilities for different angular momenta. Parameter --------- multipole_type : Union[str, list] Choose the multipolarity of the transitions. 'E1', 'M1', 'E2'. Accepts a list of max 2 multipolarities. set_title : bool Toggle plot title on / off. See the docstring of _porter_thomas_j_plot_calculator for the rest of the descriptions. """ if j_lists is None: j_list_default = True else: j_list_default = False transitions_dict = { "E1": self.transitions_BE1, "M1": self.transitions_BM1, "E2": self.transitions_BE2, } colors = ["blue", "royalblue", "lightsteelblue"] if isinstance(multipole_type, str): multipole_type = [multipole_type] elif isinstance(multipole_type, list): pass else: msg = f"multipole_type must be str or list. Got {type(multipole_type)}." raise TypeError(msg) if len(multipole_type) == 1: if j_list_default: """ Default j_lists values. """ j_lists = [] for elem in np.unique(transitions_dict[multipole_type[0]][:, 0]): j_lists.append([elem/2]) j_lists = j_lists[:3] # _porter_thomas_j_plot_calculator supports max. 3 lists of j values. if include_relative_difference: fig, axd = plt.subplot_mosaic( [['upper'], ['lower']], gridspec_kw = dict(height_ratios=[1, 0.5]), figsize = (6.4, 8), constrained_layout = True, sharex = True ) else: fig, axd = plt.subplot_mosaic( [['upper']], gridspec_kw = dict(height_ratios=[1]), # figsize = (6.4, 8), constrained_layout = True, sharex = True ) binss, countss, chi2s = self._porter_thomas_j_plot_calculator( Ex_min = Ex_min, Ex_max = Ex_max, j_lists = j_lists, BXL_bin_width = BXL_bin_width, multipole_type = multipole_type[0], ) for bins, counts, chi2, j_list, color in zip(binss, countss, chi2s, j_lists, colors): axd["upper"].step( bins, counts, label = r"$j_i = $" + f"{j_list}", color = color ) if include_relative_difference: axd["lower"].step( bins, counts/chi2, color = color, label = r"($j_i = $" + f"{j_list})" + r"$/\chi_{\nu = 1}^2$", ) axd["upper"].plot( bins, chi2, color = "tab:green", label = r"$\chi_{\nu = 1}^2$" ) axd["upper"].legend(loc="upper right") axd["upper"].set_ylabel(r"Normalised counts") if set_title: axd["upper"].set_title( f"{self.nucleus_latex}, {self.interaction}, " + r"$" + f"{multipole_type[0]}" + r"$" ) if include_relative_difference: axd["lower"].hlines(y=1, xmin=bins[0], xmax=bins[-1], linestyle="--", color="black") axd["lower"].legend(loc="upper left") axd["lower"].set_ylabel(r"Relative error") axd["lower"].set_xlabel( r"$B(" + f"{multipole_type[0]}" + r")/\langle B(" + f"{multipole_type[0]}" + r") \rangle$" ) else: axd["upper"].set_xlabel( r"$B(" + f"{multipole_type[0]}" + r")/\langle B(" + f"{multipole_type[0]}" + r") \rangle$" ) fig.savefig(fname=f"{self.nucleus}_porter_thomas_j_{multipole_type[0]}.png", dpi=300) elif len(multipole_type) == 2: if j_list_default: """ Default j_lists values. """ j_lists = [] for elem in np.unique(transitions_dict[multipole_type[0]][:, 0]): j_lists.append([elem/2]) j_lists = j_lists[:3] # _porter_thomas_j_plot_calculator supports max. 3 lists of j values. fig, axd = plt.subplot_mosaic( [['upper left', 'upper right'], ['lower left', 'lower right']], gridspec_kw = dict(height_ratios=[1, 0.5]), figsize = (10, 8), constrained_layout = True, sharex = True ) binss, countss, chi2s = self._porter_thomas_j_plot_calculator( Ex_min = Ex_min, Ex_max = Ex_max, j_lists = j_lists, BXL_bin_width = BXL_bin_width, multipole_type = multipole_type[0], ) for bins, counts, chi2, j_list, color in zip(binss, countss, chi2s, j_lists, colors): axd["upper left"].step( bins, counts, label = r"$j_i = $" + f"{j_list}", color = color ) axd["lower left"].step( bins, counts/chi2, color = color, label = r"($j_i = $" + f"{j_list})" + r"$/\chi_{\nu = 1}^2$", ) axd["upper left"].plot( bins, chi2, color = "tab:green", label = r"$\chi_{\nu = 1}^2$" ) axd["upper left"].legend(loc="upper right") axd["upper left"].set_ylabel(r"Normalised counts") axd["lower left"].hlines(y=1, xmin=bins[0], xmax=bins[-1], linestyle="--", color="black") axd["lower left"].set_xlabel( r"$B(" + f"{multipole_type[0]}" + r")/\langle B(" + f"{multipole_type[0]}" + r") \rangle$" ) axd["lower left"].legend(loc="upper left") axd["lower left"].set_ylabel(r"Relative error") if set_title: axd["upper left"].set_title( f"{self.nucleus_latex}, {self.interaction}, " + r"$" + f"{multipole_type[0]}" + r"$" ) if j_list_default: """ Default j_lists values. """ j_lists = [] for elem in np.unique(transitions_dict[multipole_type[1]][:, 0]): j_lists.append([elem/2]) j_lists = j_lists[:3] # _porter_thomas_j_plot_calculator supports max. 3 lists of j values. binss, countss, chi2s = self._porter_thomas_j_plot_calculator( Ex_min = Ex_min, Ex_max = Ex_max, j_lists = j_lists, BXL_bin_width = BXL_bin_width, multipole_type = multipole_type[1], ) for bins, counts, chi2, j_list, color in zip(binss, countss, chi2s, j_lists, colors): axd["upper right"].step( bins, counts, label = r"$j_i = $" + f"{j_list}", color = color ) axd["lower right"].step( bins, counts/chi2, color = color, label = r"($j_i = $" + f"{j_list})" + r"$/\chi_{\nu = 1}^2$", ) axd["upper right"].plot( bins, chi2, color = "tab:green", label = r"$\chi_{\nu = 1}^2$" ) # axd["upper right"].legend(loc="upper right") axd["upper right"].set_yticklabels([]) axd["upper right"].set_ylim(axd["upper left"].get_ylim()) axd["lower right"].hlines(y=1, xmin=bins[0], xmax=bins[-1], linestyle="--", color="black") axd["lower right"].set_xlabel( r"$B(" + f"{multipole_type[1]}" + r")/\langle B(" + f"{multipole_type[1]}" + r") \rangle$" ) # axd["lower right"].legend(loc="upper left") axd["lower right"].set_yticklabels([]) axd["lower right"].set_ylim(axd["lower left"].get_ylim()) if set_title: axd["upper right"].set_title( f"{self.nucleus_latex}, {self.interaction}, " + r"$" + f"{multipole_type[1]}" + r"$" ) fig.savefig(fname=f"{self.nucleus}_porter_thomas_j_{multipole_type[0]}_{multipole_type[1]}.png", dpi=300) else: msg = "Only 1 or 2 multipole types may be given at the same time!" msg += f" Got {len(multipole_type)}." raise ValueError(msg) plt.show() def angular_momentum_distribution_plot(self, bin_width: float = 0.2, E_min: float = 5, E_max: float = 10, j_list: Union[None, int, float, Iterable] = None, filter_parity: Union[None, int, str] = None, plot: bool = True, # single_spin_plot: Union[None, int, float, Iterable] = None, save_plot: bool = True, set_title: bool = True ): """ Plot the angular momentum distribution of the levels. Parameters ---------- bin_width : float Width of the energy bins. MeV. E_min : float Minimum value of the energy range. E_max : float Maximum value of the energy range. j_list : Union[None, int, float, Iterable] Filter the levels by their angular momentum. If None, all levels are plotted. filter_parity : Union[None, int, str] Filter the levels by their parity. If None, all levels are plotted. plot : bool If True, the plot will be shown. """ if not isinstance(filter_parity, (type(None), int, str)): msg = f"'filter_parity' must be of type: None, int, str. Got {type(j_list)}." raise TypeError(msg) if isinstance(filter_parity, str): valid_filter_parity = ["+", "-"] if filter_parity not in valid_filter_parity: msg = f"Valid parity filters are: {valid_filter_parity}." raise ValueError(msg) filter_parity = 1 if (filter_parity == "+") else -1 if j_list is None: """ If no angular momentum filter, then include all angular momenta in the data set. """ angular_momenta = np.unique(self.levels[:, 1])/2 else: if isinstance(j_list, (float, int)): angular_momenta = [j_list] elif isinstance(j_list, Iterable) and not isinstance(j_list, str): angular_momenta = j_list else: msg = f"'j_list' must be of type: None, Iterable, int, float. Got {type(j_list)}." raise TypeError(msg) bins = np.arange(E_min, E_max, bin_width) n_bins = len(bins) n_angular_momenta = len(angular_momenta) densities = np.zeros((n_bins, n_angular_momenta)) for i in range(n_angular_momenta): """ Calculate the nuclear level density for each angular momentum. NOTE: Each column is the density for a unique angular momentum. Consequently, rows are the energy axis. """ bins_tmp, densities_tmp, counts_tmp = level_density( levels = self.levels, bin_width = bin_width, filter_spins = angular_momenta[i], filter_parity = filter_parity, E_min = E_min, E_max = E_max, return_counts = True, plot = False, save_plot = False ) assert len(bins_tmp) <= n_bins, "There are more NLD bins than bins in the expected range!" for b1, b2 in zip(bins_tmp, bins): """ Check that the returned bins match the expected bin range. Note that bins_tmp might be shorter than bins, but never longer. """ assert b1 == b2, "NLD bins do not match the expected bins!" """ Check that the total number of levels returned by the NLD function is actually the correct number of levels as counted with the following stright-forward counter: """ E_tmp = self.levels[self.levels[:, 1] == 2*angular_momenta[i]] # Extract levels of correct angular momentum. if filter_parity is not None: E_tmp = E_tmp[E_tmp[:, 2] == filter_parity] mask_lower = (E_tmp[:, 0] - self.ground_state_energy) >= E_min # Keep only levels larger or equal to E_min. mask_upper = (E_tmp[:, 0] - self.ground_state_energy) < E_max # Keep only levels lower than E_max. mask_total = np.logical_and(mask_lower, mask_upper) # Combine the two masks with and. n_levels_in_range = sum(mask_total) # The number of Trues is the number of levels within the energy range. n_counts_tmp = sum(counts_tmp) msg = f"The number of levels from the NLD in the range [{E_min, E_max})" msg += " does not match the expected value!" msg += f" {n_levels_in_range = }, {n_counts_tmp = }" success = n_levels_in_range == n_counts_tmp assert success, msg """ If E_max exceeds the max energy in the data set, level_density will adjust E_max to the max energy value. In this function, the bin range should be the same for all angular momenta, meaning that we might have to add some extra zeros to the end of the densities array. """ n_missing_values = n_bins - len(bins_tmp) densities[:, i] = np.concatenate((densities_tmp, np.zeros(n_missing_values))) if flags["debug"]: print("-----------------------------------") print("angular_momentum_distribution debug") if all(densities_tmp == 0): print("No levels in this energy range!") print(f"{angular_momenta[i] = }") print(f"{filter_parity = }") print(f"{bin_width = }") print(f"{E_min = }") print(f"{E_max = }") print(f"densities extended with {n_missing_values} zeros") print("-----------------------------------") if filter_parity is None: exponent = r"$^{\pm}$" # For exponent in yticklabels. parity_str = "+-" # For filename in savefig. elif filter_parity == 1: exponent = r"$^{+}$" parity_str = "+" elif filter_parity == -1: exponent = r"$^{-}$" parity_str = "-" if plot: xticklabels = [] for i in bins: """ Loop for generating x tick labels. Loop over the bins of the first angular momentum entry. Note that the bins are equal for all the different angular momenta (all columns in 'bins' are equal). Round all energies to 1 decimal when that decimal is != 0. If that decimal is zero, round to 0 decimals. """ if (tmp := int(i)) == i: """ Eg. >>> 1 == 1.0 True (round to 0 decimals) """ xticklabels.append(tmp) else: """ Round to 1 decimal. """ xticklabels.append(round(i, 1)) fig, ax = plt.subplots(figsize=(7, 6.4)) sns.heatmap( data = densities.T[-1::-1], linewidth = 0.5, annot = True, cmap = 'gray', xticklabels = xticklabels, fmt = ".0f", ax = ax ) ax.set_yticklabels(np.flip([f"{Fraction(i)}" + exponent for i in angular_momenta]), rotation=0) ax.set_xlabel(r"$E$ [MeV]") ax.set_ylabel(r"$j$ [$\hbar$]") if set_title: ax.set_title(f"{self.nucleus_latex}, {self.interaction}") cbar = ax.collections[0].colorbar cbar.ax.set_ylabel(r"NLD [MeV$^{-1}$]", rotation=90) if save_plot: fig.savefig(f"{self.nucleus}_j{parity_str}_distribution_heatmap.png", dpi=300) if plot: plt.show() return bins, densities def B_distribution(self, partial_or_total: str, multipole_type: str = "M1", filter_spins: Union[None, list] = None, filter_parity: Union[None, int] = None, filter_indices: Union[None, int, list] = None, plot: bool = True, ) -> np.ndarray: """ Plot a histogram of the distribution of B values. Parameters ---------- partial_or_total : str If total, then all partial B values will be summed per level. If partial, then the distribution of all partial B values will be generated. multipole_type : str Choose the multipolarity of the transitions. 'E1', 'M1', 'E2'. filter_spins : Union[None, list] Filter the levels by their angular momentum. If None, all levels are included. filter_parity : Union[None, int] Filter the levels by their parity. If None, both parities are included. plot : bool If True, the plot will be shown. Returns ------- total_B : np.ndarray The sum over every partial B value for each level. """ total_time = time.perf_counter() is_loaded = False B_unique_string = f"{multipole_type}{filter_spins}{filter_parity}{filter_indices}{partial_or_total}" B_unique_id = hashlib.sha1((B_unique_string).encode()).hexdigest() B_fname = f"{self.npy_path}/{self.base_fname}_Bdist_{B_unique_id}_{self.unique_id}.npy" if os.path.isfile(B_fname) and self.load_and_save_to_file: total_B = np.load(file=B_fname, allow_pickle=True) msg = f"{self.nucleus} {multipole_type} B distribution data loaded from .npy!" print(msg) is_loaded = True else: transitions_dict = { "E1": self.transitions_BE1, "M1": self.transitions_BM1, "E2": self.transitions_BE2, } transitions = transitions_dict[multipole_type] if filter_spins is None: initial_j = np.unique(transitions[:, 0]) else: initial_j = [2*j for j in filter_spins] if filter_parity is None: initial_pi = [-1, 1] else: initial_pi = [filter_parity] if filter_indices is None: initial_indices = np.unique(transitions[:, 2]).astype(int) elif isinstance(filter_indices, list): initial_indices = [int(i) for i in filter_indices] elif isinstance(filter_indices, int): initial_indices = [filter_indices] total_B = [] # The sum of every partial B value for each level. idxi_masks = [] pii_masks = [] ji_masks = [] mask_time = time.perf_counter() for idxi in initial_indices: idxi_masks.append(transitions[:, 2] == idxi) for pii in initial_pi: pii_masks.append(transitions[:, 1] == pii) for ji in initial_j: ji_masks.append(transitions[:, 0] == ji) mask_time = time.perf_counter() - mask_time for pii in pii_masks: for idxi in idxi_masks: for ji in ji_masks: mask = np.logical_and(ji, np.logical_and(pii, idxi)) # total_B.append(np.sum(transitions[mask][:, 9])) # 9 is B decay total_B.append(transitions[mask][:, 9]) # 9 is B decay if partial_or_total == "total": """ Sum partial B values to get total B values. """ for i in range(len(total_B)): total_B[i] = sum(total_B[i]) elif partial_or_total == "partial": """ Keep a 1D list of partial B values. """ total_B = list(chain.from_iterable(total_B)) total_B = np.asarray(total_B) if self.load_and_save_to_file and not is_loaded: np.save(file=B_fname, arr=total_B, allow_pickle=True) total_time = time.perf_counter() - total_time if flags["debug"]: if not is_loaded: print(f"B_distribution {mask_time = :.4f}") print(f"B_distribution {total_time = :.4f}") if plot: plt.hist(total_B, bins=100, color="black") plt.xlabel(r"$B(" + f"{multipole_type}" + r")$") plt.show() return total_B def _brink_axel_j_calculator(self, bin_width: Union[float, int], Ex_min: Union[float, int], Ex_max: Union[float, int], multipole_type: str, j_list: list, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ Calculate the GSF as a function of Eg for all Ei and ji, as well as the GSF individually for all ji in j_list. """ bins_all_j, gsf_all_j = self.gsf( bin_width = bin_width, Ex_min = Ex_min, Ex_max = Ex_max, multipole_type = multipole_type, return_n_transitions = False, plot = False, ) n_j = len(j_list) n_gsf_all_j = len(gsf_all_j) gsf = np.zeros((n_gsf_all_j, n_j)) bins = np.zeros((n_gsf_all_j, n_j)) # Eg rows, j cols. for i in range(n_j): """ Calculate the GSF individually for each ji. """ bins_one_j, gsf_one_j = self.gsf( bin_width = bin_width, Ex_min = Ex_min, Ex_max = Ex_max, multipole_type = multipole_type, filter_spins = [j_list[i]], return_n_transitions = False, plot = False, ) gsf[:, i] = gsf_one_j bins[:, i] = bins_one_j return bins, gsf, bins_all_j, gsf_all_j def brink_axel_j(self, bin_width: Union[float, int] = 0.2, Ex_min: Union[float, int] = 5, Ex_max: Union[float, int] = 50, multipole_type: Union[list, str] = "M1", j_list: Union[list, None] = None, set_title: bool = True ): """ Plot a comparison of the GSF averaged over all ji and GSFs for each individual ji. """ if j_list is None: j_list_default = True else: j_list_default = False transitions_dict = { "E1": self.transitions_BE1, "M1": self.transitions_BM1, "E2": self.transitions_BE2, } if isinstance(multipole_type, str): multipole_type = [multipole_type] n_multipole_types = len(multipole_type) fig, ax = plt.subplots( nrows = n_multipole_types, ncols = 1, figsize = (6.4, 4.8*n_multipole_types) ) if not isinstance(ax, np.ndarray): ax = [ax] upper_ylim = -np.inf lower_ylim = np.inf for i in range(n_multipole_types): if j_list_default: """ Choose all available angular momenta as default. """ j_list = np.unique(transitions_dict[multipole_type[i]][:, 0])/2 j_list.sort() # Just in case. bins, gsf, bins_all_j, gsf_all_j = self._brink_axel_j_calculator( bin_width = bin_width, Ex_min = Ex_min, Ex_max = Ex_max, multipole_type = multipole_type[i], j_list = j_list, ) ax[i].plot(bins_all_j, gsf_all_j, color="black", label=r"All $j_i$") ax[i].plot(bins, gsf, color="black", alpha=0.2) ax[i].plot([0], [0], color="black", alpha=0.2, label=r"Single $j_i$") # Dummy for legend. ax[i].set_yscale('log') ax[i].set_ylabel(r"GSF [MeV$^{-3}$]") ax[i].legend() if set_title: ax[i].set_title( f"{self.nucleus_latex}, {self.interaction}, " + r"$" + f"{multipole_type[i]}" + r"$" ) else: ax[i].set_title( r"$" + f"{multipole_type[i]}" + r"$" ) lower_ylim = min(ax[i].get_ylim()[0], lower_ylim) upper_ylim = max(ax[i].get_ylim()[1], upper_ylim) for i in range(n_multipole_types): """ Set both lower ylim to the lowest of the two and both upper ylims to the largest of the two. """ ax[i].set_ylim((lower_ylim, upper_ylim)) ax[-1].set_xlabel(r"E$_{\gamma}$ [MeV]") fig.savefig( fname = f"{self.nucleus}_brink-axel_ji_{'_'.join(multipole_type)}.png", dpi = 300 ) plt.show() def primary_matrix(self, bin_width: Union[float, int] = 0.2, Ex_min: Union[float, int] = 0, Ex_max: Union[float, int] = 50, multipole_type: str = "M1", plot: bool = True, ): """ Create a Ex Eg primary matrix like the ones which are calculated with the Oslo method. Parameters ---------- bin_width : float, optional Width of the bins in MeV, by default 0.2 Ex_min : float, optional Minimum excitation energy of initial level in a transition, by default 0 MeV. Ex_max : float, optional Maximum excitation energy of initial level in a transition, by default 50 MeV. multipole_type : str Multipolarity of the transitions to be considered, by default "M1". plot : bool, optional Whether to plot the matrix, by default True. Returns ------- Ex_range : np.ndarray The range of the initial level energies. Eg_range : np.ndarray The range of the gamma energies. B_matrix : np.ndarray The primary matrix. """ transitions_dict = { "E1": self.transitions_BE1, "M1": self.transitions_BM1, "E2": self.transitions_BE2, } n_bins = int(np.ceil((Ex_max - Ex_min)/bin_width)) B_matrix = np.zeros((n_bins, n_bins), dtype=float) # rows: Ei, cols: Eg Ex_range = np.linspace(Ex_min, Ex_max, n_bins) Eg_range = np.linspace(Ex_min, Ex_max, n_bins) transitions = transitions_dict[multipole_type] Ex_masks = [] Eg_masks = [] for i in range(n_bins-1): """ Generate the masks once. It is not necessary to generate the Eg masks over and over again while iterating over the Ex masks. """ Ex_masks.append(np.logical_and( transitions[:, 3] >= Ex_range[i], transitions[:, 3] < Ex_range[i+1], )) for i in range(n_bins-1): """ Using separate loops allows using different bin widths for Ex and Eg, however, that has not yet been implemented. """ Eg_masks.append(np.logical_and( transitions[:, 8] >= Eg_range[i], transitions[:, 8] < Eg_range[i+1], )) for i in range(n_bins-1): """ Loop over each Ex Eg mask pair and create a combined mask. Take the mean of the B values for each combined mask. """ for j in range(i+1): mask = np.logical_and( Ex_masks[i], Eg_masks[j], ) B_slice = transitions[mask][:, 9] if B_slice.size == 0: continue # Skip if there are no B values in the mask. B_matrix[i, j] = np.mean(B_slice) if plot: fig, ax = plt.subplots() im = ax.pcolormesh(Ex_range, Eg_range, B_matrix, cmap="jet", norm="log") ax.set_title(r"$\langle B($" + f"{multipole_type}" + r"$) \rangle$") ax.set_xlabel(r"$E_{\gamma}$") ax.set_ylabel(r"$E_{x}$") fig.colorbar(im) plt.show() return Ex_range, Eg_range, B_matrix def _mixing_pairs(self, B_left: str = "M1", B_right: str = "E2", ): """ NOTE: Currently hard-coded for BM1_BE2! """ if B_left != "M1":#not in ["M1", "E2"]: # msg = f"'B_left' must be 'M1' or 'E2', got: {B_left}" # raise ValueError(msg) raise ValueError if B_right != "E2":# not in ["M1", "E2"]: # msg = f"'B_right' must be 'M1' or 'E2', got: {B_right}" # raise ValueError(msg) raise ValueError transitions_dict = { "M1": self.transitions_BM1, "E2": self.transitions_BE2, "E1": self.transitions_BE1 } transitions_left = transitions_dict[B_left] transitions_right = transitions_dict[B_right] mixing_pairs_fname = f"{self.npy_path}/{self.base_fname}_mixing_pairs_B{B_left}_B{B_right}_{self.unique_id}.npy" if os.path.isfile(mixing_pairs_fname) and self.load_and_save_to_file and (self.load_and_save_to_file != "overwrite"): print(f"Mixing pairs loaded from .npy!") mixing_pairs = np.load(file=mixing_pairs_fname, allow_pickle=True) return mixing_pairs @numba.njit def calculate_mixing_pairs( possible_j: list[int], possible_indices: list[int], transitions_BM1: np.ndarray, transitions_BE2: np.ndarray, ): mixing_pairs = [] for ji in possible_j: ji_slice_BM1 = transitions_BM1[transitions_BM1[:, 0] == ji] ji_slice_BE2 = transitions_BE2[transitions_BE2[:, 0] == ji] if (not ji_slice_BM1.size) or (not ji_slice_BE2.size): return for jf in possible_j: # if not j_allowed(ji=ji, jf=jf): continue jf_slice_BM1 = ji_slice_BM1[ji_slice_BM1[:, 4] == jf] jf_slice_BE2 = ji_slice_BE2[ji_slice_BE2[:, 4] == jf] if (not jf_slice_BM1.size) or (not jf_slice_BE2.size): continue for pi in [-1, 1]: """ [2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] """ pi_i_slice_BM1 = jf_slice_BM1[jf_slice_BM1[:, 1] == pi] pi_i_slice_BE2 = jf_slice_BE2[jf_slice_BE2[:, 1] == pi] if (not pi_i_slice_BM1.size) or (not pi_i_slice_BE2.size): continue pi_f_slice_BM1 = pi_i_slice_BM1[pi_i_slice_BM1[:, 5] == pi] pi_f_slice_BE2 = pi_i_slice_BE2[pi_i_slice_BE2[:, 5] == pi] if (not pi_f_slice_BM1.size) or (not pi_f_slice_BE2.size): continue for idx_i in possible_indices: idx_i_slice_BM1 = pi_f_slice_BM1[pi_f_slice_BM1[:, 2] == idx_i] idx_i_slice_BE2 = pi_f_slice_BE2[pi_f_slice_BE2[:, 2] == idx_i] if (not idx_i_slice_BM1.size) or (not idx_i_slice_BE2.size): continue for idx_f in possible_indices: idx_f_slice_BM1 = idx_i_slice_BM1[idx_i_slice_BM1[:, 2] == idx_f] idx_f_slice_BE2 = idx_i_slice_BE2[idx_i_slice_BE2[:, 2] == idx_f] if (not idx_f_slice_BM1.size) or (not idx_f_slice_BE2.size): continue for transition_BM1 in idx_f_slice_BM1: for transition_BE2 in idx_f_slice_BE2: if (transition_BM1[3] == transition_BE2[3]) and (transition_BM1[7] == transition_BE2[7]): mixing_pairs.append([transition_BM1, transition_BE2]) return mixing_pairs mixing_pairs_time = time.perf_counter() possible_j = np.unique(transitions_left[:, 0]) possible_indices = np.unique(transitions_left[:, 2]) assert np.all(possible_indices == np.unique(transitions_left[:, 6])) # Check that indices of the initial and final levels are the same range. mixing_pairs = calculate_mixing_pairs( transitions_BM1 = transitions_left, transitions_BE2 = transitions_right, possible_j = possible_j, possible_indices = possible_indices, ) mixing_pairs.sort(key=lambda tup: tup[0][8]) # Sort wrt. gamma energy. mixing_pairs = np.array(mixing_pairs) np.save(file=mixing_pairs_fname, arr=mixing_pairs, allow_pickle=True) mixing_pairs_time = time.perf_counter() - mixing_pairs_time print(f"{mixing_pairs_time = :.3f} s") return mixing_pairs def mixing_ratio(self, bin_width: float = 0.2, plot: bool = True, save_plot: bool = False, ): """ Calculate the ratio of T(E2)/(T(E2) + T(M1)), aka. how large the E2 contribution is. Currently hard-coded for this specific ratio. Parameters ---------- bin_width : float The ratios are sorted by gamma energy and averaged over the ratio values in a gamma energy bin of bin_with. """ E_min = self.mixing_pairs_BM1_BE2[0, 0, 8] # BM1 and BE2 has to be at the exact same gamma energies so it doesnt matter which one we take E_min and E_max from. E_max = self.mixing_pairs_BM1_BE2[-1, 0, 8] bins = np.arange(E_min, E_max + bin_width, bin_width) n_bins = len(bins) ratios = np.zeros(n_bins - 1) for i in range(n_bins - 1): mask_1 = self.mixing_pairs_BM1_BE2[:, 0, 8] >= bins[i] mask_2 = self.mixing_pairs_BM1_BE2[:, 0, 8] < bins[i + 1] mask_3 = np.logical_and(mask_1, mask_2) # M1_mean = self.mixing_pairs_BM1_BE2[:, 0, 9][mask_3].mean() # E2_mean = self.mixing_pairs_BM1_BE2[:, 1, 9][mask_3].mean() M1_mean = (1.76e13*(self.mixing_pairs_BM1_BE2[:, 0, 8][mask_3]**3)*self.mixing_pairs_BM1_BE2[:, 0, 9][mask_3]).mean() E2_mean = (1.22e09*(self.mixing_pairs_BM1_BE2[:, 1, 8][mask_3]**5)*self.mixing_pairs_BM1_BE2[:, 1, 9][mask_3]).mean() ratios[i] = E2_mean/(E2_mean + M1_mean) if plot: fig, ax = plt.subplots() ax.step(bins[:-1], ratios, color="black") # ax.legend() ax.grid() ax.set_ylabel(r"TE2/(TE2 + TM1)") ax.set_xlabel(r"$E_{\gamma}$ [MeV]") if save_plot: fname = f"mixing_ratio_E2_M1.png" print(f"Mixing ratio plot saved as '{fname}'") fig.savefig(fname=fname, dpi=300) plt.show() return bins[:-1], ratios @property def help(self): """ Generate a list of instance attributes without magic and private methods. Returns ------- help_list : list A list of non-magic instance attributes. """ help_list = [] for elem in dir(self): if not elem.startswith("_"): # Omit magic and private methods. help_list.append(elem) return help_list @property def parameters(self) -> dict: """ Get the KSHELL parameters from the shell file. Returns ------- : dict A dictionary of KSHELL parameters. """ path = self.path if os.path.isfile(path): path = path.rsplit("/", 1)[0] return get_parameters(path) @property def nucleus_latex(self): m = re.search(r"\d+$", self.nucleus) A = m.group() X = self.nucleus[:m.span()[0]] return r"$^{" + f"{A}" + r"}$" + f"{X}" def check_data(self): """ Check that the 'levels' data is sorted in order of increasing energy. """ msg = "'levels' should be sorted in order of increasing energy," msg += " but it isnt! Check the data!" energies = self.levels[:, 0] success = np.all(energies[:-1] <= energies[1:]) assert success, msg """ Check that the ground state energy is correct. """ msg = "'ground_state_energy' is not the lowest energy in 'levels'" msg += " as it should be! Check the data!" success = self.ground_state_energy == np.min(self.levels[:, 0]) assert success, msg """ Insert more checks under... """ def loadtxt( path: str, load_and_save_to_file: Union[bool, str] = True, old_or_new = "new" ) -> ReadKshellOutput: """ Wrapper for using ReadKshellOutput class as a function. Parameters ---------- path : str Path to summary file or path to directory with summary / log files. load_and_save_to_file : Union[bool, str] Toggle saving data as `.npy` files on / off. If 'overwrite', saved `.npy` files are overwritten. old_or_new : str Choose between old and new summary file syntax. All summary files generated pre 2021-11-24 use old style. New: J_i pi_i idx_i Ex_i J_f pi_f idx_f Ex_f dE B(E2)-> B(E2)->[wu] B(E2)<- B(E2)<-[wu] 5 + 1 0.036 6 + 1 0.000 0.036 70.43477980 6.43689168 59.59865983 5.44660066 Old: J_i Ex_i J_f Ex_f dE B(M1)-> B(M1)<- 2+(11) 18.393 2+(10) 17.791 0.602 0.1( 0.0) 0.1( 0.0) Returns ------- res : ReadKshellOutput Instances with data from `KSHELL` data file as attributes. """ loadtxt_time = time.perf_counter() # Debug. if old_or_new not in (old_or_new_allowed := ["old", "new", "jem"]): msg = f"'old_or_new' argument must be in {old_or_new_allowed}!" msg += f" Got '{old_or_new}'." raise ValueError(msg) res = ReadKshellOutput(path, load_and_save_to_file, old_or_new) loadtxt_time = time.perf_counter() - loadtxt_time if flags["debug"]: print(f"{loadtxt_time = } s") return res def _get_timing_data(path: str): """ Get timing data from KSHELL log files. Parameters ---------- path : str Path to log file. Examples -------- Last 10 lines of log_Ar30_usda_m0p.txt: ``` total 20.899 2 10.44928 1.0000 pre-process 0.029 1 0.02866 0.0014 operate 3.202 1007 0.00318 0.1532 re-orthog. 11.354 707 0.01606 0.5433 thick-restart 0.214 12 0.01781 0.0102 diag tri-mat 3.880 707 0.00549 0.1857 misc 2.220 0.1062 tmp 0.002 101 0.00002 0.0001 ``` """ if "log" not in path: msg = f"Unknown log file name! Got '{path}'" raise KshellDataStructureError(msg) if not os.path.isfile(path): raise FileNotFoundError(path) res = os.popen(f'tail -n 20 {path}').read() # Get the final 10 lines. res = res.split("\n") total = None if "_tr_" not in path: """ KSHELL log. """ for elem in res: tmp = elem.split() try: if tmp[0] == "total": total = float(tmp[1]) break except IndexError: continue elif "_tr_" in path: """ Transit log. """ for elem in res: tmp = elem.split() try: if tmp[0] == "total": total = float(tmp[3]) break except IndexError: continue if total is None: msg = f"Not able to extract timing data from '{path}'!" raise KshellDataStructureError(msg) return total def _get_memory_usage(path: str) -> Union[float, None]: """ Get memory usage from KSHELL log files. Parameters ---------- path : str Path to a single log file. Returns ------- total : float, None Memory usage in GB or None if memory usage could not be read. """ total = None if "tr" not in path: """ KSHELL log. """ with open(path, "r") as infile: for line in infile: if line.startswith("Total Memory for Lanczos vectors:"): try: total = float(line.split()[-2]) except ValueError: msg = f"Error reading memory usage from '{path}'." msg += f" Got '{line.split()[-2]}'." raise KshellDataStructureError(msg) break elif "tr" in path: """ Transit log. NOTE: Not yet implemented. """ return 0 if total is None: msg = f"Not able to extract memory data from '{path.split('/')[-1]}'!" raise KshellDataStructureError(msg) return total def _sortkey(filename): """ Key for sorting filenames based on angular momentum and parity. Example filename: 'log_Sc44_GCLSTsdpfsdgix5pn_j0n.txt' (angular momentum = 0). """ tmp = filename.split("_")[-1] tmp = tmp.split(".")[0] # parity = tmp[-1] spin = int(tmp[1:-1]) # return f"{spin:03d}{parity}" # Examples: 000p, 000n, 016p, 016n return spin def _get_data_general( path: str, func: Callable, plot: bool ): """ General input handling for timing data and memory data. Parameters ---------- path : str Path to a single log file or path to a directory of log files. func : Callable _get_timing_data or _get_memory_usage. """ total_negative = [] total_positive = [] filenames_negative = [] filenames_positive = [] if os.path.isfile(path): return func(path) elif os.path.isdir(path): for elem in os.listdir(path): """ Select only log files in path. """ tmp = elem.split("_") try: if ((tmp[0] == "log") or (tmp[1] == "log")) and elem.endswith(".txt"): tmp = tmp[-1].split(".") parity = tmp[0][-1] if parity == "n": filenames_negative.append(elem) elif parity == "p": filenames_positive.append(elem) except IndexError: continue filenames_negative.sort(key=_sortkey) filenames_positive.sort(key=_sortkey) for elem in filenames_negative: total_negative.append(func(f"{path}/{elem}")) for elem in filenames_positive: total_positive.append(func(f"{path}/{elem}")) if plot: xticks_negative = ["sum"] + [str(Fraction(_sortkey(i)/2)) for i in filenames_negative] xticks_positive = ["sum"] + [str(Fraction(_sortkey(i)/2)) for i in filenames_positive] sum_total_negative = sum(total_negative) sum_total_positive = sum(total_positive) fig0, ax0 = plt.subplots(ncols=1, nrows=2) fig1, ax1 = plt.subplots(ncols=1, nrows=2) bars = ax0[0].bar( xticks_negative, [sum_total_negative/60/60] + [i/60/60 for i in total_negative], color = "black", ) ax0[0].set_title("negative") for rect in bars: height = rect.get_height() ax0[0].text( x = rect.get_x() + rect.get_width() / 2.0, y = height, s = f'{height:.3f}', ha = 'center', va = 'bottom' ) bars = ax1[0].bar( xticks_negative, [sum_total_negative/sum_total_negative] + [i/sum_total_negative for i in total_negative], color = "black", ) ax1[0].set_title("negative") for rect in bars: height = rect.get_height() ax1[0].text( x = rect.get_x() + rect.get_width() / 2.0, y = height, s = f'{height:.3f}', ha = 'center', va = 'bottom' ) bars = ax0[1].bar( xticks_positive, [sum_total_positive/60/60] + [i/60/60 for i in total_positive], color = "black", ) ax0[1].set_title("positive") for rect in bars: height = rect.get_height() ax0[1].text( x = rect.get_x() + rect.get_width() / 2.0, y = height, s = f'{height:.3f}', ha = 'center', va = 'bottom' ) bars = ax1[1].bar( xticks_positive, [sum_total_positive/sum_total_positive] + [i/sum_total_positive for i in total_positive], color = "black", ) ax1[1].set_title("positive") for rect in bars: height = rect.get_height() ax1[1].text( x = rect.get_x() + rect.get_width() / 2.0, y = height, s = f'{height:.3f}', ha = 'center', va = 'bottom' ) fig0.text(x=0.02, y=0.5, s="Time [h]", rotation="vertical") fig0.text(x=0.5, y=0.02, s="Angular momentum") fig1.text(x=0.02, y=0.5, s="Norm. time", rotation="vertical") fig1.text(x=0.5, y=0.02, s="Angular momentum") plt.show() return sum(total_negative) + sum(total_positive) else: msg = f"'{path}' is neither a file nor a directory!" raise FileNotFoundError(msg) def get_timing_data(path: str, plot: bool = False) -> float: """ Wrapper for _get_timing_data. Input a single log filename and get the timing data. Input a path to a directory several log files and get the summed timing data. In units of seconds. Parameters ---------- path : str Path to a single log file or path to a directory of log files. Returns ------- : float The summed times for all input log files. """ return _get_data_general(path, _get_timing_data, plot) def get_memory_usage(path: str) -> float: """ Wrapper for _get_memory_usage. Input a single log filename and get the memory data. Input a path to a directory several log files and get the summed memory data. In units of GB. Parameters ---------- path : str Path to a single log file or path to a directory of log files. Returns ------- : float The summed memory usage for all input log files. """ return _get_data_general(path, _get_memory_usage, False) def get_parameters(path: str, verbose: bool = True) -> dict: """ Extract the parameters which are fed to KSHELL throught the shell script. Parameters ---------- path : str Path to a KSHELL work directory. Returns ------- res : dict A dictionary where the keys are the parameter names and the values are the corresponding values. """ res = {} shell_filename = None if os.path.isdir(path): for elem in os.listdir(path): if elem.endswith(".sh"): shell_filename = f"{path}/{elem}" break else: print("Directly specifying path to .sh file not yet implemented!") if shell_filename is None: if verbose: msg = f"No .sh file found in path '{path}'!" print(msg) return res with open(shell_filename, "r") as infile: for line in infile: if line.startswith(r"&input"): break for line in infile: if line.startswith(r"&end"): """ End of parameters. """ break tmp = line.split("=") key = tmp[0].strip() value = tmp[1].strip() try: value = ast.literal_eval(value) except ValueError: """ Cant convert strings. Keep them as strings. """ pass except SyntaxError: """ Cant convert Fortran booleans (.true., .false.). Keep them as strings. """ pass res[key] = value return res def inspect_log( path: str ): """ Load log file(s) for inspection. Parameters ---------- path : str Path to directory of log files or directly to a log file. """ allowed_multipolarities_list = [] if os.path.isdir(path): """ List all log files in 'path' and let the user decide which one to inspect. """ content = [i for i in os.listdir(path) if "log_" in i] content.sort() content = np.array(content) if not content.size: msg = f"No log files found in '{path}'!" raise FileNotFoundError(msg) for i, elem in enumerate(content): """ Make log file names more readable and calculate allowed multipolarities (E1, M1, E2) based on angular momentum and parity (if transition log file). """ if "_tr_" in elem: """ Transition log file. """ elem = elem.rstrip(".txt") elem = elem.split("_")[-2:] elem[0] = elem[0].lstrip("j") elem[1] = elem[1].lstrip("j") delta_parity = elem[0][-1] != elem[1][-1] # Change in parity. j_i = int(elem[0][:-1])/2 # Initial total angular momentum. j_f = int(elem[1][:-1])/2 # Final. if delta_parity: j_max = 1 # Because KSHELL doesnt support M2. else: j_max = 2 # Because KSHELL supports max. E2. allowed_j = np.arange(max(np.abs(j_i - j_f), 1), min(j_i + j_f, j_max) + 1, 1, dtype=int) # Possible j couplings. tmp_multipolarity = [] if delta_parity: """ If there is a change in parity: Even numbered magnetic and odd numbered electric. """ for j in allowed_j: if j%2 == 0: tmp_multipolarity.append(f"M{j}") else: tmp_multipolarity.append(f"E{j}") else: """ If there is not a change in parity: Even numbered electric and odd numbered magnetic. """ for j in allowed_j: if j%2 == 0: tmp_multipolarity.append(f"E{j}") else: tmp_multipolarity.append(f"M{j}") allowed_multipolarities_list.append(tmp_multipolarity) elem = " <-> ".join(elem) else: elem = elem.rstrip(".txt") elem = elem.split("_")[-1] elem = elem.lstrip("j") allowed_multipolarities_list.append([]) print(f"{i}: {elem}") allowed_multipolarities_list = np.array(allowed_multipolarities_list, dtype=object) # Numpy arrays support indexing with lists of indices. while True: """ Prompt user for a single index or indices separated by comma. The latter is converted to a list and used as indices to the correct path and accompanying allowed multipolarity. """ choice = input("Choose a log file for inspection: ") try: choice = ast.literal_eval(choice) except (SyntaxError, ValueError): print("Input must be an index or comma separated indices!") continue try: if isinstance(choice, int): path_log = [content[choice]] allowed_multipolarities = [allowed_multipolarities_list[choice]] elif isinstance(choice, Iterable): choice = list(choice) path_log = content[choice] allowed_multipolarities = allowed_multipolarities_list[choice] else: continue break except IndexError: print(f"Input indices cannot be larger than {len(content) - 1}.") continue print(f"{path_log} chosen") path_log = [f"{path}/{log}" for log in path_log] # Prepend entire path (relative or absolute depending on user input). elif os.path.isfile(path): """ If path to a single log file is given. """ path_log = [path] elem = path_log[0].split("/")[-1] elem = elem.rstrip(".txt") elem = elem.split("_")[-2:] elem[0] = elem[0].lstrip("j") elem[1] = elem[1].lstrip("j") delta_parity = elem[0][-1] != elem[1][-1] j_i = int(elem[0][:-1])/2 # Initial total angular momentum. j_f = int(elem[1][:-1])/2 # Final. if delta_parity: j_max = 1 # Because KSHELL doesnt support M2. else: j_max = 2 # Because KSHELL supports max. E2. allowed_j = np.arange(max(np.abs(j_i - j_f), 1), min(j_i + j_f, j_max) + 1, 1, dtype=int) # Possible j couplings. tmp_multipolarity = [] if delta_parity: """ If there is a change in parity: Even numbered magnetic and odd numbered electric. """ for j in allowed_j: if j%2 == 0: tmp_multipolarity.append(f"M{j}") else: tmp_multipolarity.append(f"E{j}") else: """ If there is not a change in parity: Even numbered electric and odd numbered magnetic. """ for j in allowed_j: if j%2 == 0: tmp_multipolarity.append(f"E{j}") else: tmp_multipolarity.append(f"M{j}") allowed_multipolarities = [tmp_multipolarity] else: msg = "Input 'path' must be a file or directory!" raise FileNotFoundError(msg) for i, log in enumerate(path_log): if "_tr_" not in log: msg = "Inspection implemented only for transition log files (for now)." msg += f"\n{log = }" raise NotImplementedError(msg) for multipolarity in allowed_multipolarities[i]: j_f = [] idx_f = [] E_f = [] j_i = [] idx_i = [] E_i = [] E_x = [] mred = [] B_decay = [] B_excite = [] mom = [] with open(log, "r") as infile: for line in infile: """ Find where 'multipolarity' starts in the log file. """ if f"{multipolarity} transition" not in line: continue else: break infile.readline() # Skip a line. for line in infile: try: tmp_j_f, tmp_idx_f, tmp_E_f, tmp_j_i, tmp_idx_i, tmp_E_i, \ tmp_E_x, tmp_mred, tmp_B_decay, tmp_B_excite, tmp_mom = \ [ast.literal_eval(i) for i in line.split()] j_f.append(tmp_j_f) idx_f.append(tmp_idx_f) E_f.append(tmp_E_f) j_i.append(tmp_j_i) idx_i.append(tmp_idx_i) E_i.append(tmp_E_i) E_x.append(tmp_E_x) mred.append(tmp_mred) B_decay.append(tmp_B_decay) B_excite.append(tmp_B_excite) mom.append(tmp_mom) except ValueError: break j_f = np.array(j_f) idx_f = np.array(idx_f) E_f = np.array(E_f) j_i = np.array(j_i) idx_i = np.array(idx_i) E_i = np.array(E_i) E_x = np.array(E_x) mred = np.array(mred) B_decay = np.array(B_decay) B_excite = np.array(B_excite) mom = np.array(mom) print(f"{multipolarity} inspection summary of {log.split('/')[-1]}") print(f"{np.mean(B_decay) = }") print(f"{np.min(B_decay) = }") print(f"{np.max(B_decay) = }") print(f"{sum(B_decay) = }") print(f"{sum(B_decay == 0) = }") print(f"{sum(B_decay != 0) = }") print(f"{len(B_decay) = }") print() <file_sep>from __future__ import annotations """ usage: count_dim.py foo.snt bar.ptn count M-scheme dimension Author: <NAME> Modified by: https://github.com/GaffaSnobb """ from functools import lru_cache import sys, math, time, multiprocessing, os from typing import TextIO, Tuple def _readline_sk( fp: TextIO, ) -> list: """ Skips lines starting with '#' or '!'. Splits and returns all other lines. Parameters ---------- fp: TextIOWrapper of .snt or .ptn file. Returns ------- arr: The current line in 'fp' split by whitespace. """ arr = fp.readline().split() while arr[0][0] in ['!','#']: arr = fp.readline().split() return arr def read_snt( model_space_filename: str ) -> Tuple[list, list, list, list, list, list]: """ Parameters ---------- model_space_filename : str The filename of the .snt model space file. Returns ------- orbits_proton_neutron : list The number of proton and neutron valence orbitals. TODO: Double check. core_protons_neutrons : list The number of protons and neutrons in the core. norb : list List of n orbital numbers. lorb : list List of l orbital numbers. jorb : list List of j orbital numbers. itorb : list ? """ fp = open(model_space_filename,'r') arr = _readline_sk(fp) orbits_proton_neutron = [ int(arr[0]), int(arr[1]) ] core_protons_neutrons = [ int(arr[2]), int(arr[3]) ] norb, lorb, jorb, itorb = [], [], [], [] for _ in range(sum(orbits_proton_neutron)): arr = _readline_sk(fp) norb.append( int(arr[1])) lorb.append( int(arr[2])) jorb.append( int(arr[3])) itorb.append(int(arr[4])) fp.close() return orbits_proton_neutron, core_protons_neutrons, norb, lorb, jorb, itorb def read_ptn( partition_filename: str ) -> Tuple[tuple, int, list, list, list]: """ Read partition file (.ptn) and extract information. Parameters ---------- partition_filename : str The filename of the .ptn partition file. Returns ------- valence_protons_neutrons : tuple A tuple containing the number of valence protons and neutrons. Example: (#p, #n). parity : int The parity of the configuration. There are separate files for the configurations of +1 and -1 parity. proton_partition : list The proton occupation for the different orbitals. neutron_partition : list The neutron occupation for the different orbitals. total_partition : list The total proton and neutron configuration (?). """ fp = open(partition_filename, 'r') arr = _readline_sk(fp) valence_protons_neutrons, parity = (int(arr[0]), int(arr[1])), int(arr[2]) arr = _readline_sk(fp) n_idp, n_idn = int(arr[0]), int(arr[1]) proton_partition = [] for _ in range(n_idp): arr = _readline_sk(fp) proton_partition.append(tuple([int(x) for x in arr[1:]])) neutron_partition = [] for _ in range(n_idn): arr = _readline_sk(fp) neutron_partition.append(tuple([int(x) for x in arr[1:]])) arr = _readline_sk(fp) n_idpn = int(arr[0]) total_partition = [] for _ in range(n_idpn): arr = _readline_sk(fp) total_partition.append((int(arr[0])-1, int(arr[1])-1)) fp.close() return valence_protons_neutrons, parity, proton_partition, neutron_partition, total_partition def _mp_add(mp1,mp2): for (m, p), v in mp2.items(): mp1[m,p] = mp1.get((m,p), 0) + v def _mp_product(mp1,mp2): mp = {} for (m1, p1), v1 in mp1.items(): for (m2, p2), v2 in mp2.items(): mp[m1+m2, p1*p2] = mp.get((m1+m2, p1*p2), 0) + v1*v2 return mp def _mps_product(mps): while len(mps) != 1: mp1 = mps.pop(0) mp2 = mps.pop(0) mps.append( _mp_product(mp1, mp2) ) return mps[0] def _set_dim_singlej( jorb ): # set dimension for each single-j orbit as a function of (j, occupation, jz) dim_jnm = {} for j in set( jorb ): dim_jnm[j] = [ {} for x in range(j+2) ] for mbit in range(2**(j+1)): n, m = 0, 0 for i in range(j+1): n += (mbit&2**i)>>i m += ((mbit&2**i)>>i)*(2*i-j) dim_jnm[j][n][m] = dim_jnm[j][n].get(m,0) + 1 return dim_jnm def _parallel(args): dim_mp_parallel = {} i, dim_idp_mp, dim_idn_mp = args # print(i) # Process number for debug. _mp_add( dim_mp_parallel, _mp_product(dim_idp_mp, dim_idn_mp) ) return dim_mp_parallel # @lru_cache(maxsize=None, typed=False) def count_dim( model_space_filename: str, parity: None | int, proton_partition: None | list[list[int]], neutron_partition: None | list[list[int]], total_partition: None | list[list[int]], partition_filename: str | None = None, print_dimensions: bool = True, debug: bool = False, ): """ Product dimension calculation is parallelized. Some timing data for a .ptn file of approximately 1 million lines: TIMING (parallel): ------- ``` where abs. time rel. time timing_read_ptn 0.7270s 0.0326 timing_read_snt 0.0005s 0.0000 timing_set_dim_singlej 0.0016s 0.0001 timing_proton_partition_loop 0.0004s 0.0000 timing_neutron_partition_loop 0.0040s 0.0002 timing_product_dimension 21.5805s 0.9671 timing_data_gather 0.0002s 0.0000 timing_total 22.3142s 1.0000 ``` TIMING (serial): ------- ``` where abs. time rel. time timing_read_ptn 0.7295s 0.0108 timing_read_snt 0.0004s 0.0000 timing_set_dim_singlej 0.0016s 0.0000 timing_proton_partition_loop 0.0004s 0.0000 timing_neutron_partition_loop 0.0035s 0.0001 timing_product_dimension 67.0947s 0.9892 timing_data_gather 0.0003s 0.0000 timing_total 67.8304s 1.0000 ``` Parameters ---------- model_space_filename : str The filename of the .snt file which contains the model space information. Example 'usda.snt'. partition_filename : str The filename of the .ptn file which contains the proton and neutron configuration, with truncation information if applied. print_dimensions : bool For toggling print on / off. debug : bool For toggling debug print on / off. """ if partition_filename is None and (proton_partition is None or neutron_partition is None or total_partition is None or parity is None): msg = ( "If 'partition_filename' is not supplied then 'proton_partition'," " 'neutron_partition', 'total_partition', and 'parity' must be defined." ) raise ValueError(msg) timing_total = time.time() timing_read_snt = time.time() orbits_proton_neutron, core_protons_neutrons, norb, lorb, jorb, itorb = \ read_snt(model_space_filename) timing_read_snt = time.time() - timing_read_snt timing_read_ptn = time.time() if partition_filename is not None: valence_protons_neutrons, parity, proton_partition, neutron_partition, total_partition = \ read_ptn(partition_filename) timing_read_ptn = time.time() - timing_read_ptn timing_set_dim_singlej = time.time() dim_jnm = _set_dim_singlej( jorb ) timing_set_dim_singlej = time.time() - timing_set_dim_singlej timing_proton_partition_loop = time.time() # dimension for proton dim_idp_mp = [] for ptn in proton_partition: """ Loop over all proton partitions. Ex: proton_partition=[(2, 6, 2), (3, 5, 2), (3, 6, 1), (4, 4, 2), (4, 5, 1), (4, 6, 0)] """ mps = [] for i,n in enumerate(ptn): p = (-1)**(lorb[i]*n) j = jorb[i] mps.append( dict( ( (m, p), d ) for m,d in dim_jnm[j][n].items() ) ) dim_idp_mp.append(_mps_product(mps)) timing_proton_partition_loop = time.time() - timing_proton_partition_loop timing_neutron_partition_loop = time.time() # dimension for neutron dim_idn_mp = [] for ptn in neutron_partition: mps = [] for i,n in enumerate(ptn): p = (-1)**( lorb[ orbits_proton_neutron[0]+i ] * n ) j = jorb[ orbits_proton_neutron[0]+i ] mps.append( dict( ( (m, p), d ) for m,d in dim_jnm[j][n].items() ) ) dim_idn_mp.append( _mps_product(mps) ) timing_neutron_partition_loop = time.time() - timing_neutron_partition_loop """ Product dimensions of protons and neutrons. Parallelization gives some penalty for small partition files, but a large speed-up for huge partition files. """ timing_product_dimension = time.time() dim_mp = {} with multiprocessing.Pool() as pool: list_of_dicts = pool.map( _parallel, # [(dim_idp_mp[idp], dim_idn_mp[idn]) for idp, idn in total_partition] [(i, dim_idp_mp[idx[0]], dim_idn_mp[idx[1]]) for i, idx in enumerate(total_partition)] ) for dict_ in list_of_dicts: for key in dict_: try: dim_mp[key] += dict_[key] except KeyError: dim_mp[key] = dict_[key] # dim_mp = {} # for idp, idn in total_partition: # _mp_add( dim_mp, _mp_product(dim_idp_mp[idp], dim_idn_mp[idn]) ) timing_product_dimension = time.time() - timing_product_dimension timing_data_gather = time.time() M, mdim, jdim, mpow, jpow = [], [], [], [], [] # Might be unnecessary to make all of these lists. for m in range( max([x[0] for x in dim_mp]), -1, -2 ): M.append(m) mdim_tmp = dim_mp[m, parity] jdim_tmp = dim_mp[m, parity] - dim_mp.get((m+2, parity), 0) mdim.append(mdim_tmp) jdim.append(jdim_tmp) mpow.append(int( math.log10(mdim_tmp) ) if mdim_tmp != 0 else 0) jpow.append(int( math.log10(jdim_tmp) ) if jdim_tmp != 0 else 0) if print_dimensions: print(" 2*M M-scheme dim. J-scheme dim.") for i in range(len(M)): msg = f"dim. {M[i]:5d}{mdim[i]:21d}{jdim[i]:21d}" msg += f" {mdim[i]/(10**mpow[i]):4.2f}x10^{mpow[i]:2d}" msg += f" {jdim[i]/(10**jpow[i]):4.2f}x10^{jpow[i]:2d}" print(msg) timing_data_gather = time.time() - timing_data_gather timing_total = time.time() - timing_total if debug: print("TIMING:") print("-------") print("where abs. time rel. time") print(f"timing_read_ptn {timing_read_ptn:.4f}s {timing_read_ptn/timing_total:.4f}") print(f"timing_read_snt {timing_read_snt:.4f}s {timing_read_snt/timing_total:.4f}") print(f"timing_set_dim_singlej {timing_set_dim_singlej:.4f}s {timing_set_dim_singlej/timing_total:.4f}") print(f"timing_proton_partition_loop {timing_proton_partition_loop:.4f}s {timing_proton_partition_loop/timing_total:.4f}") print(f"timing_neutron_partition_loop {timing_neutron_partition_loop:.4f}s {timing_neutron_partition_loop/timing_total:.4f}") print(f"timing_product_dimension {timing_product_dimension:.4f}s {timing_product_dimension/timing_total:.4f}") print(f"timing_data_gather {timing_data_gather:.4f}s {timing_data_gather/timing_total:.4f}") print(f"timing_total {timing_total:.4f}s {timing_total/timing_total:.4f}") return M, mdim, jdim def input_choice(content, content_type): if (n := len(content)) > 1: for i in range(n): print(f"{content[i]} ({i}), ", end="") while True: choice = input(": ") try: choice = int(choice) filename = content[choice] break except (ValueError, IndexError): continue elif n == 1: filename = content[0] else: print(f"No {content_type} file in this directory. Exiting...") sys.exit() return filename def handle_input(): try: model_space_filename, partition_filename = sys.argv[1:3] except ValueError: """ Ask for input if none is given in the command line, or choose the only combination of .ptn and .snt. """ dir_content = os.listdir() snt_content = [elem for elem in dir_content if elem.endswith(".snt")] ptn_content = [elem for elem in dir_content if elem.endswith(".ptn")] model_space_filename = input_choice(snt_content, ".snt") partition_filename = input_choice(ptn_content, ".ptn") count_dim(model_space_filename, partition_filename) if __name__ == "__main__": handle_input() <file_sep>""" Author: <NAME> (?) Modified by: <NAME> """ import sys, os, warnings from typing import List, Tuple from fractions import Fraction from math import pi #weisskopf_threshold = 1.0 # threshold to show in W.u. weisskopf_threshold = -0.001 n_jnp = {} E_gs = 0.0 def parity_integer_to_string(i: int) -> str: """ Convert 1 to '+' and -1 to '-'. Parameters ---------- i : int Parity in integer representation. Returns ------- : str The string representation of the parity. """ if i == 1: return '+' else: return '-' def weisskopf_unit(multipole_type: str, mass: int) -> Tuple[float, str]: """ Generate the Weisskopf unit_weisskopf for input multipolarity and mass. Ref. Bohr and Mottelson, Vol.1, p. 389. Parameters ---------- multipole_type : str The electromagnetic character and angular momentum of the gamma radiation. Examples: 'E1', 'M1', 'E2'. mass : int Mass of the nucleus. Returns ------- B_weisskopf : float Reduced transition probability in the Weisskopf estimate. unit_weisskopf : str The accompanying unit. """ l = int(multipole_type[1:]) if multipole_type[0].upper() == "E": B_weisskopf = 1.2**(2*l)/(4*pi)*(3/(l + 3))**2*mass**(2*l/3) unit_weisskopf = f"e^2 fm^{str(2*l)}" elif multipole_type[0].upper() == "M": B_weisskopf = 10/pi*1.2**(2*l - 2)*(3/(l + 3))**2*mass**((2*l - 2)/3) if l == 1: unit_weisskopf = 'mu_N^2 ' else: unit_weisskopf = f"mu_N^2 fm^{str(2*l - 2)}" else: msg = f"Got invalid multipole type: '{multipole_type}'." raise ValueError(msg) return B_weisskopf, unit_weisskopf def read_energy_logfile(filename: str, E_data: dict): """ Extract the energy, spin, and parity for each eigenstate and arrange the data in a dictionary, E_data, where the keys are the energies and the values are tuples of (log filename, spin, parity, eigenstate number, tt). The transition logs will not be read by this function as they do not contain the energy level information. Only the KSHELL logs will be read. Parameters ---------- filename : str The log filename. """ with open(filename, "r") as infile: while True: line = infile.readline() if not line: break if len(line) >= 11 and line[:11] != "H converged": continue if len(line) >= 14 and line[:14] != "H bn converged": continue while True: line = infile.readline() if not line: break if line[6:10] == '<H>:': """ Example: ------------------------------------------------- 1 <H>: -391.71288 <JJ>: -0.00000 J: 0/2 prty -1 <-- this line will be read <Hcm>: 0.00022 <TT>: 6.00000 T: 4/2 <-- this line will be read <p Nj> 5.944 3.678 1.489 3.267 0.123 0.456 0.043 <-- this line will be skipped <n Nj> 5.993 3.902 1.994 5.355 0.546 0.896 0.314 <-- this line will be skipped hw: 1:1.000 <-- this line will be skipped ------------------------------------------------- NOTE: All this substring indexing seems to be easily replaceable with a simple split! """ n_eig = int(line[:5]) # Eigenvalue number. 1, 2, 3, ... energy = float(line[11:22]) spin = int(line[45:48]) # 2*spin actually. parity = int(line[57:59]) parity = parity_integer_to_string(parity) while energy in E_data: energy += 0.000001 # NOTE: To separate energies close together? Else keys may be identical! while True: line = infile.readline() if line[42:45] != ' T:': continue tt = int(line[45:48]) E_data[ energy ] = (filename, spin, parity, n_eig, tt) break def spin_to_string(spin: int) -> str: """ Divide spin by 2 and represent integer results as integers, and fraction results as fractions. NOTE: Tempting to just do str(Fraction(spin/2)) on the negatives too and just let them be negative fractions. Parameters ---------- spin : int Two times the actual spin (for easier integer representation). Returns ------- res : str The actual spin (input divided by 2) represented correctly as an integer or as a fraction. """ if spin < 0: """ For the invalid -1 cases. Spin cannot actually be < 0. """ res = str(spin) else: res = str(Fraction(spin/2)) return res def read_transit_logfile_old( filename: str, multipole_type: str ): """ Extract transit information from transit logfile. Old syntax style, pre 2021-11-24. Parameters ---------- filename : str Filename of the log file. multipole_type : str The electromagnetic character and angular momentum of the gamma radiation. Examples: 'E1', 'M1', 'E2'. Raises ------ Exception: If mass != mass_save. Unsure why mass_save is here at all. ValueError: If the conversion of log file values to int or float cannot be done. This indicates wrong log syntax. """ out_e = {} mass_save = 0 # NOTE: Unclear what this is used for. with open(filename, "r") as infile: for line in infile: """ Fetch mass number, wave function filenames and parities. Loop breaks when the line with parity information is found. """ line_split = line.split() if len(line_split) == 0: continue # Skip empty lines. if 'mass=' in line: """ Fetch mass number. Example: N. of valence protons and neutrons = 15 19 mass= 50 n,z-core 8 8 """ n = line.index('mass=') mass = int(line[n + 5:n + 8]) if not mass_save: mass_save = mass if mass_save != mass: msg = f"ERROR mass: {mass=}, {mass_save=}" raise RuntimeError(msg) B_weisskopf, unit_weisskopf = weisskopf_unit(multipole_type, mass) continue if line_split[0] == 'fn_load_wave_l': filename_wavefunction_left = line_split[2] continue if line_split[0] == 'fn_load_wave_r': filename_wavefunction_right = line_split[2] continue if f"{multipole_type} transition" in line: """ Example: E2 transition e^2 fm^4 eff_charge= 1.3500 0.3500 parity -1 -1 2Jf idx Ef 2Ji idx Ei Ex Mred. B(EM )-> B(EM)<- Mom. 4 1 -387.729 4 1 -387.729 0.000 -20.43244863 83.49699137 83.49699137 -15.48643011 ... """ parity_final = parity_integer_to_string(int(line_split[-2])) parity_initial = parity_integer_to_string(int(line_split[-1])) if filename_wavefunction_left == filename_wavefunction_right: is_diag = True else: is_diag = False break continue # Included for readability. infile.readline() # Skip table header. for line in infile: """ Extract transition data from log_*_tr_*.txt. Example: NEW (higher decimal precision and only whitespace between values): E2 transition e^2 fm^4 eff_charge= 1.3500 0.3500 parity -1 -1 2Jf idx Ef 2Ji idx Ei Ex Mred. B(EM )-> B(EM)<- Mom. 4 1 -387.729 4 1 -387.729 0.000 -20.43244863 83.49699137 83.49699137 -15.48643011 4 1 -387.729 6 2 -387.461 0.267 10.55639593 22.28749899 15.91964213 0.00000000 4 1 -387.729 8 3 -387.196 0.532 14.53838975 42.27295529 23.48497516 0.00000000 4 1 -387.729 6 4 -387.080 0.649 -17.34631937 60.17895916 42.98497083 0.00000000 4 1 -387.729 8 5 -386.686 1.042 -11.24379628 25.28459094 14.04699497 0.00000000 ... OLD: ... 4( 2) -200.706 6( 4) -198.842 1.864 0.0147 0.0000 0.0000 0.0000 4( 2) -200.706 6( 10) -197.559 3.147 -0.0289 0.0002 0.0001 0.0000 ... """ line_split = line.split() if not line_split: break # End file read when blank lines are encountered. if line.startswith("pn="): """ jonkd: I had to add this because 'pn' showed up in the middle of the 'log_Ni56_gxpf1a_tr_m0p_m0p.txt' file after trying (unsuccessfully) to run on Fram. Example: ... 4( 2) -200.706 6( 4) -198.842 1.864 0.0147 0.0000 0.0000 0.0000 pn= 1 # of mbits= 286 4( 2) -200.706 6( 10) -197.559 3.147 -0.0289 0.0002 0.0001 0.0000 ... """ continue try: spin_final = int(line[:2]) idx_1 = int(line[3:7]) spin_initial = int(line[17:19]) idx_2 = int(line[20:24]) dE = float(line[34:42]) # Gamma energy. E_final = float(line[8:17]) - E_gs E_initial = float(line[25:34]) - E_gs B_decay = float(line[52:62]) B_excite = float(line[62:72]) except ValueError as err: msg = f"\n{err.__str__()}" msg += "\nThis might be due to wrong log file syntax." msg += " Try using old_or_new='new' or 'both' as argument" msg += " to collect_logs." msg += f"\n{filename = }" msg += f"\n{line = }" raise ValueError(msg) B_weisskopf_decay = B_decay/B_weisskopf B_weisskopf_excite = B_excite/B_weisskopf if (spin_final == spin_initial) and (idx_1 == idx_2): continue if is_diag and (dE < 0.0): continue if (B_weisskopf_decay < weisskopf_threshold): continue if (B_weisskopf_excite < weisskopf_threshold): continue if abs(E_final) < 1e-3: E_final = 0. if abs(E_initial) < 1e-3: E_initial = 0. idx_1 = n_jnp[ (spin_final, parity_final, idx_1) ] idx_2 = n_jnp[ (spin_initial, parity_initial, idx_2) ] if dE > 0: out = f"{spin_to_string(spin_initial):4s} " out += f"{parity_initial:1s} " out += f"{idx_2:4d} " out += f"{E_initial:9.3f} " out += f"{spin_to_string(spin_final):4s} " out += f"{parity_final:1s} " out += f"{idx_1:4d} " out += f"{E_final:9.3f} " out += f"{dE:9.3f} " out += f"{B_excite:15.8f} " out += f"{B_weisskopf_excite:15.8f} " out += f"{B_decay:15.8f} " out += f"{B_weisskopf_decay:15.8f}\n" key = E_initial + E_final * 1e-5 + spin_initial *1e-10 + idx_2*1e-11 + spin_final*1e-13 + idx_1*1e-14 else: """ NOTE: What is this option used for? In what case is the excitation energy negative? """ out = f"{spin_to_string(spin_final):4s} " out += f"{parity_final:1s} " out += f"{idx_1:4d} " out += f"{E_final:9.3f} " out += f"{spin_to_string(spin_initial):4s} " out += f"{parity_initial:1s} " out += f"{idx_2:4d} " out += f"{E_initial:9.3f} " out += f"{-dE:9.3f} " out += f"{B_decay:15.8f} " out += f"{B_weisskopf_decay:15.8f} " out += f"{B_excite:15.8f} " out += f"{B_weisskopf_excite:15.8f}\n" key = E_final + E_initial * 1e-5 + spin_final *1.e-10 + idx_1*1.e-11 + spin_initial*1.e-12 + idx_2*1.e-14 out_e[key] = out return unit_weisskopf, out_e, mass_save def read_transit_logfile(filename: str, multipole_type: str): """ Extract transit information from transit logfile. Parameters ---------- filename : str Filename of the log file. multipole_type : str The electromagnetic character and angular momentum of the gamma radiation. Examples: 'E1', 'M1', 'E2'. Raises ------ Exception: If mass != mass_save. Unsure why mass_save is here at all. ValueError: If the conversion of log file values to int or float cannot be done. This indicates wrong log syntax. """ out_e = {} mass_save = 0 # NOTE: Unclear what this is used for. unit_weisskopf = None # Stays None if the logfile is invalid. with open(filename, "r") as infile: for line in infile: """ Fetch mass number, wave function filenames and parities. Loop breaks when the line with parity information is found. """ line_split = line.split() if len(line_split) == 0: continue # Skip empty lines. if 'mass=' in line: """ Fetch mass number. Example: N. of valence protons and neutrons = 15 19 mass= 50 n,z-core 8 8 """ n = line.index('mass=') mass = int(line[n + 5:n + 8]) if not mass_save: mass_save = mass if mass_save != mass: msg = f"ERROR mass: {mass=}, {mass_save=}" raise RuntimeError(msg) B_weisskopf, unit_weisskopf = weisskopf_unit(multipole_type, mass) continue if line_split[0] == 'fn_load_wave_l': filename_wavefunction_left = line_split[2] continue if line_split[0] == 'fn_load_wave_r': filename_wavefunction_right = line_split[2] continue if f"{multipole_type} transition" in line: """ Example: E2 transition e^2 fm^4 eff_charge= 1.3500 0.3500 parity -1 -1 2Jf idx Ef 2Ji idx Ei Ex Mred. B(EM )-> B(EM)<- Mom. 4 1 -387.729 4 1 -387.729 0.000 -20.43244863 83.49699137 83.49699137 -15.48643011 ... """ parity_final = parity_integer_to_string(int(line_split[-2])) parity_initial = parity_integer_to_string(int(line_split[-1])) if filename_wavefunction_left == filename_wavefunction_right: is_diag = True else: is_diag = False break continue # Included for readability. infile.readline() # Skip table header. for line in infile: """ Extract transition data from log_*_tr_*.txt. Example: NEW (higher decimal precision and only whitespace between values): E2 transition e^2 fm^4 eff_charge= 1.3500 0.3500 parity -1 -1 2Jf idx Ef 2Ji idx Ei Ex Mred. B(EM )-> B(EM)<- Mom. 4 1 -387.729 4 1 -387.729 0.000 -20.43244863 83.49699137 83.49699137 -15.48643011 4 1 -387.729 6 2 -387.461 0.267 10.55639593 22.28749899 15.91964213 0.00000000 4 1 -387.729 8 3 -387.196 0.532 14.53838975 42.27295529 23.48497516 0.00000000 4 1 -387.729 6 4 -387.080 0.649 -17.34631937 60.17895916 42.98497083 0.00000000 4 1 -387.729 8 5 -386.686 1.042 -11.24379628 25.28459094 14.04699497 0.00000000 ... OLD: ... 4( 2) -200.706 6( 4) -198.842 1.864 0.0147 0.0000 0.0000 0.0000 4( 2) -200.706 6( 10) -197.559 3.147 -0.0289 0.0002 0.0001 0.0000 ... """ line_split = line.split() if not line_split: break # End file read when blank lines are encountered. if line.startswith("pn="): """ jonkd: I had to add this because 'pn' showed up in the middle of the 'log_Ni56_gxpf1a_tr_m0p_m0p.txt' file after trying (unsuccessfully) to run on Fram. Example: ... 4( 2) -200.706 6( 4) -198.842 1.864 0.0147 0.0000 0.0000 0.0000 pn= 1 # of mbits= 286 4( 2) -200.706 6( 10) -197.559 3.147 -0.0289 0.0002 0.0001 0.0000 ... """ continue try: spin_final = int(line_split[0]) idx_1 = int(line_split[1]) E_final = float(line_split[2]) - E_gs spin_initial = int(line_split[3]) idx_2 = int(line_split[4]) E_initial = float(line_split[5]) - E_gs dE = float(line_split[6]) Mred = float(line_split[7]) B_decay = float(line_split[8]) B_excite = float(line_split[9]) Mom = float(line_split[10]) except ValueError as err: msg = f"\n{err.__str__()}" msg += "\nThis might be due to wrong log file syntax." msg += " Try using old_or_new='old' or 'both' as argument to" msg += " collect_logs." msg += f"\n{filename = }" msg += f"\n{line = }" raise ValueError(msg) B_weisskopf_decay = B_decay/B_weisskopf B_weisskopf_excite = B_excite/B_weisskopf if (spin_final == spin_initial) and (idx_1 == idx_2): continue if is_diag and (dE < 0.0): continue if (B_weisskopf_decay < weisskopf_threshold): continue if (B_weisskopf_excite < weisskopf_threshold): continue if abs(E_final) < 1e-3: E_final = 0. if abs(E_initial) < 1e-3: E_initial = 0. idx_1 = n_jnp[ (spin_final, parity_final, idx_1) ] idx_2 = n_jnp[ (spin_initial, parity_initial, idx_2) ] if dE > 0.0: out = f"{spin_to_string(spin_initial):4s} " out += f"{parity_initial:1s} " out += f"{idx_2:4d} " out += f"{E_initial:9.3f} " out += f"{spin_to_string(spin_final):4s} " out += f"{parity_final:1s} " out += f"{idx_1:4d} " out += f"{E_final:9.3f} " out += f"{dE:9.3f} " out += f"{B_excite:15.8f} " out += f"{B_weisskopf_excite:15.8f} " out += f"{B_decay:15.8f} " out += f"{B_weisskopf_decay:15.8f}\n" key = E_initial + E_final * 1e-5 + spin_initial *1e-10 + idx_2*1e-11 + spin_final*1e-13 + idx_1*1e-14 else: """ NOTE: What is this option used for? In what case is the excitation energy negative? """ out = f"{spin_to_string(spin_final):4s} " out += f"{parity_final:1s} " out += f"{idx_1:4d} " out += f"{E_final:9.3f} " out += f"{spin_to_string(spin_initial):4s} " out += f"{parity_initial:1s} " out += f"{idx_2:4d} " out += f"{E_initial:9.3f} " out += f"{-dE:9.3f} " out += f"{B_decay:15.8f} " out += f"{B_weisskopf_decay:15.8f} " out += f"{B_excite:15.8f} " out += f"{B_weisskopf_excite:15.8f}\n" key = E_final + E_initial * 1e-5 + spin_final *1.e-10 + idx_1*1.e-11 + spin_initial*1.e-12 + idx_2*1.e-14 out_e[key] = out return unit_weisskopf, out_e, mass_save def check_multipolarities(path: str="."): """ Check whether E1, M1, and E2 values are present in transit logfiles. Currently only checks that the correct headers are there, not the actual values. Parameters ---------- path : str Path to directory with transit logfiles. """ print("logfile E1 M1 E2 Is it correct?") print("------------------------------------------------------------------------------------") # print("log_V50_sdpf-mu_tr_j12n_j16n.txt True False True") for elem in os.listdir(path): E1 = False should_it_have_E1 = False M1 = False should_it_have_M1 = False E2 = False should_it_have_E2 = False if elem.startswith("log_") and elem.endswith(".txt") and ("_tr_" in elem): tmp = elem[:-4] tmp = tmp.split("_") orbital_1_parity = tmp[-2][-1] orbital_2_parity = tmp[-1][-1] orbital_1_spin = int(tmp[-2][1:-1])/2 orbital_2_spin = int(tmp[-1][1:-1])/2 # spin_diff = abs(orbital_1_spin - orbital_2_spin) spin_range = list(range( int(abs(orbital_1_spin - orbital_2_spin)), int(orbital_1_spin + orbital_2_spin + 1), 1 )) if orbital_1_parity == orbital_2_parity: if (1 in spin_range) and (2 not in spin_range): should_it_have_E1 = False should_it_have_M1 = True should_it_have_E2 = False elif (1 in spin_range) and (2 in spin_range): should_it_have_E1 = False should_it_have_M1 = True should_it_have_E2 = True elif (1 not in spin_range) and (2 in spin_range): should_it_have_E1 = False should_it_have_M1 = False should_it_have_E2 = True else: msg = "No conditions met! (parity change)" raise RuntimeError(msg) elif orbital_1_parity != orbital_2_parity: if (1 in spin_range) and (2 not in spin_range): should_it_have_E1 = True should_it_have_M1 = False should_it_have_E2 = False elif (1 in spin_range) and (2 in spin_range): should_it_have_E1 = True should_it_have_M1 = False should_it_have_E2 = False elif (1 not in spin_range) and (2 in spin_range): """ This condition should never be met since KSHELL will never calculate these transitions. """ should_it_have_E1 = False should_it_have_M1 = False should_it_have_E2 = False msg = "This condition should not ever be met!" raise RuntimeError(msg) else: msg = "No conditions met! (no parity change)" raise RuntimeError(msg) else: msg = "No conditions met! (could not decide parity change)" raise RuntimeError(msg) with open(f"{path}/{elem}", "r") as infile: for line in infile: if "E1 transition" in line: E1 = True elif "M1 transition" in line: M1 = True elif "E2 transition" in line: E2 = True if (E1 == should_it_have_E1) and (M1 == should_it_have_M1) and (E2 == should_it_have_E2): correct = True else: correct = False print(f"{elem:40s}{str(E1):10s}{str(M1):10s}{str(E2):10s}{correct}") def collect_logs(path: str=".", old_or_new: str="new"): """ Collect energy and transition data from all log files in 'path'. Parameters ---------- path : str Path to directory with log files, or parth to single energy log file, if you wanna do that for some reason. old_or_new : str Choose between old or new log file syntax. Pre or post 2021-11-24. Summary file syntax is of new type, regardless. The option "both" is for the rare case of log files of mixed syntax in the same directory. Raises ------ RuntimeError: If no energy log files are found in 'path'. ValueError: If 'old_or_new' is of invalid value. """ allowed_old_or_new = ["new", "old", "both"] old_or_new = old_or_new.lower() if old_or_new not in allowed_old_or_new: msg = f"old_or_new must be in {allowed_old_or_new}. Got {old_or_new}." raise ValueError(msg) energy_log_files = [] transit_log_files = [] isotopes = [] for elem in os.listdir(path): # if elem.startswith("log_") and elem.endswith(".txt"): if ("log_" in elem) and elem.endswith(".txt"): tmp = elem.split("_") isotope_index = tmp.index("log") + 1 # Isotope name is always after 'log'. # if (tmp := elem.split("_")[1].lower()) not in isotopes: if tmp[isotope_index] not in isotopes: isotopes.append(tmp[isotope_index]) if not "_tr_" in elem: energy_log_files.append(f"{path}/{elem}") elif "_tr_" in elem: transit_log_files.append(f"{path}/{elem}") if len(isotopes) > 1: print(f"Log files for different isotopes have been found in {path}") msg = f"Found: {isotopes}. Your choice: " while True: choice = input(msg) if choice in isotopes: break # Remove all log files not of type 'choice'. energy_log_files = [i for i in energy_log_files if choice in i.split("/")[-1].lower()] transit_log_files = [i for i in transit_log_files if choice in i.split("/")[-1].lower()] if len(energy_log_files) == 0: msg = f"No energy log files in path '{path}'." raise FileNotFoundError(msg) if len(transit_log_files) == 0: msg = f"No transit log files in path '{path}', only energy log files." warnings.warn(msg, RuntimeWarning) E_data = {} # E_data[energy] = (log filename, spin, parity, eigenstate number, tt). spin_parity_occurrences = {} # Count the occurrences of each (spin, parity) pair. multipole_types = ["E1", "M1", "E2"] print("Loading energy log files...") for i, log_file in enumerate(energy_log_files): progress_message = f"Reading file {i + 1:3d} of {len(energy_log_files)}," progress_message += f" '{log_file.split('/')[-1]}'" print(progress_message) read_energy_logfile(log_file, E_data) energies = E_data.keys() if len(energies) == 0: msg = "No energy data has been read from energy logs!" raise RuntimeError(msg) energies = sorted(energies) for energy in energies: """ What does this loop actually do...? """ filename, spin, parity, n_eig, tt = E_data[energy] spin_parity = (spin, parity) try: """ Count the number of each (spin, parity) occurrence. """ spin_parity_occurrences[spin_parity] += 1 except KeyError: """ Create initial value if key has not yet occurred. """ spin_parity_occurrences[spin_parity] = 1 n_jnp[ (spin, parity, n_eig) ] = spin_parity_occurrences[spin_parity] E_data[energy] = filename, spin, parity, spin_parity_occurrences[spin_parity], tt global E_gs E_gs = energies[0] counter = 0 filename_without_path = energy_log_files[0].split("/")[-1] isotope = filename_without_path.split("_")[1] model_space = filename_without_path.split("_")[2] while True: """ Create unique summary filename. """ summary_filename = f"summary_{isotope}_{model_space}_{counter:03d}" if os.path.isfile(f"{path}/{summary_filename}.txt"): counter += 1 else: summary_filename += ".txt" break with open(f"{path}/{summary_filename}", "w") as outfile: outfile.write("\n Energy levels\n") outfile.write('\n N J prty N_Jp T E(MeV) Ex(MeV) log-file\n\n') for i, energy in enumerate(energies): filename, spin, parity, n_eig, tt = E_data[energy] out = f"{i + 1:5d} " out += f"{spin_to_string(spin):5s} " out += f"{parity:1s} " out += f"{n_eig:5d} " out += f"{spin_to_string(tt):3s} " out += f"{energy:10.3f} " out += f"{energy - E_gs:10.3f} " out += f"{filename}\n" outfile.write(out) outfile.write("\n") if len(transit_log_files) > 0: print("\nLoading transit log files...") for multipole_type in multipole_types: output_e = {} for i, filename in enumerate(transit_log_files): progress_message = f"Reading file {i + 1:3d} of {len(transit_log_files)}," progress_message += f" multipole: {multipole_type}," progress_message += f" '{filename.split('/')[-1]}'" print(progress_message) if old_or_new == "new": unit_weisskopf, out_e, mass = read_transit_logfile(filename, multipole_type) elif old_or_new == "old": unit_weisskopf, out_e, mass = read_transit_logfile_old(filename, multipole_type) elif old_or_new == "both": try: unit_weisskopf, out_e, mass = read_transit_logfile_old(filename, multipole_type) except ValueError: """ If a ValueError is raised inside read_transit_logfile_old, it is due to the log file being new syntax styled. """ unit_weisskopf, out_e, mass = read_transit_logfile(filename, multipole_type) if unit_weisskopf is None: """ Incomplete and invalid logfile. """ print(f"Incomplete logfile '{filename}'. Skipping...") continue output_e.update(out_e) B_weisskopf, unit_weisskopf = weisskopf_unit(multipole_type, mass) outfile.write(f"B({multipole_type}) ( > {weisskopf_threshold:.1f} W.u.) mass = {mass} 1 W.u. = {B_weisskopf:.1f} {unit_weisskopf}") outfile.write(f"\n{unit_weisskopf} (W.u.)") outfile.write(f"\nJ_i pi_i idx_i Ex_i J_f pi_f idx_f Ex_f dE B({multipole_type})-> B({multipole_type})->[wu] B({multipole_type})<- B({multipole_type})<-[wu]\n") for _, out in sorted(output_e.items()): outfile.write(out) outfile.write("\n\n") return summary_filename<file_sep>from __future__ import annotations from .data_structures import OrbitalOrder GS_FREE_PROTON = 5.585 GS_FREE_NEUTRON = -3.826 flags = {"debug": False, "parallel": True} def debug_mode(switch): if isinstance(switch, bool): flags["debug"] = switch else: print(f"Invalid debug switch '{switch}'") def latex_plot(): import matplotlib.pyplot as plt plt.rcParams.update({ "text.usetex": True, "font.family": "serif", "font.serif": ["roman"], "legend.fontsize": 14, "xtick.labelsize": 15, "ytick.labelsize": 15, "axes.labelsize": 14, "axes.titlesize": 15, "figure.titlesize": 15 }) spectroscopic_conversion: dict[int, str] = { 0: "s", 1: "p", 2: "d", 3: "f", 4: "g", 5: "h" } atomic_numbers = { "oxygen": 8, "fluorine": 9, "neon": 10, "sodium": 11, "magnesium": 12, "aluminium": 13, "silicon": 14, "phosphorus": 15, "sulfur": 16, "chlorine": 17, "argon": 18 } atomic_numbers_reversed = { 8: 'oxygen', 9: 'fluorine', 10: 'neon', 11: 'sodium', 12: 'magnesium', 13: 'aluminium', 14: 'silicon', 15: 'phosphorus', 16: 'sulfur', 17: 'chlorine', 18: 'argon' } elements = { 'h': 1, 'he': 2, 'li': 3, 'be': 4, 'b': 5, 'c': 6, 'n': 7, 'o': 8, 'f': 9, 'ne': 10, 'na': 11, 'mg': 12, 'al': 13, 'si': 14, 'p': 15, 's': 16, 'cl': 17, 'ar': 18, 'k': 19, 'ca': 20, 'sc': 21, 'ti': 22, 'v': 23, 'cr': 24, 'mn': 25, 'fe': 26, 'co': 27, 'ni': 28, 'cu': 29, 'zn': 30, 'ga': 31, 'ge': 32, 'as': 33, 'se': 34, 'br': 35, 'kr': 36, 'rb': 37, 'sr': 38, 'y': 39, 'zr': 40, 'nb': 41, 'mo': 42, 'tc': 43, 'ru': 44, 'rh': 45, 'pd': 46, 'ag': 47, 'cd': 48, 'in': 49, 'sn': 50, 'sb': 51, 'te': 52, 'i': 53, 'xe': 54, 'cs': 55, 'ba': 56, 'la': 57, 'ce': 58, 'pr': 59, 'nd': 60, 'pm': 61, 'sm': 62, 'eu': 63, 'gd': 64, 'tb': 65, 'dy': 66, 'ho': 67, 'er': 68, 'tm': 69, 'yb': 70, 'lu': 71, 'hf': 72, 'ta': 73, 'w': 74, 're': 75, 'os': 76, 'ir': 77, 'pt': 78, 'au': 79, 'hg': 80, 'tl': 81, 'pb': 82, 'bi': 83, 'po': 84, 'at': 85, 'rn': 86, 'fr': 87, 'ra': 88, 'ac': 89, 'th': 90, 'pa': 91, 'u': 92, 'np': 93, 'pu': 94, 'am': 95, 'cm': 96, 'bk': 97, 'cf': 98, 'es': 99, 'fm': 100, 'md': 101, 'no': 102, 'lr': 103, 'rf': 104, 'db': 105, 'sg': 106, 'bh': 107, 'hs': 108, 'mt': 109, 'ds': 110, 'rg': 111, 'cn': 112, 'nh': 113, 'fl': 114, 'mc': 115, 'lv': 116, 'ts': 117, 'og': 118 } recommended_quenching_factors = { "GCLSTsdpfsdgix5pn.snt": f"0.75*GS_FREE = {round(0.75*GS_FREE_PROTON, 3), round(0.75*GS_FREE_NEUTRON, 3)}", "gs8.snt": f"0.75*GS_FREE = {round(0.75*GS_FREE_PROTON, 3), round(0.75*GS_FREE_NEUTRON, 3)}", "jun45.snt": f"0.7*GS_FREE = {round(0.7*GS_FREE_PROTON, 3), round(0.7*GS_FREE_NEUTRON, 3)}", "gxpf1a.snt": f"0.9*GS_FREE = {round(0.9*GS_FREE_PROTON, 3), round(0.9*GS_FREE_NEUTRON, 3)}", "gxpf1.snt": f"0.9*GS_FREE = {round(0.9*GS_FREE_PROTON, 3), round(0.9*GS_FREE_NEUTRON, 3)}", "sdpf-mu.snt": f"0.9*GS_FREE = {round(0.9*GS_FREE_PROTON, 3), round(0.9*GS_FREE_NEUTRON, 3)}", "sn100pn.snt": f"0.7*GS_FREE = {round(0.7*GS_FREE_PROTON, 3), round(0.7*GS_FREE_NEUTRON, 3)}" } # shell_model_order: dict[str, int] = { # Standard shell order for spherical nuclei. # "0s1": 0, # "0p3": 1, # "0p1": 2, # "0d5": 3, # "1s1": 4, # "0d3": 5, # "0f7": 6, # "1p3": 7, # "0f5": 8, # "1p1": 9, # "0g9": 10, # "1d5": 11, # "0g7": 12, # "1d3": 13, # "2s1": 14, # } shell_model_order: dict[str, OrbitalOrder] = { # Standard shell order for spherical nuclei. "0s1": OrbitalOrder(idx=0, major_shell_idx=0, major_shell_name="s"), "0p3": OrbitalOrder(idx=1, major_shell_idx=1, major_shell_name="p"), "0p1": OrbitalOrder(idx=2, major_shell_idx=1, major_shell_name="p"), "0d5": OrbitalOrder(idx=3, major_shell_idx=2, major_shell_name="sd"), "1s1": OrbitalOrder(idx=4, major_shell_idx=2, major_shell_name="sd"), "0d3": OrbitalOrder(idx=5, major_shell_idx=2, major_shell_name="sd"), "0f7": OrbitalOrder(idx=6, major_shell_idx=3, major_shell_name="pf"), "1p3": OrbitalOrder(idx=7, major_shell_idx=3, major_shell_name="pf"), "0f5": OrbitalOrder(idx=8, major_shell_idx=3, major_shell_name="pf"), "1p1": OrbitalOrder(idx=9, major_shell_idx=3, major_shell_name="pf"), "0g9": OrbitalOrder(idx=10, major_shell_idx=4, major_shell_name="sdg"), "1d5": OrbitalOrder(idx=11, major_shell_idx=4, major_shell_name="sdg"), "0g7": OrbitalOrder(idx=12, major_shell_idx=4, major_shell_name="sdg"), "1d3": OrbitalOrder(idx=13, major_shell_idx=4, major_shell_name="sdg"), "2s1": OrbitalOrder(idx=14, major_shell_idx=4, major_shell_name="sdg"), } major_shell_order: dict[str, int] = { "s" : 0, "p" : 1, "sd" : 2, "pf" : 3, "sdg": 4, } <file_sep>import kshell_utilities.kshell_utilities from kshell_utilities.general_utilities import create_spin_parity_list def test_spin_parity_list(): """ Check that all spin-parity pairs appear in spin_parity_list. TODO: Loop over BE2 values too? """ res = kshell_utilities.loadtxt( path = "summary_O19_sdpf-mu.txt", load_and_save_to_file = False, old_or_new = "old" ) n_transitions = len(res.transitions_BM1[:, 0]) spins = res.levels[:, 1] parities = res.levels[:, 2] spin_parity_list = create_spin_parity_list(spins, parities) index_list = [] for transition_idx in range(n_transitions): """ list.index raises ValueError if x is not in list. """ spin_initial = int(res.transitions_BM1[transition_idx, 0]) parity_initial = int(res.transitions_BM1[transition_idx, 1]) index = spin_parity_list.index([spin_initial, parity_initial]) if index not in index_list: index_list.append(index) index_list.sort() for i in range(len(index_list)-1): msg = "Warning! Not all spin parity pairs have been used!" msg += f" {index_list[i+1]} != {index_list[i] + 1}" assert index_list[i+1] == index_list[i] + 1, msg if __name__ == "__main__": test_spin_parity_list()<file_sep>from __future__ import annotations from dataclasses import dataclass, field import numpy as np @dataclass class Skips: n_proton_skips: int = 0 n_neutron_skips: int = 0 n_parity_skips: int = 0 n_ho_skips: int = 0 n_monopole_skips: int = 0 @dataclass class OrbitalOrder: """ For storing information about the general classification of the shell model orbitals. """ idx: int # NOTE: Indices are in the "standard shell model order", not the order of the interaction file. major_shell_idx: int major_shell_name: str @dataclass class OrbitalParameters: """ For storing parameters of the model space orbitals. """ idx: int # Index of the orbital from the interaction file. n: int # The "principal quantum number". l: int # Orbital angular momentum. j: int # Total angular momentum. tz: int # Isospin. nucleon: str # 'p' or 'n'. name: str # Ex: 'p 0d5/2'. parity: int order: OrbitalOrder ho_quanta: int # Harmonic oscillator quanta (2*n + l) of the orbital (little bit unsure if this is a good name). Used to limit the possible combinations of pn configuration combinations. def __str__(self): return self.name @dataclass class ModelSpace: orbitals: list[OrbitalParameters] = field(default_factory=list) major_shell_names: set[str] = field(default_factory=set) n_major_shells: int = 0 n_orbitals: int = 0 n_valence_nucleons: int = 0 @dataclass class Interaction: model_space: ModelSpace = field(default_factory=ModelSpace) model_space_proton: ModelSpace = field(default_factory=ModelSpace) model_space_neutron: ModelSpace = field(default_factory=ModelSpace) name: str = "" n_core_protons: int = 0 n_core_neutrons: int = 0 n_spe: int = 0 spe: list[float] = field(default_factory=list) # Single-particle energies. n_tbme: int = 0 # tbme: list[list[int | float]] = field(default_factory=list) # Two-body matrix elements. tbme: dict[tuple[int, int, int, int, int], float] = field(default_factory=dict) # Two-body matrix elements. fmd_mass: int = 0 # Dont know what this is yet. fmd_power: float = 0 # The exponent of fmd_mass. vm: np.ndarray = field(default_factory=lambda: np.zeros(shape=0, dtype=float)) # Dont know what this is yet. @dataclass class Configuration: """ Terminology: - "Occupation" refers to the number of particles occupying one orbital. Ex: 1 is an occupation. - "Configuration" refers to a set of orbitals with a given occupation. Ex: [0, 1, 1, 0, 0, 0] is a configuration. - "Partition" refers to a set of configurations with a given number of particles. Ex: [[0, 1, 1, 0, 0, 0], [0, 1, 0, 1, 0, 0]] is a partition. Parameters ---------- parity : int The parity of the configuration. configuration : list[int] The configuration as a list of occupations. Ex: [0, 1, 1, 0, 0, 0]. ho_quanta : int The sum of the harmonic oscillator quanta of all the particles in the configuration. Used to limit the possible combinations of pn configuration combinations when using hw truncation. energy : float | None The energy of the combined pn configuration. For just proton configurations and just neutron configurations the energy has not yet been properly defined and is therefore set to None. is_original : bool If True, the configuration existed in the original partition file. If the configuration is new, then False. NOTE: Snce the total configurations are re-calculated, they are set to is_original = True if both proton and neutron configuration which it is built of of is is_original = True. There might however be a problem with this, namely that if the user changes the max H.O. quanta, then previously disallowed combinations of the original proton and neutron configurations might now be allowed, and these new total configurations will subsequently be is_original = True even though they are not. """ parity: int configuration: list[int] ho_quanta: int energy: float | None is_original: bool def __lt__(self, other): if isinstance(other, Configuration): return self.configuration < other.configuration return NotImplemented def __le__(self, other): if isinstance(other, Configuration): return self.configuration <= other.configuration return NotImplemented def __gt__(self, other): if isinstance(other, Configuration): return self.configuration > other.configuration return NotImplemented def __ge__(self, other): if isinstance(other, Configuration): return self.configuration >= other.configuration return NotImplemented def __eq__(self, other): if isinstance(other, Configuration): return self.configuration == other.configuration return NotImplemented def __ne__(self, other): if isinstance(other, Configuration): return self.configuration != other.configuration return NotImplemented @dataclass class Partition: """ Parameters ---------- parity : int The parity of the partition file. Properties ---------- n_configurations : int The number of configurations. """ configurations: list[Configuration] = field(default_factory=list) parity: int = 0 n_existing_positive_configurations: int = 0 n_existing_negative_configurations: int = 0 n_new_positive_configurations: int = 0 n_new_negative_configurations: int = 0 ho_quanta_min_opposite_parity: int = +1000 ho_quanta_max_opposite_parity: int = -1000 ho_quanta_min_this_parity: int = +1000 ho_quanta_max_this_parity: int = -1000 ho_quanta_min: int = +1000 ho_quanta_max: int = -1000 min_configuration_energy: float = 0.0 # Is this also the ground state energy? max_configuration_energy: float = 0.0 max_configuration_energy_original: float = 0.0 @property def n_configurations(self) -> int: expected = ( self.n_existing_negative_configurations + self.n_existing_positive_configurations + self.n_new_negative_configurations + self.n_new_positive_configurations ) calculated = len(self.configurations) assert expected == calculated return calculated @property def n_new_configurations(self) -> int: return self.n_new_negative_configurations + self.n_new_positive_configurations @property def n_existing_configurations(self) -> int: return self.n_existing_negative_configurations + self.n_existing_positive_configurations def clear(self): self.configurations.clear() self.n_existing_positive_configurations = 0 self.n_existing_negative_configurations = 0 self.n_new_positive_configurations = 0 self.n_new_negative_configurations = 0 self.ho_quanta_min_this_parity = +1000 self.ho_quanta_max_this_parity = -1000 <file_sep>import os from kshell_utilities.data_structures import OrbitalParameters from kshell_utilities.partition_editor import partition_editor from kshell_utilities.other_tools import HidePrint def test_partition_editor(): """ Add one proton and one neutron configuration to Ni67_gs8_n.ptn with a 1hw truncation and check that the new partition file is constructed correctly. """ def input_wrapper_test(arg: str): if (arg == "Add new proton configuration? (y/n): "): return "y" if (arg == "Add another proton configuration? (y/n): "): return "n" if (arg == "p 0d5/2 (remaining: 20): "): return "0" if (arg == "p 0d3/2 (remaining: 20): "): return "0" if (arg == "p 1s1/2 (remaining: 20): "): return "0" if (arg == "p 0f7/2 (remaining: 20): "): return "0" if (arg == "p 0f5/2 (remaining: 20): "): return "6" if (arg == "p 1p3/2 (remaining: 14): "): return "2" if (arg == "p 1p1/2 (remaining: 12): "): return "2" if (arg == "p 0g9/2 (remaining: 10): "): return "2" if (arg == "p 0g7/2 (remaining: 8): "): return "2" if (arg == "p 1d5/2 (remaining: 6): "): return "2" if (arg == "p 1d3/2 (remaining: 4): "): return "2" if (arg == "p 2s1/2 (remaining: 2): "): return "2" if (arg == "Add new neutron configuration? (y/n): "): return "y" if (arg == "n 0d5/2 (remaining: 31): "): return "6" if (arg == "n 0d3/2 (remaining: 25): "): return "4" if (arg == "n 1s1/2 (remaining: 21): "): return "2" if (arg == "n 0f7/2 (remaining: 19): "): return "8" if (arg == "n 0f5/2 (remaining: 11): "): return "6" if (arg == "n 1p3/2 (remaining: 5): "): return "2" if (arg == "n 1p1/2 (remaining: 3): "): return "1" if (arg == "n 0g9/2 (remaining: 2): "): return "2" if (arg == "n 0g7/2 (remaining: 0): "): return "0" if (arg == "n 1d5/2 (remaining: 0): "): return "0" if (arg == "n 1d3/2 (remaining: 0): "): return "0" if (arg == "n 2s1/2 (remaining: 0): "): return "0" if (arg == "Add another neutron configuration? (y/n): "): return "n" msg = f"'{arg}' is not accounted for in the testing procedure!" raise RuntimeError(msg) filename_partition_edited = "tmp_partition_editor_output_can_be_deleted_anytime.ptn" filename_partition_original = "Ni67_gs8_n_test.ptn" partition_editor( filename_interaction = "gs8_test.snt", filename_partition = filename_partition_original, filename_partition_edited = filename_partition_edited, input_wrapper = input_wrapper_test, is_interactive = False, ) with open(filename_partition_edited, "r") as infile_edited, open(filename_partition_original, "r") as infile_original: for i, (line_edited, line_original) in enumerate(zip(infile_edited, infile_original)): """ Loop over the proton configurations, neutron configurations, and metadata and check that they are as expected. """ if line_edited != line_original: if line_edited == " 87 5\n": """ The edited file will have one extra proton and neutron configuration. """ continue if line_edited == " 87 0 0 0 0 6 2 2 2 2 2 2 2\n": """ The edited file will have this as an extra proton configuration. That extra line has its own check in this block. """ assert infile_edited.readline() == "# neutron partition\n" continue if line_edited == " 5 6 4 2 8 6 2 1 2 0 0 0 0\n": """ The edited file will have this as an extra neutron configuration. That extra line has its own check in this block. """ assert infile_edited.readline() == "# partition of proton and neutron\n" continue if line_edited == "435\n": """ The edited file will have more proton-neutron configurations than the original because of the extra proton and neutron configurations. """ break msg = ( f"Error on line {i+1}. {line_edited = }, {line_original = }" ) assert False, msg msg = "Incorrect proton-neutron indices: " for proton_index in range(1, 87+1): """ Check that the proton-neutron indices are calculated correctly. """ for neutron_index in range(1, 5+1): calculated = infile_edited.readline().split() expected = [str(proton_index), str(neutron_index)] assert calculated == expected, f"{msg}{calculated = }, {expected = }" msg = ( "There are still untested lines in the edited file!" " It should be exhausted now!" ) assert not infile_edited.readline(), msg os.remove(filename_partition_edited) # Will be removed only if there is no AssertionError. if __name__ == "__main__": with HidePrint(): test_partition_editor()<file_sep>from __future__ import annotations import sys, time, warnings from typing import Union, Tuple, Optional from fractions import Fraction import numpy as np import matplotlib.pyplot as plt from scipy.stats import chi2 from .parameters import flags, elements # warnings.filterwarnings("error") # To catch warnings with try except. # from scipy.optimize import curve_fit def isotope(name: str, A: int): protons = elements[name] neutrons = A - protons return protons, neutrons def create_spin_parity_list( spins: np.ndarray, parities: np.ndarray ) -> list: """ Pair up input spins and parities in a list of lists. Parameters ---------- spins : np.ndarray Array of spins for each energy level. parities : np.ndarray Array of corresponding parities for each energy level. Returns ------- spins_parities : list A nested list of spins and parities [[spin, parity], ...] sorted with respect to the spin. N is the number of unique spins in 'spins'. Examples -------- Example list: ``` python [[1, +1], [3, +1], [5, +1], [7, +1], [9, +1], [11, +1], [13, +1]] ``` """ spin_parity_list = [] for i in range(len(spins)): if (tmp := [int(spins[i]), int(parities[i])]) in spin_parity_list: continue spin_parity_list.append(tmp) return spin_parity_list def div0(numerator, denominator): """ Suppress ZeroDivisionError, set x/0 to 0, and set inf, -inf and nan to 0. Author <NAME>. Examples -------- >>> div0([1, 1, 1], [1, 2, 0]) array([1. , 0.5, 0. ]) """ with np.errstate(divide='ignore', invalid='ignore'): res = np.true_divide(numerator, denominator) res[~np.isfinite(res)] = 0 # -inf inf NaN return res def gamma_strength_function_average( levels: np.ndarray, transitions: np.ndarray, bin_width: Union[float, int], Ex_min: Union[float, int], Ex_max: Union[float, int], multipole_type: str, prefactor_E1: Union[None, float] = None, prefactor_M1: Union[None, float] = None, prefactor_E2: Union[None, float] = None, initial_or_final: str = "initial", partial_or_total: str = "partial", include_only_nonzero_in_average: bool = True, include_n_levels: Union[None, int] = None, filter_spins: Union[None, list] = None, filter_parities: str = "both", return_n_transitions: bool = False, # plot: bool = False, # save_plot: bool = False ) -> Tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]: """ Calculate the gamma strength function averaged over total angular momenta, parities, and initial excitation energies. Author: <NAME>. Modified by: GaffaSnobb. TODO: Figure out the pre-factors. TODO: Use numpy.logical_or to filter levels and transitions to avoid using many if statements in the loops (less readable, though!). TODO: Make res.transitions_BXL.ji, res.transitions_BXL.pii, etc. class attributes (properties). Parameters ---------- levels : np.ndarray Array containing energy, spin, and parity for each excited state. [[E, 2*spin, parity, idx], ...]. idx counts how many times a state of that given spin and parity has occurred. The first 0+ state will have an idx of 1, the second 0+ will have an idx of 2, etc. transitions : np.ndarray Array containing transition data for the specified multipolarity. OLD: Mx8 array containing [2*spin_final, parity_initial, Ex_final, 2*spin_initial, parity_initial, Ex_initial, E_gamma, B(.., i->f)] OLD NEW: [2*spin_initial, parity_initial, Ex_initial, 2*spin_final, parity_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] NEW: [2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] bin_width : Union[float, int] The width of the energy bins. A bin width of 0.2 contains 20 states of uniform spacing of 0.01. Ex_min : Union[float, int] Lower limit for initial level excitation energy, usually in MeV. Ex_max : Union[float, int] Upper limit for initial level excitation energy, usually in MeV. multipole_type : str Choose whether to calculate for 'E1', 'M1' or 'E2'. NOTE: Currently only M1 and E1 is implemented. prefactor_E1 : Union[None, float] E1 pre-factor from the definition of the GSF. Defaults to a standard value if None. prefactor_M1 : Union[None, float] M1 pre-factor from the definition of the GSF. Defaults to a standard value if None. prefactor_E2 : Union[None, float] E2 pre-factor from the definition of the GSF. Defaults to a standard value if None. initial_or_final : str Choose whether to use the energy of the initial or final state for the transition calculations. NOTE: This may be removed in a future release since the correct alternative is to use the initial energy. partial_or_total : str Choose whether to use the partial level density rho(E_i, J_i, pi_i) or the total level density rho(E_i) for calculating the gamma strength function. Note that the partial level density, the default value, is probably the correct alternative. Using the total level density will introduce an arbitrary scaling depending on how many (J, pi) combinations were included in the calculations. This argument is included for easy comparison between the two densities. See the appendix of PhysRevC.98.064321 for details. include_only_nonzero_in_average : bool If True (default) only non-zero values are included in the final averaging of the gamma strength function. The correct alternative is to use only the non-zero values, so setting this parameter to False should be done with care. include_n_levels : Union[None, int] The number of states per spin to include. Example: include_n_levels = 100 will include only the 100 lowest laying states for each spin. filter_spins : Union[None, list] Which spins to include in the GSF. If None, all spins are included. TODO: Make int valid input too. filter_parities : str Which parities to include in the GSF. 'both', '+', '-' are allowed. return_n_transitions : bool Count the number of transitions, as a function of gamma energy, involved in the GSF calculation and return this number as a third return value. For calculating Porter-Thomas fluctuations in the GSF by r(E_gamma) = sqrt(2/n(E_gamma)) where n is the number of transitions for each gamma energy, used to calculate the GSF. The value n is called n_transitions_array in the code. See for example DOI: 10.1103/PhysRevC.98.054303 for details. plot : bool Toogle plotting on / off. save_plot : bool Toogle saving of plot (as .png with dpi=300) on / off. Variables --------- Ex : np.ndarray The excitation energy of all levels. Ex_initial : np.ndarray The excitation energy of the initial state of a transition. spins : np.ndarray The spins of all levels. parities : np.ndarray The parities of all levels. Returns ------- bins : np.ndarray The bins corresponding to gSF_ExJpiavg (x values for plot). gSF_ExJpiavg : np.ndarray The gamma strength function. """ skip_counter = { # Debug. "Transit: Energy range": 0, "Transit: Number of levels": 0, "Transit: Parity": 0, "Level density: Energy range": 0, "Level density: Number of levels": 0, "Level density: Parity": 0 } total_gsf_time = time.perf_counter() allowed_filter_parities = ["+", "-", "both"] if filter_parities not in allowed_filter_parities: msg = f"filter_parities must be {allowed_filter_parities}" raise TypeError(msg) if filter_parities == "both": filter_parities = [-1, +1] elif filter_parities == "-": filter_parities = [-1] elif filter_parities == "+": filter_parities = [+1] if include_n_levels is None: include_n_levels = np.inf # Include all states. if (Ex_min < 0) or (Ex_max < 0): msg = "Ex_min and Ex_max cannot be negative!" raise ValueError(msg) if Ex_max < Ex_min: msg = "Ex_max cannot be smaller than Ex_min!" raise ValueError(msg) prefactors: dict[str, float] = { # Factor for converting from B(XL) to GSF "M1": 11.5473e-9, # [1/(mu_N**2*MeV**2)]. # "E1": 1.047e-6, "E1": 3.4888977e-7, "E2": 0.80632e-12, # PhysRevC.90.064321 } if prefactor_E1 is not None: """ Override the E1 prefactor. """ prefactors["E1"] = prefactor_E1 if prefactor_M1 is not None: prefactors["M1"] = prefactor_M1 if prefactor_E2 is not None: prefactors["E2"] = prefactor_E2 prefactor = prefactors[multipole_type] # Extract data to a more readable form: n_transitions = len(transitions[:, 0]) n_levels = len(levels[:, 0]) E_ground_state = levels[0, 0] # Read out the absolute ground state energy so we can get relative energies later. try: Ex, spins, parities, level_counter = np.copy(levels[:, 0]), levels[:, 1], levels[:, 2], levels[:, 3] except IndexError as err: msg = f"{err.__str__()}\n" msg += "Error probably due to old tmp files. Use loadtxt parameter" msg += " load_and_save_to_file = 'overwrite' (once) to re-read data from the" msg += " summary file and generate new tmp files." raise Exception(msg) from err if initial_or_final == "initial": Ex_initial_or_final = np.copy(transitions[:, 3]) # To avoid altering the raw data. spin_initial_or_final_idx = 0 parity_initial_or_final_idx = 1 elif initial_or_final == "final": Ex_initial_or_final = np.copy(transitions[:, 7]) # To avoid altering the raw data. spin_initial_or_final_idx = 4 parity_initial_or_final_idx = 5 msg = "Using final states for the energy limits is not correct" msg += " and should only be used for comparison with the correct" msg += " option which is using initial states for the energy limits." warnings.warn(msg, RuntimeWarning) else: msg = "'initial_or_final' must be either 'initial' or 'final'." msg += f" Got {initial_or_final}" raise ValueError(msg) if abs(Ex_initial_or_final[0]) > 10: """ Adjust energies relative to the ground state energy if they have not been adjusted already. The ground state energy is usually minus a few tens of MeV and above, so checking absolute value above 10 MeV is probably safe. Cant check for equality to zero since the initial state will never be zero. NOTE: Just check if the value is negative instead? """ Ex_initial_or_final -= E_ground_state if Ex[0] != 0: """ Adjust energies relative to the ground state energy if they have not been adjusted already. """ Ex -= E_ground_state if (Ex_actual_max := np.max(Ex)) < Ex_max: msg = "Requested max excitation energy is greater than the largest" msg += " excitation energy in the data file." msg += f" Changing Ex_max from {Ex_max} to {Ex_actual_max}." Ex_max = Ex_actual_max print(msg) """ Find index of first and last bin (lower bin edge) where we put counts. It's important to not include the other Ex bins in the averaging later, because they contain zeros which will pull the average down. Bin alternatives: bin_array = np.linspace(0, bin_width*n_bins, n_bins + 1) # Array of lower bin edge energy values bin_array_middle = (bin_array[0: -1] + bin_array[1:])/2 # Array of middle bin values """ Ex_min_idx = int(Ex_min/bin_width) Ex_max_idx = int(Ex_max/bin_width) n_bins = int(np.ceil(Ex_max/bin_width)) # Make sure the number of bins cover the whole Ex region. # Ex_max = bin_width*n_bins # Adjust Ex_max to match the round-off in the bin width. NOTE: Unsure if this is needed. """ B_pixel_sum[Ex_final_idx, E_gamma_idx, spin_parity_idx] contains the summed reduced transition probabilities for all transitions contained within the Ex_final_idx bin, E_gamma_idx bin, and spin_parity_idx bin. B_pixel_counts counts the number of transitions within the same bins. """ spin_parity_list = create_spin_parity_list(spins, parities) # To create a unique index for every [spin, parity] pair. n_unique_spin_parity_pairs = len(spin_parity_list) B_pixel_sum = np.zeros((n_bins, n_bins, n_unique_spin_parity_pairs)) # Summed B(..) values for each pixel. B_pixel_count = np.zeros((n_bins, n_bins, n_unique_spin_parity_pairs)) # The number of transitions. rho_ExJpi = np.zeros((n_bins, n_unique_spin_parity_pairs)) # (Ex, Jpi) matrix to store level density gSF = np.zeros((n_bins, n_bins, n_unique_spin_parity_pairs)) n_transitions_array = np.zeros(n_bins, dtype=int) # Count the number of transitions per gamma energy bin. transit_gsf_time = time.perf_counter() for transition_idx in range(n_transitions): """ Iterate over all transitions in the transitions matrix and add up all reduced transition probabilities and the number of transitions in the correct bins. """ if (Ex_initial_or_final[transition_idx] < Ex_min) or (Ex_initial_or_final[transition_idx] >= Ex_max): """ Check if transition is within min max limits, skip if not. """ skip_counter["Transit: Energy range"] += 1 # Debug. continue idx_initial = transitions[transition_idx, 2] idx_final = transitions[transition_idx, 6] if (idx_initial > include_n_levels) or (idx_final > include_n_levels): """ Include only 'include_n_levels' number of levels. Defaults to np.inf (include all). """ skip_counter["Transit: Number of levels"] += 1 # Debug. continue spin_initial = transitions[transition_idx, 0]/2 spin_final = transitions[transition_idx, 4]/2 if filter_spins is not None: # if (spin_initial not in filter_spins) or (spin_final not in filter_spins): if spin_initial not in filter_spins: """ Skip transitions to or from levels of total angular momentum not in the filter list. """ try: skip_counter[f"Transit: j init: {spin_initial}"] += 1 except KeyError: skip_counter[f"Transit: j init: {spin_initial}"] = 1 continue parity_initial = transitions[transition_idx, 1] parity_final = transitions[transition_idx, 5] if (parity_initial not in filter_parities) or (parity_final not in filter_parities): """ Skip initial or final parities which are not in the filter list. NOTE: Might be wrong to filter on the final parity. """ skip_counter["Transit: Parity"] += 1 continue # Get bin index for E_gamma and Ex. Indices are defined with respect to the lower bin edge. E_gamma_idx = int(transitions[transition_idx, 8]/bin_width) Ex_initial_or_final_idx = int(Ex_initial_or_final[transition_idx]/bin_width) n_transitions_array[E_gamma_idx] += 1 # Count the number of transitions involved in this GSF (Porter-Thomas fluctuations). """ transitions : np.ndarray OLD: Mx8 array containing [2*spin_final, parity_initial, Ex_final, 2*spin_initial, parity_initial, Ex_initial, E_gamma, B(.., i->f)] OLD NEW: [2*spin_initial, parity_initial, Ex_initial, 2*spin_final, parity_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] NEW: [2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, B(.., i->f), B(.., f<-i)] """ spin_initial_or_final = int(transitions[transition_idx, spin_initial_or_final_idx]) # Superfluous int casts? parity_initial_or_final = int(transitions[transition_idx, parity_initial_or_final_idx]) spin_parity_idx = spin_parity_list.index([spin_initial_or_final, parity_initial_or_final]) try: """ Add B(..) value and increment transition count, respectively. NOTE: Hope to remove this try-except by implementing suitable input checks to this function. Note to the note: Will prob. not be removed to keep the ability to compare initial and final. """ B_pixel_sum[Ex_initial_or_final_idx, E_gamma_idx, spin_parity_idx] += \ transitions[transition_idx, 9] B_pixel_count[Ex_initial_or_final_idx, E_gamma_idx, spin_parity_idx] += 1 except IndexError as err: """ NOTE: This error usually occurs because Ex_max is set to limit Ex_final instead of Ex_initial. If so, E_gamma might be larger than Ex_max and thus be placed in a B_pixel outside of the allocated scope. This error has a larger probability of occuring if Ex_max is set to a low value because then the probability of E_gamma = Ex_initial - Ex_final is larger. """ msg = f"{err.__str__()}\n" msg += f"{Ex_initial_or_final_idx=}, {E_gamma_idx=}, {spin_parity_idx=}, {transition_idx=}\n" msg += f"{B_pixel_sum.shape=}\n" msg += f"{transitions.shape=}\n" msg += f"{Ex_max=}\n" msg += f"2*spin_final: {transitions[transition_idx, 4]}\n" msg += f"parity_initial: {transitions[transition_idx, 1]}\n" msg += f"Ex_final: {transitions[transition_idx, 7]}\n" msg += f"2*spin_initial: {transitions[transition_idx, 0]}\n" msg += f"parity_initial: {transitions[transition_idx, 1]}\n" msg += f"Ex_initial: {transitions[transition_idx, 3]}\n" msg += f"E_gamma: {transitions[transition_idx, 8]}\n" msg += f"B(.., i->f): {transitions[transition_idx, 9]}\n" msg += f"B(.., f<-i): {transitions[transition_idx, 10]}\n" raise Exception(msg) from err transit_gsf_time = time.perf_counter() - transit_gsf_time level_density_gsf_time = time.perf_counter() for levels_idx in range(n_levels): """ Calculate the level density for each (Ex, spin_parity) pixel. """ if Ex[levels_idx] >= Ex_max: """ Skip if level is outside range. Only upper limit since decays to levels below the lower limit are allowed. """ skip_counter["Level density: Energy range"] += 1 continue if level_counter[levels_idx] > include_n_levels: """ Include only 'include_n_levels' number of levels. Defaults to np.inf (include all). """ skip_counter["Level density: Number of levels"] += 1 continue if filter_spins is not None: if (spin_tmp := levels[levels_idx, 1]/2) not in filter_spins: """ Skip levels of total angular momentum not in the filter list. """ try: skip_counter[f"Level density: j: {spin_tmp}"] += 1 except KeyError: skip_counter[f"Level density: j: {spin_tmp}"] = 1 continue Ex_idx = int(Ex[levels_idx]/bin_width) spin_parity_idx = \ spin_parity_list.index([spins[levels_idx], parities[levels_idx]]) rho_ExJpi[Ex_idx, spin_parity_idx] += 1 level_density_gsf_time = time.perf_counter() - level_density_gsf_time if partial_or_total == "total": """ Use the total level density, rho(E_i), instead of the partial level density, rho(E_i, J_i, pi_i). Sum over all (J_i, pi_i) pairs and then copy these summed values to all columns in rho_ExJpi. """ tmp_sum = rho_ExJpi.sum(axis=1) for i in range(rho_ExJpi.shape[1]): """ All columns in rho_ExJpi will be identical. This is for compatibility with the following for loop. """ rho_ExJpi[:, i] = tmp_sum msg = "Using the total level density is not correct and" msg += " should only be used when comparing with the correct" msg += " alternative which is using the partial level density." warnings.warn(msg, RuntimeWarning) rho_ExJpi /= bin_width # Normalize to bin width, to get density in MeV^-1. gsf_time = time.perf_counter() for spin_parity_idx in range(n_unique_spin_parity_pairs): """ Calculate gamma strength functions for each [Ex, E_gamma, spin_parity] individually using the partial level density for each [Ex, spin_parity]. """ for Ex_idx in range(n_bins): gSF[Ex_idx, :, spin_parity_idx] = \ prefactor*rho_ExJpi[Ex_idx, spin_parity_idx]*div0( numerator = B_pixel_sum[Ex_idx, :, spin_parity_idx], denominator = B_pixel_count[Ex_idx, :, spin_parity_idx] ) gsf_time = time.perf_counter() - gsf_time avg_gsf_time = time.perf_counter() if include_only_nonzero_in_average: """ Update 20171009 (Midtbø): Took proper care to only average over the non-zero f(Eg,Ex,J,parity_initial) pixels. NOTE: Probably not necessary to set an upper limit on gSF due to the input adjustment of Ex_max. """ gSF_currentExrange = gSF[Ex_min_idx:Ex_max_idx + 1, :, :] gSF_ExJpiavg = div0( numerator = gSF_currentExrange.sum(axis = (0, 2)), denominator = (gSF_currentExrange != 0).sum(axis = (0, 2)) ) else: """ NOTE: Probably not necessary to set an upper limit on gSF due to the input adjustment of Ex_max. """ gSF_ExJpiavg = gSF[Ex_min_idx:Ex_max_idx + 1, :, :].mean(axis=(0, 2)) msg = "Including non-zero values when averaging the gamma strength" msg += " function is not correct and should be used with care!" warnings.warn(msg, RuntimeWarning) avg_gsf_time = time.perf_counter() - avg_gsf_time bins = np.linspace(0, Ex_max, n_bins + 1) bins = (bins[:-1] + bins[1:])/2 # Middle point of the bins. bins = bins[:len(gSF_ExJpiavg)] total_gsf_time = time.perf_counter() - total_gsf_time if flags["debug"]: transit_total_skips = \ sum([skip_counter[key] for key in skip_counter if key.startswith("Transit")]) level_density_total_skips = \ sum([skip_counter[key] for key in skip_counter if key.startswith("Level density")]) n_transitions_included = n_transitions - transit_total_skips n_levels_included = n_levels - level_density_total_skips print("--------------------------------") print(f"{transit_gsf_time = } s") print(f"{level_density_gsf_time = } s") print(f"{gsf_time = } s") print(f"{avg_gsf_time = } s") print(f"{total_gsf_time = } s") print(f"{multipole_type = }") for elem in skip_counter: print(f"Skips: {elem}: {skip_counter[elem]}") # print(f"{skip_counter = }") print(f"{transit_total_skips = }") print(f"{n_transitions = }") print(f"{n_transitions_included = }") print(f"{level_density_total_skips = }") print(f"{n_levels = }") print(f"{n_levels_included = }") print("--------------------------------") if return_n_transitions: return bins, gSF_ExJpiavg, n_transitions_array else: return bins, gSF_ExJpiavg def level_plot( levels: np.ndarray, include_n_levels: int = 1_000, filter_spins: Union[None, list] = None, filter_parity: Union[None, str] = None, ax: Union[None, plt.Axes] = None, color: Union[None, str] = None, line_width: float = 0.4, x_offset_scale: float = 1.0, ): """ Generate a level plot for a single isotope. Spin on the x axis, energy on the y axis. Parameters ---------- levels : np.ndarray NxM array of [[energy, spin, parity, index], ...]. This is the instance attribute 'levels' of ReadKshellOutput. include_n_levels : int The maximum amount of states to plot for each spin. Default set to a large number to indicate ≈ no limit. filter_spins : Union[None, list] Which spins to include in the plot. If None, all spins are plotted. filter_parity : Union[None, str] A filter for parity. If None (default) then the parity of the ground state will be used. `+` is positive, `-` is negative, while `both` gives both parities. ax : Union[None, plt.Axes] matplotlib Axes to plot on. If None, plt.Figure and plt.Axes is generated in this function. color : Union[None, str] Color to use for the levels. If None, the next color in the matplotlib color_cycle iterator is used. line_width : float The width of the level lines. Not really supposed to be changed by the user. Set to 0.2 for comparison plots when both integer and half integer angular momenta are included, 0.4 else. x_offset_scale : float To scale the x offset for the hlines. This is used to fit columns for both integer and half integer angular momenta, as well as both parities. """ ax_input = False if (ax is None) else True if levels[0, 0] != 0: """ Adjust energies relative to the ground state energy. """ energies = levels[:, 0] - levels[0, 0] else: energies = levels[:, 0] spins = levels[:, 1]/2 # levels[:, 1] is 2*spin. parities = levels[:, 2] allowed_filter_parity = [None, "+", "-", "both"] if filter_parity not in allowed_filter_parity: msg = f"Allowed parity filters are: {allowed_filter_parity}." raise ValueError(msg) if filter_parity is None: """ Default to the ground state parity. """ parity_integer: int = [levels[0, 2]] parity_symbol: str = "+" if (levels[0, 2] == 1) else "-" x_offset = 0 # No offset needed for single parity plot. elif filter_parity == "+": parity_symbol: str = filter_parity parity_integer: list = [1] x_offset = 0 elif filter_parity == "-": parity_symbol: str = filter_parity parity_integer: list = [-1] x_offset = 0 elif filter_parity == "both": line_width /= 2 # Make room for both parities. parity_symbol: str = r"-+" parity_integer: list = [-1, 1] x_offset = 1/4*x_offset_scale # Offset for plots containing both parities. if filter_spins is not None: spin_scope = np.unique(filter_spins) # x values for the plot. else: spin_scope = np.unique(spins) counts = {} # Dict to keep tabs on how many levels of each angular momentum have been plotted. if not ax_input: fig, ax = plt.subplots() if color is None: color = next(ax._get_lines.color_cycle) for i in range(len(energies)): if filter_spins is not None: if spins[i] not in filter_spins: """ Skip spins which are not in the filter. """ continue if parities[i] not in parity_integer: continue key: str = f"{spins[i]} + {parities[i]}" try: counts[key] += 1 except KeyError: counts[key] = 1 if counts[key] > include_n_levels: """ Include only the first `include_n_levels` amount of states for any of the spins. """ continue ax.hlines( y = energies[i], xmin = spins[i] - line_width + x_offset*parities[i]*0.9, xmax = spins[i] + line_width + x_offset*parities[i]*0.9, color = color, alpha = 0.5, ) ax.set_xticks(spin_scope) ax.set_xticklabels([f"{Fraction(i)}" + r"$^{" + f"{parity_symbol}" + r"}$" for i in spin_scope]) ax.set_xlabel(r"$j^{\pi}$") ax.set_ylabel(r"$E$ [MeV]") if not ax_input: plt.show() def level_density( levels: np.ndarray, bin_width: Union[int, float], include_n_levels: Union[None, int] = None, filter_spins: Union[None, int, list] = None, filter_parity: Union[None, str, int] = None, E_min: Union[float, int] = 0, E_max: Union[float, int] = np.inf, return_counts: bool = False, plot: bool = False, save_plot: bool = False ) -> Tuple[np.ndarray, np.ndarray]: """ Calculate the level density for a given bin size. Parameters ---------- levels : Union[np.ndarray, list] Nx4 array of [[E, 2*spin, parity, idx], ...] or 1D array / list of only energies. bin_width : Union[int, float] Energy interval of which to calculate the density. include_n_levels : Union[None, int] The number of states per spin to include. Example: include_n_levels = 100 will include only the 100 lowest laying states for each spin. filter_spins : Union[None, int, list] Keep only the levels which have angular momenta in the filter. If None, all angular momenta are kept. Input must be the actual angular momenta values and not 2*j. filter_parity : Union[None, str, int] Keep only levels of parity 'filter_parity'. +1, -1, '+', '-' allowed inputs. E_min : Union[None, float, int] Minimum energy to include in the calculation. E_max : Union[None, float, int] Maximum energy to include in the calculation. If input E_max is larger than the largest E in the data set, E_max is set to that value. return_counts : bool Return the counts per bin instead of the density (density = counts/bin_width). plot : bool For toggling plotting on / off. save_plot : bool Toogle saving of plot (as .png with dpi=300) on / off. Returns ------- bins : np.ndarray The corresponding bins (x value for plotting). density : np.ndarray The level density. Raises ------ ValueError: If any filter is given when energy_levels is a list of only energy levels. TypeError: If input parameters are of the wrong type. """ if not isinstance(levels, np.ndarray): levels = np.array(levels) if not isinstance(filter_spins, (int, float, list, type(None), np.ndarray)): msg = f"'filter_spins' must be of type: int, float, list, None. Got {type(filter_spins)}." raise TypeError(msg) if not isinstance(include_n_levels, (int, type(None))): msg = f"'include_n_levels' must be of type: int, None. Got {type(include_n_levels)}." raise TypeError(msg) if not isinstance(filter_parity, (type(None), int, str)): msg = f"'filter_parity' must be of type: None, int, str. Got {type(filter_parity)}." raise TypeError(msg) if not isinstance(E_min, (int, float)): msg = f"'E_min' must be of type: int, float. Got {type(E_min)}." raise TypeError(msg) if not isinstance(E_max, (int, float)): msg = f"'E_max' must be of type: int, float. Got {type(E_max)}." raise TypeError(msg) if isinstance(filter_parity, str): valid_filter_parity = ["+", "-"] if filter_parity not in valid_filter_parity: msg = f"Valid parity filters are: {valid_filter_parity}." raise ValueError(msg) filter_parity = 1 if (filter_parity == "+") else -1 if isinstance(filter_spins, (int, float)): filter_spins = [filter_spins] if (levels.ndim == 1) and (filter_spins is not None): msg = "Spin filter cannot be applied to a list of only energy levels!" raise ValueError(msg) if (levels.ndim == 1) and (include_n_levels is not None): msg = "Cannot choose the number of levels per spin if 'levels' is only a list of energies!" raise ValueError(msg) if (levels.ndim == 1) and (filter_parity is not None): msg = "Parity filter cannot be applied to a list of only energy levels!" raise ValueError(msg) energy_levels = np.copy(levels) # Just in case. if energy_levels.ndim == 1: """ 'levels' only contains energy values. """ if energy_levels[0] < 0: msg = "Please scale energies relative to the ground state" msg += " energy before calculating the NLD!" raise ValueError(msg) elif energy_levels.ndim == 2: """ 'levels' is a multidimensional array on the form [[E, 2*spin, parity, idx], ...]. Subtract ground state energy from all energies. """ energy_levels[:, 0] -= energy_levels[0, 0] if include_n_levels is not None: """ Include ony 'include_n_levels' of levels per angular momentum and parity pair. """ indices = energy_levels[:, 3] # Counter for the number of levels per spin. energy_levels = energy_levels[indices <= include_n_levels] if filter_spins is not None: """ filter_spins is a list of angular momenta. Inside this if statement we know that 'levels' is a multidimensional array due to the check inside the previous except. levels: """ filter_spins = [2*j for j in filter_spins] # energy_levels has 2*j to avoid fractions. mask_list = [] for j in filter_spins: """ Create a [bool1, bool2, ...] mask for each j. """ mask_list.append(energy_levels[:, 1] == j) energy_levels = energy_levels[np.logical_or.reduce(mask_list)] # Contains only levels of j in the filter. if filter_parity is not None: energy_levels = energy_levels[energy_levels[:, 2] == filter_parity] energy_levels = energy_levels[:, 0] E_max = min(E_max, energy_levels[-1] + 0.1) # E_max cant be larger than the largest energy in the data set. Add small number to include the final level(s) in the counting. if E_max <= E_min: """ This behaviour is OK for angular momentum distribution heatmaps where the NLDs for different angular momenta are compared using the same bin range. In this situation, the density at E_min is of course zero because there are no levels of this energy for the given angular momentum. """ bins = np.array([E_min]) density = np.array([0]) return bins, density bins = np.arange(E_min, E_max + bin_width, bin_width) bins[-1] = E_max # arange will mess up the final bin if it does not match the bin width. n_bins = len(bins) counts = np.zeros(n_bins - 1) for i in range(n_bins - 1): mask_1 = energy_levels >= bins[i] mask_2 = energy_levels < bins[i+1] mask_3 = np.logical_and(mask_1, mask_2) counts[i] = sum(mask_3) # counts[i] = np.sum(bins[i] <= energy_levels[energy_levels < bins[i + 1]]) density = (counts/bin_width) # bins = bins[1:] bins = bins[:-1] # Maybe just a matter of preference...? if plot: fig, ax = plt.subplots() if return_counts: ax.step(bins, counts, color="black") ax.set_ylabel(r"Counts") else: ax.step(bins, density, color="black") ax.set_ylabel(r"NLD [MeV$^{-1}$]") ax.set_xlabel("E [MeV]") ax.legend([f"{bin_width=} MeV"]) ax.grid() if save_plot: fname = "nld.png" print(f"NLD saved as '{fname}'") fig.savefig(fname=fname, dpi=300) plt.show() if return_counts: return bins, density, counts else: return bins, density def porter_thomas( transitions: np.ndarray, Ei: Union[int, float, list], BXL_bin_width: Union[int, float], j_list: Union[list, None] = None, Ei_bin_width: Union[int, float] = 0.1, return_chi2: bool = False, ) -> tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]: """ Calculate the distribution of B(XL)/mean(B(XL)) values scaled to a chi-squared distribution of 1 degree of freedom. Parameters ---------- transitions : np.ndarray Array containing transition data for the specified multipolarity. [2*spin_initial, parity_initial, idx_initial, Ex_initial, 2*spin_final, parity_final, idx_final, Ex_final, E_gamma, B(XL, i->f), B(XL, f<-i)] Ei : int, float, list The initial excitation energy of the transitions where the distribution will be calculated. If Ei is only a number, then a bin of size 'Ei_bin_width' around Ei will be used. If Ei is a list, tuple, or array with both a lower and an upper limit, then all excitation energies in that interval will be used. BXL_bin_width : int, float The bin size of the BXL values for the distribution (not the Ei bin size!). Ei_bin_width : int, float The size of the initial energy bin if 'Ei' is only one number. Will not be used if 'Ei' is both a lower and an upper limit. return_chi2 : bool If True, the chi-squared distribution y values will be returned as a third return value. Returns ------- BXL_bins : np.ndarray The BXL bins (x values). BXL_counts : np.ndarray The number of counts in each BXL_bins bin (y values). rv.pdf(BXL_bins) : np.ndarray The chi-squared distribution y values. """ pt_prepare_data_time = time.perf_counter() if isinstance(Ei, (list, tuple, np.ndarray)): """ If Ei defines a lower and an upper limit. """ Ei_mask = np.logical_and( transitions[:, 3] >= Ei[0], transitions[:, 3] < Ei[-1] ) BXL = transitions[Ei_mask] else: BXL = transitions[np.abs(transitions[:, 3] - Ei) < Ei_bin_width] # Consider only levels around Ei. if j_list is not None: """ Create a mask of j values for the transitions array. Allow only entries with initial angular momenta in j_list. """ if not isinstance(j_list, list): msg = f"j_list must be of type list! Got {type(j_list)}." raise TypeError(msg) j_list = [2*j for j in j_list] # Angular momenta are stored as 2*j to avoid fractions. mask_list = [] for j in j_list: """ Create a [bool1, bool2, ...] mask for each j. """ mask_list.append(BXL[:, 0] == j) BXL = BXL[np.logical_or.reduce(mask_list)] # Contains only transitions of j in the filter. # BXL = np.copy(BXL[:, 9]) # The 9th col. is the reduced decay transition probabilities. n_BXL_before = len(BXL) idxi_masks = [] pii_masks = [] ji_masks = [] BXL_tmp = [] initial_indices = np.unique(BXL[:, 2]).astype(int) initial_parities = np.unique(BXL[:, 1]).astype(int) initial_j = np.unique(BXL[:, 0]) for idxi in initial_indices: idxi_masks.append(BXL[:, 2] == idxi) for pii in initial_parities: pii_masks.append(BXL[:, 1] == pii) for ji in initial_j: ji_masks.append(BXL[:, 0] == ji) n_B_skips = 0 for pii in pii_masks: for idxi in idxi_masks: for ji in ji_masks: mask = np.logical_and(ji, np.logical_and(pii, idxi)) tmp = BXL[mask][:, 9] # 9 is B decay. n_B_skips += sum(tmp == 0) # Count the number of zero values. tmp = tmp[tmp != 0] # Remove all zero values. if not tmp.size: """ Some combinations of masks might not match any levels. """ continue BXL_tmp.extend(tmp/tmp.mean()) BXL = np.asarray(BXL_tmp) BXL.sort() # BXL = BXL/np.mean(BXL) n_BXL_after = len(BXL) if (n_BXL_before - n_B_skips) != n_BXL_after: msg = "The number of BXL values has changed too much during the Porter-Thomas analysis!" msg += f" This should not happen! n_BXL_after should be: {n_BXL_before - n_B_skips}, got: {n_BXL_after}." msg += f"\n{n_BXL_before = }" msg += f"\n{n_BXL_after = }" msg += f"\n{n_B_skips = }" raise RuntimeError(msg) BXL_bins = np.arange(0, BXL[-1] + BXL_bin_width, BXL_bin_width) n_BXL_bins = len(BXL_bins) BXL_counts = np.zeros(n_BXL_bins) pt_prepare_data_time = time.perf_counter() - pt_prepare_data_time pt_count_time = time.perf_counter() for i in range(n_BXL_bins - 1): """ Calculate the number of transitions with BXL values between BXL_bins[i] and BXL_bins[i + 1]. """ BXL_counts[i] = np.sum(BXL_bins[i] <= BXL[BXL < BXL_bins[i + 1]]) pt_count_time = time.perf_counter() - pt_count_time pt_post_process_time = time.perf_counter() rv = chi2(1) BXL_counts = BXL_counts[1:] # Exclude the first data point because chi2(1) goes to infinity and is hard to work with there. BXL_bins = BXL_bins[1:] n_BXL_bins -= 1 # BXL_counts_normalised = BXL_counts/np.trapz(BXL_counts) # Normalize counts. # popt, _ = curve_fit( # f = lambda x, scale: scale*rv.pdf(x), # xdata = BXL_bins, # ydata = BXL_counts, # p0 = [rv.pdf(BXL_bins)[1]/BXL_counts[1]], # method = "lm", # ) # BXL_counts *= popt[0] # Scale counts to match chi2. # BXL_counts_normalised *= np.mean(rv.pdf(BXL_bins)[1:20]/BXL_counts_normalised[1:20]) """ Normalise BXL_counts to the chi2(1) distribution, ie. find a coefficient which makes BXL_counts become chi2(1) by BXL_counts*chi2(1)/BXL_counts = chi2(1). Since any single point in the BXL distribution might over or undershoot chi2(1), I have chosen to use the mean of 19 ([1:20] slice, pretty arbitrary chosen) of these values to make a more stable normalisation coefficient. """ BXL_counts_normalised = BXL_counts*np.mean(rv.pdf(BXL_bins)[1:20]/BXL_counts[1:20]) pt_post_process_time = time.perf_counter() - pt_post_process_time if flags["debug"]: print("--------------------------------") print(f"Porter-Thomas: Prepare data time: {pt_prepare_data_time:.3f} s") print(f"Porter-Thomas: Count time: {pt_count_time:.3f} s") print(f"Porter-Thomas: Post process time: {pt_post_process_time:.3f} s") print(f"{sum(BXL_counts) = }") print(f"{sum(BXL_counts_normalised) = }") print(f"{n_B_skips = }") print(f"{Ei = }") print(f"{Ei_bin_width = }") print("--------------------------------") if return_chi2: # return BXL_bins, BXL_counts, rv.pdf(BXL_bins) return BXL_bins, BXL_counts_normalised, rv.pdf(BXL_bins) else: # return BXL_bins, BXL_counts return BXL_bins, BXL_counts_normalised def nuclear_shell_model(): """ Generate a diagram of the nuclear shell model shell structure. """ plt.rcParams.update({ "backend": "pgf", "text.usetex": True, "font.family": "serif", "font.serif": ["roman"], "legend.fontsize": 14, "xtick.labelsize": 15, "ytick.labelsize": 15, "axes.labelsize": 14, "axes.titlesize": 15, }) fig, ax = plt.subplots(figsize=(6.4, 8)) ax.axis(False) fontsize = 15 x_offset = 0.6 x_text_offset = x_offset - 0.5 first_layer_labels = [ r"$1s$", r"$1p$", r"$1d$", r"$2s$", r"$1f$", r"$2p$", r"$1g$", r"$2d$", r"$3s$" ] first_layer_y = [1, 2.4, 4.2, 4.45, 6.3, 6.8, 9, 10.0, 10.5] second_layer_labels = [ r"$1s_{1/2}$", r"$1p_{3/2}$", r"$1p_{1/2}$", r"$1d_{5/2}$", r"$2s_{1/2}$", r"$1d_{3/2}$", r"$1f_{7/2}$", r"$2p_{3/2}$", r"$1f_{5/2}$", r"$2p_{1/2}$", r"$1g_{9/2}$", r"$2d_{5/2}$", r"$1g_{7/2}$", r"$3s_{1/2}$", r"$2d_{3/2}$" ] second_layer_y = [ first_layer_y[0], first_layer_y[1] - 0.15, first_layer_y[1] + 0.15, first_layer_y[2] - 0.3, first_layer_y[3], first_layer_y[2] + 0.51, first_layer_y[4] - 0.6, first_layer_y[5] - 0.10, first_layer_y[4] + 0.7, first_layer_y[5] + 0.5, first_layer_y[6] - 1.0, first_layer_y[7] - 0.4, first_layer_y[6] + 0.9, first_layer_y[7] + 0.8, first_layer_y[8] ] dash_layer = [ [2 + x_offset, first_layer_y[0], 2.5 + x_offset, second_layer_y[0]], [2 + x_offset, first_layer_y[1], 2.5 + x_offset, second_layer_y[1]], [2 + x_offset, first_layer_y[1], 2.5 + x_offset, second_layer_y[2]], [2 + x_offset, first_layer_y[2], 2.5 + x_offset, second_layer_y[3]], [2 + x_offset, first_layer_y[2], 2.5 + x_offset, second_layer_y[5]], [2 + x_offset, first_layer_y[3], 2.5 + x_offset, second_layer_y[4]], [2 + x_offset, first_layer_y[4], 2.5 + x_offset, second_layer_y[6]], [2 + x_offset, first_layer_y[4], 2.5 + x_offset, second_layer_y[8]], [2 + x_offset, first_layer_y[5], 2.5 + x_offset, second_layer_y[7]], [2 + x_offset, first_layer_y[5], 2.5 + x_offset, second_layer_y[9]], [2 + x_offset, first_layer_y[6], 2.5 + x_offset, second_layer_y[10]], [2 + x_offset, first_layer_y[7], 2.5 + x_offset, second_layer_y[11]], [2 + x_offset, first_layer_y[6], 2.5 + x_offset, second_layer_y[12]], [2 + x_offset, first_layer_y[7], 2.5 + x_offset, second_layer_y[13]], [2 + x_offset, first_layer_y[8], 2.5 + x_offset, second_layer_y[14]], ] core_layer_labels = [ r"$^{16}$O", r"$^{40}$Ca", r"$^{56}$Ni" ] core_layer_y = [ second_layer_y[2] + 0.5, second_layer_y[5] + 0.5, second_layer_y[6] + 0.5 ] occupations = [ 2, 4, 2, 6, 2, 4, 8, 4, 6, 2, 10, 6, 8, 2, 4 ] occupations_y = second_layer_y cum_occupations = [ 2, 8, 20, 28, 50 ] cum_occupations_y = [ second_layer_y[0], second_layer_y[2], second_layer_y[5], second_layer_y[6], second_layer_y[10] ] ax.hlines( # To force the width of the figure. y = 1, xmin = 3.5 + x_offset, xmax = 4.5 + x_offset, color = "white" ) ax.hlines( # To force the width of the figure. y = 1, xmin = 1, xmax = 2, color = "white" ) for y, label in zip(first_layer_y, first_layer_labels): ax.hlines( y = y, xmin = 1 + x_offset, xmax = 2 + x_offset, color = "black", ) fig.text( x = 0.12 + x_text_offset, y = y/13.95 + 0.067, s = label, fontsize = fontsize ) for y, label in zip(second_layer_y, second_layer_labels): ax.hlines( y = y, xmin = 2.5 + x_offset, xmax = 3.5 + x_offset, color = "black", ) fig.text( x = 0.6 + x_text_offset, y = y/14.2 + 0.067, s = label, fontsize = fontsize ) for x1, y1, x2, y2 in dash_layer: ax.plot([x1, x2], [y1, y2], linestyle="dashed", color="black") for occupation, y in zip(occupations, occupations_y): fig.text( x = 0.69 + x_text_offset, y = y/14.2 + 0.067, s = occupation, fontsize = fontsize - 1 ) for occupation, y in zip(cum_occupations, cum_occupations_y): fig.text( x = 0.73 + x_text_offset, y = y/14.2 + 0.067, s = occupation, fontsize = fontsize - 1 ) for y, label in zip(core_layer_y, core_layer_labels): fig.text( x = 0.77 + x_text_offset, y = y/14 + 0.067, s = label, fontsize = fontsize - 1 ) fig.text( x = 0.73 + x_text_offset, y = y/14 + 0.064, s = "---------", fontsize = fontsize - 1 ) # USD x1 = 1.35 x2 = 1.25 y1 = 4.9 y2 = 3.83 ax.vlines( x = x2, ymin = y2, ymax = y1, color = "darkorange", ) fig.text( x = 0.15, y = 0.37, s = "USD", fontsize = 12, rotation = "vertical", color = "darkorange" ) # GXPF y3 = 7.5 y4 = 5.6 ax.vlines( x = x2, ymin = y4, ymax = y3, color = "firebrick", ) fig.text( x = 0.15, y = 0.52, s = "GXPF", fontsize = 12, rotation = "vertical", color = "firebrick" ) # SDPF-MU x4 = x2 - 0.04 ax.vlines( x = x4, ymin = y2, ymax = y3, color = "royalblue", ) fig.text( x = 0.14, y = 0.42, s = "SDPF-MU", fontsize = 12, rotation = "vertical", color = "royalblue" ) #JUN45 y7 = 6.5 y8 = 8.2 x6 = x4 - 0.04 ax.vlines( x = x6, ymin = y8, ymax = y7, color = "green", ) fig.text( x = 0.14, y = 0.59, s = "JUN45", fontsize = 12, rotation = "vertical", color = "green" ) # SDPF-SDG ax.vlines( x = x6 - 0.04, ymin = y2, ymax = 11, color = "mediumorchid", ) fig.text( x = 0.15, y = 0.66, s = "SDPF-SDG", fontsize = 12, rotation = "vertical", color = "mediumorchid" ) # Spectroscopic notation fig.text( x = 0.45, y = 0.93, s = r"$s \;\; p \;\; d \;\; f \;\; g \;\; h$", fontsize = fontsize - 1, color = "black", ) fig.text( x = 0.45, y = 0.92, s = "------------------", fontsize = fontsize - 1, color = "black", ) fig.text( x = 0.415, y = 0.90, s = r"$l: 0 \;\; 1 \;\; 2 \;\; 3 \;\; 4 \;\; 5$", fontsize = fontsize - 1, color = "black", ) fig.text( x = 0.405, y = 0.88, s = r"$\pi:+ - + - \, + \, -$", fontsize = fontsize - 1, color = "black", ) fig.savefig(fname="nuclear_shell_model.png", dpi=500)#, format="eps") plt.show() <file_sep>__author__ = "<NAME>, <NAME>" __version__ = "1.5.1.0" __credits__ = "<NAME>, <NAME>" """ Version legend: a.b.c.d a: major release b: new functionality added c: new feature to existing functionality d: bug fixes """ from .kshell_utilities import * from .general_utilities import * from .kshell_exceptions import * from .count_dim import * from .parameters import * from .compare import Compare from .collect_logs import collect_logs, check_multipolarities from .script_editing import edit_and_queue_executables from .partition_editor import partition_editor, test_partition_editor, test_partition_editor_2 from . import loaders from . import data_structures <file_sep>from __future__ import annotations from typing import Union, Tuple from itertools import cycle, islice import numpy as np import matplotlib.pyplot as plt import seaborn as sns from .kshell_utilities import ReadKshellOutput from .general_utilities import ( level_plot, level_density, gamma_strength_function_average ) class Compare: """ Plot levels, level density and gamma strength function for easy comparison between multiple kshell outputs. """ def __init__(self, kshell_outputs: list[ReadKshellOutput], legend_labels: Union[None, list[str]] = None, ): """ Initialize instance with the given kshell outputs and a default color palette. Parameters ---------- kshell_outputs : list[ReadKshellOutput] list of instances of the `ReadKshellOutput` class to be plotted together. legend_labels : Union[None, list[str]] A list of labels for the legends of the plots. The number of labels must equal the number of elements in `kshell_outputs`. """ type_error_msg = 'kshell_outputs must be a list of ReadKshellOutput' type_error_msg += ' instances (the return value of ksutil.loadtxt).' type_error_msg += ' Eg: ksutil.Compare(kshell_outputs=[V50, V51]).' if not isinstance(kshell_outputs, (list, tuple)): raise TypeError(type_error_msg) else: if not all(isinstance(i, ReadKshellOutput) for i in kshell_outputs): raise TypeError(type_error_msg) if isinstance(legend_labels, list): if len(legend_labels) != len(kshell_outputs): msg = ( "The number of labels must equal the number of" " ReadKshellOutput instances!" ) raise RuntimeError(msg) self._legend_labels = legend_labels self._kshell_outputs = kshell_outputs self._color_palette = sns.color_palette( palette = "tab10", n_colors = len(self._kshell_outputs)) def set_color_palette( self, color_palette: Union[str, list[str], list[tuple]]): """ Set the color palette to use for the plots. Parameters ---------- color_palette : Union[str, list[str], list[tuple]] name of the color palette to use or a list of colors. """ required_number_of_colors = len(self._kshell_outputs) if isinstance(color_palette, str): self._color_palette = sns.color_palette( palette = color_palette, n_colors = required_number_of_colors) elif len(color_palette) >= required_number_of_colors: self._color_palette = color_palette else: warning_message = ( "The supplied color palette is too short. " "Some colors will be repeated.") print(warning_message) self._color_palette = list(islice( cycle(color_palette), required_number_of_colors)) def plot_levels( self, ax: Union[None, plt.Axes] = None, include_n_levels: int = 1_000, filter_spins: Union[None, list] = None, filter_parity: Union[None, str] = None, ): """ Draw level plots for all kshell outputs. Parameters ---------- ax : Union[None, plt.Axes] matplotlib Axes on which to plot. If None, plt.Figure and plt.Axes is generated in this function. See level_plot in general_utilities.py for details on the other parameters. """ ax_input, fig, ax = self._get_fig_and_ax(ax) xticks = {} is_half_integer: bool = any(self._kshell_outputs[0].levels[:, 1]%2 == 1) for kshell_output in self._kshell_outputs: if is_half_integer != any(kshell_output.levels[:, 1]%2 == 1): """ If both integer and half integer angular momentum exsists in two or more kshell data sets, then the line width must be halved to make room for both. """ line_width = 0.2 x_offset_scale = 0.5 break else: """ In this case, the kshell outputs contain either integer or half integer angular momenta, not both. """ line_width = 0.4 x_offset_scale = 1 if self._legend_labels is None: labels: list = [i.nucleus for i in self._kshell_outputs] else: labels: list = self._legend_labels for color, kshell_output, label in zip( self._color_palette, self._kshell_outputs, labels ): level_plot( levels = kshell_output.levels, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parity = filter_parity, ax = ax, color = color, line_width = line_width, x_offset_scale = x_offset_scale, ) for tick_position, tick_label in zip( ax.get_xticks(), [l.get_text() for l in ax.get_xticklabels()] ): xticks[tick_position] = tick_label ax.plot([], [], label=label, color=color) ax.set_xticks(ticks=list(xticks.keys()), labels=list(xticks.values())) ax.legend(loc="lower right") if not ax_input: plt.show() def plot_level_densities( self, ax: Union[None, plt.Axes] = None, bin_width: Union[int, float] = 0.2, include_n_levels: Union[None, int] = None, filter_spins: Union[None, int, list] = None, filter_parity: Union[None, str, int] = None, E_min: Union[float, int] = 0, E_max: Union[float, int] = np.inf ): """ Draw level density plots for all kshell outputs. Parameters ---------- ax : Union[None, plt.Axes] matplotlib Axes on which to plot. If None, plt.Figure and plt.Axes is generated in this function. See level_density in general_utilities.py for details on the other parameters. """ ax_input, fig, ax = self._get_fig_and_ax(ax) ax.set_ylabel(r"NLD [MeV$^{-1}$]") ax.set_xlabel("E [MeV]") ax.legend([f"{bin_width=} MeV"]) for color, kshell_output in zip(self._color_palette, self._kshell_outputs): bins, density = level_density( levels = kshell_output.levels, bin_width = bin_width, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parity = filter_parity, E_min = E_min, E_max = E_max, return_counts = False, plot = False, save_plot = False ) ax.step(bins, density, color=color) if not ax_input: plt.show() def plot_gamma_strength_functions( self, ax: Union[None, plt.Axes] = None, bin_width: Union[float, int] = 0.2, Ex_min: Union[float, int] = 5, Ex_max: Union[float, int] = 50, multipole_type: str = "M1", prefactor_E1: Union[None, float] = None, prefactor_M1: Union[None, float] = None, prefactor_E2: Union[None, float] = None, initial_or_final: str = "initial", partial_or_total: str = "partial", include_only_nonzero_in_average: bool = True, include_n_levels: Union[None, int] = None, filter_spins: Union[None, list] = None, filter_parities: str = "both", return_n_transitions: bool = False, ): """ Draw gamma strength function plots for all kshell outputs. Parameters ---------- ax : Union[None, plt.Axes] matplotlib Axes on which to plot. If None, plt.Figure and plt.Axes is generated in this function. See level_density in general_utilities.py for details on the other parameters. """ ax_input, fig, ax = self._get_fig_and_ax(ax) for color, kshell_output in zip(self._color_palette, self._kshell_outputs): transitions_dict = { "M1": kshell_output.transitions_BM1, "E2": kshell_output.transitions_BE2, "E1": kshell_output.transitions_BE1 } bins, gsf = gamma_strength_function_average( levels = kshell_output.levels, transitions = transitions_dict[multipole_type], bin_width = bin_width, Ex_min = Ex_min, Ex_max = Ex_max, multipole_type = multipole_type, prefactor_E1 = prefactor_E1, prefactor_M1 = prefactor_M1, prefactor_E2 = prefactor_E2, initial_or_final = initial_or_final, partial_or_total = partial_or_total, include_only_nonzero_in_average = include_only_nonzero_in_average, include_n_levels = include_n_levels, filter_spins = filter_spins, filter_parities = filter_parities, return_n_transitions = return_n_transitions ) ax.plot(bins, gsf, color=color) if not ax_input: plt.show() @staticmethod def _get_fig_and_ax( ax: Union[None, plt.Axes] ) -> Tuple[bool, plt.Figure, plt.Axes]: """ Return a matplotlib Figure and Axes on which to plot, and whether these were generated in this function or existed previously. Parameter: ---------- ax : Union[None, plt.Axes] matplotlib Axes on which to plot. If None, plt.Figure and plt.Axes is generated by this function. Returns: -------- ax_input : bool whether a matplotlib Axes was passed. fig : plt.Figure matplotlib Figure on which to plot. ax : plt.Axes matplotlib Axes on which to plot. If a matplotlib Axes object was passed, it is returned unchanged. """ ax_input = False if (ax is None) else True if not ax_input: fig, ax = plt.subplots() else: fig = ax.get_figure() return (ax_input, fig, ax) <file_sep>from typing import Union import numpy as np def generate_states( start: int = 0, stop: int = 14, n_states: int = 100, parity: Union[str, int] = "both" ): """ Generate correct string for input to `kshell_ui.py` when asked for which states to calculate. Copy the string generated by this function and paste it into `kshell_ui.py` when it prompts for states. DEPRECATED: RANGE FUNCTIONALITY WAS ADDED IN kshell_ui.py MAKING THIS FUNCTION OBSOLETE. WILL BE REMOVED. Parameters ---------- start : int The lowest spin value. stop : int The largest spin value. n_states : int The number of states per spin value. parity : Union[str, int] The parity of the states. Allowed values are: 1, -1, 'both', 'positive', 'negative', 'pos', 'neg', '+', '-'. Examples -------- ``` python >>> import kshell_utilities as ksutil >>> ksutil.generate_states(start=0, stop=3, n_states=100, parity="both") 0+100, 0.5+100, 1+100, 1.5+100, 2+100, 2.5+100, 3+100, 0-100, 0.5-100, 1-100, 1.5-100, 2-100, 2.5-100, 3-100, ``` """ allowed_positive_parity_inputs = ["positive", "pos", "+", "1", "+1", 1, "both"] allowed_negative_parity_inputs = ["negative", "neg", "-", "-1", -1, "both"] def correct_syntax(lst): for elem in lst: print(elem, end=", ") if parity in allowed_positive_parity_inputs: positive = [f"{i:g}{'+'}{n_states}" for i in np.arange(start, stop+0.5, 0.5)] correct_syntax(positive) if parity in allowed_negative_parity_inputs: negative = [f"{i:g}{'-'}{n_states}" for i in np.arange(start, stop+0.5, 0.5)] correct_syntax(negative)<file_sep>from __future__ import annotations import os, warnings from .parameters import GS_FREE_PROTON, GS_FREE_NEUTRON def _ask_for_time_input(unit: str, lower_lim: int, upper_lim: int) -> int: """ Input prompting generalized for seconds, minutes, hours, and days. Parameters ---------- unit : str 'seconds', 'minutes', 'hours', or 'days'. lower_lim : int Lower allowed limit for the unit input. upper_lim : int Upper allowed limit for the unit input. Returns ------- ans : int User input for the unit within the limits. """ while True: try: ans = int(input(f"Number of {unit}: ")) except ValueError: print("Only integers are allowed!") continue if lower_lim <= ans <= upper_lim: return ans else: print(f"The number of {unit} must be in the interval [{lower_lim}, {upper_lim}]") continue def edit_and_queue_executables(): """ Simple wrapper for quietly quitting on KeyboardInterrupt without having to indent the entire _edit_and_queue_executables function. """ try: _edit_and_queue_executables() except KeyboardInterrupt: print("\nExiting...") return def _prompt_user_for_values( available_parameters: dict[str, bool], available_parameters_values: dict[str, str | int | float] ): """ Ask the user for the actual values for each of the parameters which are to be changed. """ if available_parameters["job_name"]: available_parameters_values["job_name"] = input("Job name: ") if available_parameters["nodes"]: while True: """ Ask for new number of nodes. """ try: available_parameters_values["nodes"] = int(input("Number of nodes: ")) break except ValueError: print("Only integers are allowed!") continue if available_parameters["seconds"]: available_parameters_values["seconds"] = _ask_for_time_input( unit = "seconds", lower_lim = 0, upper_lim = 59 ) tmp = available_parameters_values["time_parameter_new"].split(":") available_parameters_values["time_parameter_new"] = f"{tmp[0]}:{tmp[1]}:{available_parameters_values['seconds']:02d}" if available_parameters["minutes"]: available_parameters_values["minutes"] = _ask_for_time_input( unit = "minutes", lower_lim = 0, upper_lim = 59 ) tmp = available_parameters_values["time_parameter_new"].split(":") available_parameters_values["time_parameter_new"] = f"{tmp[0]}:{available_parameters_values['minutes']:02d}:{tmp[2]}" if available_parameters["hours"]: available_parameters_values["hours"] = _ask_for_time_input( unit = "hours", lower_lim = 0, upper_lim = 23 ) tmp = available_parameters_values["time_parameter_new"].split(":") tmp_days, _ = tmp[0].split("-") available_parameters_values["time_parameter_new"] = f"{tmp_days}-{available_parameters_values['hours']:02d}:{tmp[1]}:{tmp[2]}" if available_parameters["days"]: available_parameters_values["days"] = _ask_for_time_input( unit = "days", lower_lim = 0, upper_lim = 4 ) tmp = available_parameters_values["time_parameter_new"].split(":") _, tmp_hours = tmp[0].split("-") available_parameters_values["time_parameter_new"] = f"{available_parameters_values['days']}-{tmp_hours}:{tmp[1]}:{tmp[2]}" if available_parameters["quench"]: while True: try: available_parameters_values["quench"] = float(input("quench: ")) break except ValueError: print("Only integers and floats are allowed!") continue def _edit_and_queue_executables(): """ Loop over .sh files generated by 'kshell_ui' and adjust queue system parameters and if possible, queue the .sh file. Currently hard-coded to the slurm system. """ available_parameters: dict[str, bool] = { "nodes": False, "seconds": False, "minutes": False, "hours": False, "days": False, "job_name": False, "quench": False, "queue": False, "apply same values to several or all .sh files": False, # "ask for confirmation per file": False, } available_parameters_values: dict[str, str | int | float] = {key: "" for key in available_parameters.items()} available_parameters_values["time_parameter_new"] = "" # For storing the entire new formatted time parameter string. prompt_user_input: bool = True print("Please choose what parameters you want to alter (y/n) (default n):") for parameter in available_parameters: """ Decide what to do with all parameters. """ while True: ans = input(f"{parameter}: ").lower() if ans == "y": available_parameters[parameter] = True break elif ans == "n": break elif ans == "": break else: continue content = [i for i in os.listdir() if i.endswith(".sh")] content.sort() for elem in content: """ Loop over all .sh files in directory. """ edit_ans = input(f"\nEdit {elem}? (y/n) (default y): ").lower() if edit_ans == "n": print(f"Skipping {elem}") continue print(f"Loading {elem}") time_parameter = "" nodes_parameter = "" job_name_parameter = "" gs_parameter = "" content = "" with open(elem, "r") as infile: """ Extract all file content and other specific lines. """ for line in infile: content += line if "#SBATCH --time=" in line: time_parameter += line elif "#SBATCH --nodes=" in line: nodes_parameter += line elif "#SBATCH --job-name=" in line: job_name_parameter += line elif "gs =" in line: gs_parameter += line if (not content) or ((not time_parameter) and (not nodes_parameter) and (not job_name_parameter)): print(f"Could not extract info from {elem}. Skipping ...") continue # time_parameter_new = time_parameter.split("=")[-1].strip() # '0-00:00:00' d-hh:mm:ss if prompt_user_input: if available_parameters["apply same values to several or all .sh files"]: """ Ask the user only once and start with the same time template for all .sh files. """ prompt_user_input = False available_parameters_values["time_parameter_new"] = '#SBATCH --time=0-00:00:00'.split("=")[-1].strip() # '0-00:00:00' d-hh:mm:ss else: available_parameters_values["time_parameter_new"] = time_parameter.split("=")[-1].strip() # '0-00:00:00' d-hh:mm:ss _prompt_user_for_values( available_parameters = available_parameters, available_parameters_values = available_parameters_values ) if time_parameter: """ Insert new time parameter. """ content_tmp = content.replace(time_parameter, f"#SBATCH --time={available_parameters_values['time_parameter_new']}\n") if (content_tmp == content) and (available_parameters['seconds'] or available_parameters['minutes'] or available_parameters['hours'] or available_parameters['days']): msg = "Time parameter is unchanged. Either str.replace could" msg += " not find a match or new time parameter is identical" msg += " to old time parameter." warnings.warn(msg, RuntimeWarning) else: content = content_tmp if job_name_parameter and available_parameters['job_name']: """ Insert new job name parameter. """ content_tmp = content.replace(job_name_parameter, f"#SBATCH --job-name={available_parameters_values['job_name']}\n") if content_tmp == content: msg = "Job name parameter is unchanged. Either str.replace" msg += " could not find a match or new job name parameter is" msg += " identical to old job name parameter." warnings.warn(msg, RuntimeWarning) else: content = content_tmp if nodes_parameter and available_parameters["nodes"]: """ Insert new nodes parameter. """ nodes_parameter_new = nodes_parameter.split("=")[0] nodes_parameter_new += f"={available_parameters_values['nodes']}\n" content_tmp = content.replace(nodes_parameter, nodes_parameter_new) if content_tmp == content: msg = "Nodes parameter is unchanged. Either str.replace could" msg += " not find a match or new nodes parameter is identical" msg += " to old nodes parameter." warnings.warn(msg, RuntimeWarning) else: content = content_tmp if available_parameters["quench"]: quenching_factor = available_parameters_values["quench"] gs_parameter_new = gs_parameter.split("=")[0] gsp = round(quenching_factor*GS_FREE_PROTON, 2) gsn = round(quenching_factor*GS_FREE_NEUTRON, 2) gs_parameter_new += f"= {gsp}, {gsn}\n" content_tmp = content.replace(gs_parameter, gs_parameter_new) if content_tmp == content: msg = "gs parameter is unchanged. Either str.replace could" msg += " not find a match or new nodes parameter is identical" msg += " to old nodes parameter." warnings.warn(msg, RuntimeWarning) else: content = content_tmp with open(elem, "w") as outfile: outfile.write(content) if available_parameters["queue"]: os.system(f"sbatch {elem}") <file_sep>from __future__ import annotations import time, os, curses, warnings from math import inf from typing import Callable from vum import Vum from .count_dim import count_dim from .kshell_exceptions import KshellDataStructureError from .parameters import ( spectroscopic_conversion, shell_model_order, major_shell_order ) from .data_structures import ( OrbitalParameters, Configuration, ModelSpace, Interaction, Partition, Skips ) from .partition_tools import ( _prompt_user_for_interaction_and_partition, _calculate_configuration_parity, _sanity_checks, configuration_energy, ) from .loaders import load_partition, load_interaction from .partition_compare import _partition_compare warnings.filterwarnings("ignore", category=UserWarning) DELAY: int = 2 # Delay time for time.sleep(DELAY) in seconds PARITY_CURRENT_Y_COORD = 5 # is_duplicate_warning = True y_offset: int = 0 class ScreenDummy: def clear(self): return class VumDummy: def __init__(self) -> None: self.screen = ScreenDummy() self.command_log_length = 0 self.command_log_length = 0 self.n_rows = 0 self.n_cols = 0 self.blank_line = "" def addstr(self, y, x, string, is_blank_line=None): return def input(self, _) -> str: return "n" class VumDummy2(VumDummy): def __init__(self) -> None: super().__init__() # self.answers: list[str] = [ # "n", # Analyse? # "y", # Add config? # "p", # Proton or neutron? # "r", # Single or range? # "2", # N particle N hole? # "2", # How many excitations to add? NOTE: Currently not in use. # "pf", # Initial major shell? # "sdg", # Final major shell? # "n", # Add config? # ] self.answers: list[str] = [ "n", "y", "p", "s", "f", "f", "2", "2", "2", "2", "2", "2", ] def input(self, _) -> str: ans = self.answers.pop(0) print(ans) return ans def _analyse_existing_configuration( vum: Vum, proton_configurations: list[Configuration], neutron_configurations: list[Configuration], input_wrapper: Callable, model_space: list[OrbitalParameters], y_offset: int, n_proton_orbitals: int, ) -> None: """ Prompt the user for an index of an existing configuration and show an analysis of the configuration in question. This function is only used once and exists simply to make the amount of code lines in `_partition_editor` smaller. Parameters ---------- vum : Vum The Vum object to draw the map with. proton_configurations : list[Configuration] The proton configurations to choose from. neutron_configurations : list[Configuration] The neutron configurations to choose from. input_wrapper : Callable The input wrapper to use for user input. model_space : list[OrbitalParameters] The model space orbitals to use for the calculation. y_offset : int The y offset to use for drawing the map. """ pn_configuration_dict: dict[str, list[Configuration]] = { "p": proton_configurations, "n": neutron_configurations, } while True: if input_wrapper("Analyse existing configuration? (y/n)") == "y": while True: p_or_n = input_wrapper("Proton or neutron configuration? (p/n)") if (p_or_n == "p"): is_proton = True is_neutron = False orbital_idx_offset: int = 0 break if (p_or_n == "n"): is_proton = False is_neutron = True orbital_idx_offset: int = n_proton_orbitals # This is needed to index the neutron orbitals correctly when drawing the map. break draw_shell_map(vum=vum, model_space=model_space, is_proton=is_proton, is_neutron=is_neutron) while True: configuration_idx = input_wrapper(f"Choose a {p_or_n} configuration index in 1, 2, ..., {len(pn_configuration_dict[p_or_n])} (q to quit)") if configuration_idx == "q": break try: configuration_idx = int(configuration_idx) except ValueError: draw_shell_map(vum=vum, model_space=model_space, is_proton=is_proton, is_neutron=is_neutron) continue configuration_idx -= 1 # List indices are from 0 while indices in .ptn are from 1. if configuration_idx in range(len(pn_configuration_dict[p_or_n])): current_configuration = pn_configuration_dict[p_or_n][configuration_idx].configuration configuration_parity = 1 for i in range(len(current_configuration)): configuration_parity *= model_space[i].parity**current_configuration[i] if current_configuration[i] else 1 # Avoid multiplication by 0. draw_shell_map( vum = vum, model_space = model_space, is_proton = is_proton, is_neutron = is_neutron, occupation = (orbital_idx_offset + i, current_configuration[i]), ) vum.addstr(y_offset + PARITY_CURRENT_Y_COORD, 0, f"parity current configuration = {configuration_parity}") else: draw_shell_map(vum=vum, model_space=model_space, is_proton=is_proton, is_neutron=is_neutron) else: break # If answer from user is not 'y'. vum.addstr(y_offset + PARITY_CURRENT_Y_COORD, 0, "parity current configuration = None") draw_shell_map(vum=vum, model_space=model_space, is_proton=True, is_neutron=True) def draw_shell_map( vum: Vum, model_space: list[OrbitalParameters], is_proton: bool, is_neutron: bool, occupation: tuple[int, int] | None = None, n_holes: int = 0, ) -> None: """ Draw a simple map of the model space orbitals of the current interaction file. Sort the orbitals based on the shell_model_order dict. Parameters ---------- vum : Vum The Vum object to draw the map with. model_space : list[OrbitalParameters] The model space orbitals to draw. is_proton : bool Whether to draw the proton map. is_neutron : bool Whether to draw the neutron map. occupation : tuple[int, int] | None, optional The occupation of the model space orbitals. The tuple contains (orbital index, occupation). If None, draw the entire map with no occupation, by default None. n_holes : int For indicating the original position of excited particles. Returns ------- None """ y_offset: int = 14 model_space_copy = sorted( # Sort the orbitals based on the shell_model_order dict. model_space, key = lambda orbital: shell_model_order[f"{orbital.n}{spectroscopic_conversion[orbital.l]}{orbital.j}"].idx, reverse = True ) model_space_proton = [orbital for orbital in model_space_copy if orbital.tz == -1] model_space_neutron = [orbital for orbital in model_space_copy if orbital.tz == 1] max_neutron_j: int = max([orbital.j for orbital in model_space_neutron], default=0) max_proton_j: int = max([orbital.j for orbital in model_space_proton], default=0) # Use the max j value to center the drawn orbitals. if is_proton: proton_offset: int = 17 + (max_proton_j + 1)*2 # The offset for the neutron map. is_blank_line: bool = False if occupation is None: """ Draw the entire map with no occupation. """ for i in range(len(model_space_proton)): string = ( f"{model_space_proton[i].idx + 1:2d}" f" {model_space_proton[i].name}" f" {model_space_proton[i].parity:2d} " + " "*(max_proton_j - model_space_proton[i].j) + "-" + " -"*(model_space_proton[i].j + 1) ) vum.addstr(i + y_offset, 0, string) else: """ Re-draw a single orbital with the user inputted occupation. """ location: int = 0 for orbital in model_space_proton: if orbital.idx == occupation[0]: break location += 1 else: msg = ( f"Orbital index {occupation[0]} not found in the" " current model space!" ) raise RuntimeError(msg) string = ( f"{orbital.idx + 1:2d}" f" {orbital.name}" f" {orbital.parity:2d} " + " "*(max_proton_j - orbital.j) + "-" ) if not n_holes: string += "o-"*occupation[1] + " -"*(orbital.j + 1 - occupation[1]) else: string += "o-"*(occupation[1] - n_holes) + "x-"*n_holes + " -"*(orbital.j + 1 - occupation[1]) vum.addstr(location + y_offset, 0, string) else: proton_offset: int = 0 is_blank_line: bool = True if is_neutron: if occupation is None: for i in range(len(model_space_neutron)): string = ( f"{model_space_neutron[i].idx + 1:2d}" f" {model_space_neutron[i].name}" f" {model_space_neutron[i].parity:2d} " + " "*(max_neutron_j - model_space_neutron[i].j) + "-" + " -"*(model_space_neutron[i].j + 1) ) vum.addstr(i + y_offset, proton_offset, string, is_blank_line=is_blank_line) else: """ Re-draw a single orbital with the user inputted occupation. """ location: int = 0 for orbital in model_space_neutron: if orbital.idx == occupation[0]: break location += 1 else: msg = ( f"Orbital index {occupation[0]} not found in the" " current model space!" ) raise RuntimeError(msg) string = ( f"{orbital.idx + 1:2d}" f" {orbital.name}" f" {orbital.parity:2d} " + " "*(max_neutron_j - orbital.j) + "-" ) string += "o-"*occupation[1] + " -"*(orbital.j + 1 - occupation[1]) vum.addstr(location + y_offset, proton_offset, string) def _summary_information( vum: Vum, skips: Skips, filename_interaction: str, filename_partition: str, partition_proton: Partition, partition_neutron: Partition, partition_combined: Partition, interaction: Interaction, M: list[int], mdim: list[int], # n_proton_skips: int, # n_neutron_skips: int, # n_parity_skips: int, # n_ho_skips: int, y_offset: int, mdim_original: int | None = None, ): vum.addstr( y = y_offset, x = 0, string = f"{filename_interaction} -- {filename_partition} -- parity: {partition_combined.parity} -- core pn: ({interaction.n_core_protons}, {interaction.n_core_neutrons}) -- valence pn: ({interaction.model_space_proton.n_valence_nucleons}, {interaction.model_space_neutron.n_valence_nucleons})" ) if mdim_original is None: vum.addstr( y = y_offset + 1, x = 0, string = f"M-scheme dim (M={M[-1]}): {mdim[-1]:d} ({mdim[-1]:.2e})" ) else: vum.addstr( y = y_offset + 1, x = 0, string = f"M-scheme dim (M={M[-1]}): {mdim[-1]:d} ({mdim[-1]:.2e}) (original {mdim_original:d} ({mdim_original:.2e}))" ) # vum.addstr( # y = y_offset + 2, # x = 0, # string = f"n valence protons, neutrons: {interaction.model_space_proton.n_valence_nucleons}, {interaction.model_space_neutron.n_valence_nucleons}" # ) # vum.addstr( # y = y_offset + 3, # x = 0, # string = f"n core protons, neutrons: {interaction.n_core_protons}, {interaction.n_core_neutrons}" # ) vum.addstr( y = y_offset + 2, x = 0, string = f"n proton +, -, sum : ({partition_proton.n_existing_positive_configurations} + {partition_proton.n_new_positive_configurations}), ({partition_proton.n_existing_negative_configurations} + {partition_proton.n_new_negative_configurations}), ({partition_proton.n_existing_configurations} + {partition_proton.n_new_configurations})", ) vum.addstr( y = y_offset + 3, x = 0, string = f"n neutron +, -, sum : ({partition_neutron.n_existing_positive_configurations} + {partition_neutron.n_new_positive_configurations}), ({partition_neutron.n_existing_negative_configurations} + {partition_neutron.n_new_negative_configurations}), ({partition_neutron.n_existing_configurations} + {partition_neutron.n_new_configurations})" ) vum.addstr( y = y_offset + 4, x = 0, string = f"n combined: {partition_combined.n_configurations}" ) vum.addstr( y = y_offset + PARITY_CURRENT_Y_COORD, x = 0, string = "parity current configuration = None" ) vum.addstr( y = y_offset + 6, x = 0, string = f"n proton, neutron configurations will be deleted because of parity or H.O. mismatch: {skips.n_proton_skips, skips.n_neutron_skips}" ) vum.addstr( y = y_offset + 7, x = 0, string = f"n parity, H.O. skips: {skips.n_parity_skips, skips.n_ho_skips}" ) vum.addstr( y = y_offset + 8, x = 0, string = f"Monopole trunc skips: {skips.n_monopole_skips}" ) if partition_combined.max_configuration_energy_original == partition_combined.max_configuration_energy: vum.addstr( y = y_offset + 9, x = 0, string = f"Min, max, diff configuration energy: {partition_combined.min_configuration_energy:.2f}, {partition_combined.max_configuration_energy:.2f}, {abs(partition_combined.min_configuration_energy - partition_combined.max_configuration_energy):.2f}" ) else: vum.addstr( y = y_offset + 9, x = 0, string = f"Min, max, diff configuration energy: {partition_combined.min_configuration_energy:.2f}, {partition_combined.max_configuration_energy:.2f} (original {partition_combined.max_configuration_energy_original:.2f}), {abs(partition_combined.min_configuration_energy - partition_combined.max_configuration_energy):.2f}" ) vum.addstr( y = y_offset + 10, x = 0, string = f"Min H.O.: {partition_combined.ho_quanta_min}, max H.O.: {partition_combined.ho_quanta_max}" ) def _generate_total_configurations( interaction: Interaction, partition_proton: Partition, partition_neutron: Partition, partition_combined: Partition, partition_file_parity: int, skips: Skips, threshold_energy: float, allow_invalid: bool = True, is_recursive: bool = False, ):# -> tuple[int, int]: """ Generate all the possible combinations of proton and neutron configurations. The parities of the proton and neutron configurations must combine multiplicatively to the parity of the partition file. The `combined_configurations` list will be cleared before the new configurations are added. Parameters ---------- partition_file_parity : int The parity of the partition file. Returns ------- None Raises ------ KshellDataStructureError If any proton or neutron configuration is unused. This happens if the parity of the configuration does not multiplicatively combine with any of the configurations of the opposite nucleon to the parity of the partition file. """ ho_quanta_min_before = partition_combined.ho_quanta_min_this_parity ho_quanta_max_before = partition_combined.ho_quanta_max_this_parity assert partition_combined.ho_quanta_min != +1000 # Check that they're not at the default values. assert partition_combined.ho_quanta_max != -1000 partition_combined.clear() neutron_configurations_count: list[int] = [0]*partition_neutron.n_configurations neutron_configurations_parity_skips: list[int] = [0]*partition_neutron.n_configurations neutron_configurations_ho_skips: list[int] = [0]*partition_neutron.n_configurations proton_configurations_count: list[int] = [0]*partition_proton.n_configurations proton_configurations_parity_skips: list[int] = [0]*partition_proton.n_configurations proton_configurations_ho_skips: list[int] = [0]*partition_proton.n_configurations n_monopole_skips = 0 partition_proton.configurations.sort(key=lambda elem: elem.configuration) # Sort configs in lexicographic order. partition_neutron.configurations.sort(key=lambda elem: elem.configuration) for p_idx in range(partition_proton.n_configurations): for n_idx in range(partition_neutron.n_configurations): parity_tmp: int = partition_proton.configurations[p_idx].parity*partition_neutron.configurations[n_idx].parity if parity_tmp != partition_file_parity: """ Only combinations of proton and neutron orbitals with the same parity as the parity of the partition file are accepted. """ neutron_configurations_parity_skips[n_idx] += 1 proton_configurations_parity_skips[p_idx] += 1 continue ho_quanta_tmp: int = ( partition_proton.configurations[p_idx].ho_quanta + partition_neutron.configurations[n_idx].ho_quanta ) if not (partition_combined.ho_quanta_min <= ho_quanta_tmp <= partition_combined.ho_quanta_max): """ The combined harmonic oscillator quanta of the combined proton and neutron orbitals must be within the initial limits. """ neutron_configurations_ho_skips[n_idx] += 1 proton_configurations_ho_skips[p_idx] += 1 continue is_original = partition_proton.configurations[p_idx].is_original and partition_neutron.configurations[n_idx].is_original energy = configuration_energy( interaction = interaction, proton_configuration = partition_proton.configurations[p_idx], neutron_configuration = partition_neutron.configurations[n_idx], ) if (energy > threshold_energy):# and not is_original: """ Skip configurations with energies over the threshold energy only if they are newly generated configurations and not originally existing configurations. """ n_monopole_skips += 1 continue if energy < partition_combined.min_configuration_energy: """ I am not yet sure if this is OK or not. """ msg = ( "A newly calculated pn configuration energy is lower than" " the initial lowest energy pn configuration!" ) raise RuntimeError(msg) neutron_configurations_count[n_idx] += 1 proton_configurations_count[p_idx] += 1 if partition_file_parity == -1: partition_combined.n_new_negative_configurations += 1 if partition_file_parity == +1: partition_combined.n_new_positive_configurations += 1 partition_combined.ho_quanta_min_this_parity = min(partition_combined.ho_quanta_min_this_parity, ho_quanta_tmp) partition_combined.ho_quanta_max_this_parity = max(partition_combined.ho_quanta_max_this_parity, ho_quanta_tmp) partition_combined.configurations.append( Configuration( configuration = [p_idx, n_idx], parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = energy, is_original = is_original, ) ) if is_recursive: assert len(proton_configurations_count) == len(partition_proton.configurations) assert len(neutron_configurations_count) == len(partition_neutron.configurations) assert 0 not in proton_configurations_count, proton_configurations_count # Every config should be used now. assert 0 not in neutron_configurations_count, neutron_configurations_count assert ( partition_proton.n_existing_positive_configurations + partition_proton.n_existing_negative_configurations + partition_proton.n_new_positive_configurations + partition_proton.n_new_negative_configurations ) == partition_proton.n_configurations assert ( partition_neutron.n_existing_positive_configurations + partition_neutron.n_existing_negative_configurations + partition_neutron.n_new_positive_configurations + partition_neutron.n_new_negative_configurations ) == partition_neutron.n_configurations assert ( partition_combined.n_existing_positive_configurations + partition_combined.n_existing_negative_configurations + partition_combined.n_new_positive_configurations + partition_combined.n_new_negative_configurations ) == partition_combined.n_configurations return # The recursive call should only re-generate combined configs. if not allow_invalid: """ Remove proton and neutron configurations which have not been counted. """ for p_idx in reversed(range(partition_proton.n_configurations)): """ Traverse configurations in reverse to preserve the order of deletion. Consider the list ['0', '1', '2', '3', '4']. If we are to delete elements 1 and 3, starting from index 0, we would first delete '1' at position 1 and then '4' at position 3. In reverse however, we would delete '3' at position 3 and then '1' at position 1. """ if proton_configurations_count[p_idx] == 0: if partition_proton.configurations[p_idx].parity == -1: partition_proton.n_new_negative_configurations -= 1 elif partition_proton.configurations[p_idx].parity == +1: partition_proton.n_new_positive_configurations -= 1 else: raise KshellDataStructureError partition_proton.configurations.pop(p_idx) for n_idx in reversed(range(partition_neutron.n_configurations)): if neutron_configurations_count[n_idx] == 0: if partition_neutron.configurations[n_idx].parity == -1: partition_neutron.n_new_negative_configurations -= 1 elif partition_neutron.configurations[n_idx].parity == +1: partition_neutron.n_new_positive_configurations -= 1 else: raise KshellDataStructureError partition_neutron.configurations.pop(n_idx) _generate_total_configurations( # Re-generate combined partition after removing invalid p and n configs. interaction = interaction, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, partition_file_parity = partition_file_parity, skips = skips, threshold_energy = threshold_energy, is_recursive = True, ) # assert ho_quanta_min_before == partition_combined.ho_quanta_min_this_parity, f"{ho_quanta_min_before} != {partition_combined.ho_quanta_min_this_parity}" # assert ho_quanta_max_before == partition_combined.ho_quanta_max_this_parity, f"{ho_quanta_max_before} != {partition_combined.ho_quanta_max_this_parity}" partition_combined.max_configuration_energy = max([configuration.energy for configuration in partition_combined.configurations]) skips.n_proton_skips = len([i for i in proton_configurations_count if i == 0]) # The number of proton configurations which will be removed at the end of this program. skips.n_neutron_skips = len([i for i in neutron_configurations_count if i == 0]) # The number of neutron configurations which will be removed at the end of this program. skips.n_parity_skips = sum(proton_configurations_parity_skips) + sum(neutron_configurations_parity_skips) skips.n_ho_skips = sum(proton_configurations_ho_skips) + sum(neutron_configurations_ho_skips) skips.n_monopole_skips = n_monopole_skips def _check_configuration_duplicate( new_configuration: list[int], existing_configurations: list[Configuration], vum: Vum, interaction: Interaction, is_proton: bool, is_neutron: bool, init_orb_idx: int, n_particles_choice: int, is_duplicate_warning: bool, ) -> bool: """ allow_duplicate_warning : bool The duplicate warnings should just be displayed if the user requested configurations have duplicates in the existing configurations. This program might have some overlap in the configuration generation algorithms and in these cases no duplicate warning should be displayed. """ for i, configuration in enumerate(existing_configurations): if new_configuration == configuration.configuration: duplicate_configuration = [str(i), configuration] break else: return False if not is_duplicate_warning: return True vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, f"DUPLICATE: {new_configuration = }, {duplicate_configuration = }" ) draw_shell_map(vum=vum, model_space=interaction.model_space.orbitals, is_proton=is_proton, is_neutron=is_neutron) for i in range(len(new_configuration)): draw_shell_map( vum = vum, model_space = interaction.model_space.orbitals, is_proton = is_proton, is_neutron = is_neutron, occupation = (i, new_configuration[i]), ) draw_shell_map( vum = vum, model_space = interaction.model_space.orbitals, is_proton = is_proton, is_neutron = is_neutron, occupation = (init_orb_idx, new_configuration[init_orb_idx] + n_particles_choice), n_holes = n_particles_choice, ) return True def _add_npnh_excitations( vum: Vum, input_wrapper: Callable, model_space_slice: ModelSpace, interaction: Interaction, partition: Partition, partition_proton: Partition, partition_neutron: Partition, partition_combined: Partition, nucleon_choice: str, is_proton: bool, is_neutron: bool, ) -> bool: while True: """ Prompt user for the number of particles to excite. """ n_particles_choice = input_wrapper("N-particle N-hole (N)") if n_particles_choice == "q": return False try: n_particles_choice = int(n_particles_choice) except ValueError: continue if n_particles_choice > 2: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, "INVALID: Only supports 1 and 2 particle excitations!" ) continue if n_particles_choice < 1: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, "INVALID: The number of particles must be larger than 0." ) continue break while True: """ Prompt the user for which major shells to include in the N-particle N-hole excitation. """ initial_major_shell_choice = input_wrapper(f"Initial major shell? ({model_space_slice.major_shell_names})") if initial_major_shell_choice == "q": return False if initial_major_shell_choice in model_space_slice.major_shell_names: break while True: """ Prompt the user for which major shells to include in the N-particle N-hole excitation. """ final_major_shell_choice = input_wrapper(f"Final major shell? ({model_space_slice.major_shell_names})") if final_major_shell_choice == "q": return False if final_major_shell_choice in model_space_slice.major_shell_names: break if initial_major_shell_choice == final_major_shell_choice: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, "INVALID: Initial and final major shell cannot be the same!" ) return False if major_shell_order[initial_major_shell_choice] > major_shell_order[final_major_shell_choice]: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, "INVALID: Initial major shell cannot be higher energy than final major shell!" ) return False vum.addstr( # Remove any error messages. vum.n_rows - 3 - vum.command_log_length, 0, " " ) initial_orbital_indices: list[int] = [] # Store the indices of the orbitals which are in the initial major shell. final_orbital_indices: list[int] = [] # Store the indices of the orbitals which are in the final major shell. final_orbital_degeneracy: dict[int, int] = {} # Accompanying degeneracy of the orbital. new_configurations: list[Configuration] = [] # Will be merged with partition.configurations at the end of this function. is_duplicate_warning: bool = True n_duplicate_skips: int = 0 for orb in model_space_slice.orbitals: """ Extract indices and degeneracies of the initial and final orbitals. """ if orb.order.major_shell_name == initial_major_shell_choice: if is_proton: init_orb_idx = orb.idx elif is_neutron: init_orb_idx = orb.idx - interaction.model_space_proton.n_orbitals else: msg = "'is_proton' and 'is_neutron' should never both be True or False at the same time!" raise ValueError(msg) initial_orbital_indices.append(init_orb_idx) elif orb.order.major_shell_name == final_major_shell_choice: if is_proton: final_orb_idx = orb.idx elif is_neutron: final_orb_idx = orb.idx - interaction.model_space_proton.n_orbitals final_orbital_indices.append(final_orb_idx) final_orbital_degeneracy[final_orb_idx] = orb.j + 1 # j is stored as j*2. while True: remove_initial_orbital_choice = input_wrapper(f"Remove any of the initial orbitals? ({[idx + 1 for idx in initial_orbital_indices]}/n)") if remove_initial_orbital_choice == "n": break if remove_initial_orbital_choice == "q": return try: remove_initial_orbital_choice = int(remove_initial_orbital_choice) except ValueError: continue remove_initial_orbital_choice -= 1 try: initial_orbital_indices.remove(remove_initial_orbital_choice) except ValueError: continue if not initial_orbital_indices: return while True: remove_final_orbital_choice = input_wrapper(f"Remove any of the final orbitals? ({[idx + 1 for idx in final_orbital_indices]}/n)") if remove_final_orbital_choice == "n": break if remove_final_orbital_choice == "q": return try: remove_final_orbital_choice = int(remove_final_orbital_choice) except ValueError: continue remove_final_orbital_choice -= 1 try: final_orbital_indices.remove(remove_final_orbital_choice) except ValueError: continue if not final_orbital_indices: return if is_proton: new_ho_quanta_max = partition_proton.ho_quanta_max_this_parity + partition_neutron.ho_quanta_max_this_parity new_ho_quanta_max -= n_particles_choice*interaction.model_space_proton.orbitals[initial_orbital_indices[-1]].ho_quanta new_ho_quanta_max += n_particles_choice*interaction.model_space_proton.orbitals[final_orbital_indices[-1]].ho_quanta if is_neutron: new_ho_quanta_max = partition_proton.ho_quanta_max_this_parity + partition_neutron.ho_quanta_max_this_parity new_ho_quanta_max -= n_particles_choice*interaction.model_space_neutron.orbitals[initial_orbital_indices[-1]].ho_quanta new_ho_quanta_max += n_particles_choice*interaction.model_space_neutron.orbitals[final_orbital_indices[-1]].ho_quanta if new_ho_quanta_max > partition_combined.ho_quanta_max: while True: ho_quanta_max_choice = input_wrapper(f"This NpNh will exceed the max ho quanta ({partition_combined.ho_quanta_max}) with up to {new_ho_quanta_max - partition_combined.ho_quanta_max}. New max?") if ho_quanta_max_choice == "q": return False try: ho_quanta_max_choice = int(ho_quanta_max_choice) except ValueError: continue if ho_quanta_max_choice < partition_combined.ho_quanta_max: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, "INVALID: New max H.O. quanta must be larger than the old value!" ) continue partition_combined.ho_quanta_max = ho_quanta_max_choice break """ NOTE: Gjøre slik at jeg kan velge å legge til n NpNh-eksitasjoner og at de er de med n lavest energi. `init_orb_idx` og `final_orb_idx` inneholder nok det jeg trenger for å gjøre dette valget. Et alternativ er å begrense hele orbitaler i stedet for å velge antall eksitasjoner. F.eks. å bare helt droppe den orbitalen med høyest energi. """ for configuration in partition.configurations: """ Loop over every existing configuration. """ for init_orb_idx in initial_orbital_indices: """ Case: N particles from from the same initial orbital are excited to the same final orbital. """ if configuration.configuration[init_orb_idx] < n_particles_choice: continue # Cannot excite enough particles. for final_orb_idx in final_orbital_indices: """ Both particles to the same final orbital. """ max_additional_occupation = final_orbital_degeneracy[final_orb_idx] - configuration.configuration[final_orb_idx] assert max_additional_occupation >= 0, "'max_additional_occupation' should never be negative!" # Development sanity test. if max_additional_occupation < n_particles_choice: continue # Cannot excite enough particles. new_configuration = configuration.configuration.copy() new_configuration[init_orb_idx] -= n_particles_choice new_configuration[final_orb_idx] += n_particles_choice is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = new_configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = init_orb_idx, n_particles_choice = n_particles_choice, is_duplicate_warning = False ) if is_duplicate_configuration: """ Checking against the newly generated configuraions. """ continue is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = partition.configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = init_orb_idx, n_particles_choice = n_particles_choice, is_duplicate_warning = is_duplicate_warning, ) if is_duplicate_configuration: """ Check that the newly generated configuration does not already exist. """ n_duplicate_skips += 1 if not is_duplicate_warning: continue duplicate_choice = vum.input("Enter any char to continue or 'i' to ignore duplicate warnings (they will still be deleted)") if duplicate_choice == "i": is_duplicate_warning = False continue parity_tmp = _calculate_configuration_parity( configuration = new_configuration, model_space = model_space_slice.orbitals, ) if parity_tmp == -1: partition.n_new_negative_configurations += 1 elif parity_tmp == +1: partition.n_new_positive_configurations += 1 ho_quanta_tmp = sum([ # The number of harmonic oscillator quanta for each configuration. n*orb.ho_quanta for n, orb in zip(new_configuration, model_space_slice.orbitals) ]) new_configurations.append( Configuration( configuration = new_configuration.copy(), parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = None, is_original = False, ) ) if n_particles_choice == 1: """ The next loop of this function only applies for the 2 particle excitation case. """ partition.configurations.extend(new_configurations) if n_duplicate_skips: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, f"DUPLICATE SKIPS: {n_duplicate_skips}" ) return True for configuration in partition.configurations: """ NOTE: Currently hard-coded for 2 particle excitation. This loop deals with the case where 1 particle from 2 different initial orbitals are excited into the final major shell. """ # for init_orb_idx in initial_orbital_indices: for i1 in range(len(initial_orbital_indices)): init_orb_idx_1 = initial_orbital_indices[i1] if configuration.configuration[init_orb_idx_1] < 1: continue # Cannot excite enough particles. for i2 in range(i1+1, len(initial_orbital_indices)): init_orb_idx_2 = initial_orbital_indices[i2] if configuration.configuration[init_orb_idx_2] < 1: continue # Cannot excite enough particles. for f1 in range(len(final_orbital_indices)): final_orb_idx_1 = final_orbital_indices[f1] max_additional_occupation_1 = final_orbital_degeneracy[final_orb_idx_1] - configuration.configuration[final_orb_idx_1] assert max_additional_occupation_1 >= 0, "'max_additional_occupation' should never be negative!" # Development sanity test. if max_additional_occupation_1 < 1: continue # Cannot excite enough particles. for f2 in range(f1+1, len(final_orbital_indices)): final_orb_idx_2 = final_orbital_indices[f2] max_additional_occupation_2 = final_orbital_degeneracy[final_orb_idx_2] - configuration.configuration[final_orb_idx_2] assert max_additional_occupation_2 >= 0, "'max_additional_occupation' should never be negative!" # Development sanity test. if max_additional_occupation_2 < 1: continue # Cannot excite enough particles. new_configuration = configuration.configuration.copy() new_configuration[init_orb_idx_1] -= 1 new_configuration[init_orb_idx_2] -= 1 new_configuration[final_orb_idx_1] += 1 new_configuration[final_orb_idx_2] += 1 is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = new_configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = init_orb_idx, n_particles_choice = n_particles_choice, is_duplicate_warning = False ) if is_duplicate_configuration: """ Checking against the newly generated configuraions. """ continue is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = partition.configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = init_orb_idx, n_particles_choice = n_particles_choice, is_duplicate_warning = is_duplicate_warning, ) if is_duplicate_configuration: """ Check that the newly generated configuration does not already exist. """ n_duplicate_skips += 1 if not is_duplicate_warning: continue duplicate_choice = vum.input("Enter any char to continue or 'i' to ignore duplicate warnings (they will still be deleted)") if duplicate_choice == "i": is_duplicate_warning = False continue parity_tmp = _calculate_configuration_parity( configuration = new_configuration, model_space = model_space_slice.orbitals ) if parity_tmp == -1: partition.n_new_negative_configurations += 1 elif parity_tmp == +1: partition.n_new_positive_configurations += 1 ho_quanta_tmp = sum([ # The number of harmonic oscillator quanta for each configuration. n*orb.ho_quanta for n, orb in zip(new_configuration, model_space_slice.orbitals) ]) new_configurations.append( Configuration( configuration = new_configuration.copy(), parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = None, is_original = False, ) ) for f1 in range(len(final_orbital_indices)): """ Case: Both particles are excited to the same final orbital. """ final_orb_idx_1 = final_orbital_indices[f1] max_additional_occupation_1 = final_orbital_degeneracy[final_orb_idx_1] - configuration.configuration[final_orb_idx_1] assert max_additional_occupation_1 >= 0, "'max_additional_occupation' should never be negative!" # Development sanity test. if max_additional_occupation_1 < n_particles_choice: continue # Cannot excite enough particles. new_configuration = configuration.configuration.copy() new_configuration[init_orb_idx_1] -= 1 new_configuration[init_orb_idx_2] -= 1 new_configuration[final_orb_idx_1] += n_particles_choice is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = new_configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = init_orb_idx, n_particles_choice = n_particles_choice, is_duplicate_warning = False ) if is_duplicate_configuration: """ Checking against the newly generated configuraions. """ continue is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = partition.configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = init_orb_idx, n_particles_choice = n_particles_choice, is_duplicate_warning = is_duplicate_warning, ) if is_duplicate_configuration: """ Check that the newly generated configuration does not already exist. """ n_duplicate_skips += 1 if not is_duplicate_warning: continue duplicate_choice = vum.input("Enter any char to continue or 'i' to ignore duplicate warnings (they will still be deleted)") if duplicate_choice == "i": is_duplicate_warning = False continue parity_tmp = _calculate_configuration_parity( configuration = new_configuration, model_space = model_space_slice.orbitals ) if parity_tmp == -1: partition.n_new_negative_configurations += 1 elif parity_tmp == +1: partition.n_new_positive_configurations += 1 ho_quanta_tmp = sum([ # The number of harmonic oscillator quanta for each configuration. n*orb.ho_quanta for n, orb in zip(new_configuration, model_space_slice.orbitals) ]) new_configurations.append( Configuration( configuration = new_configuration.copy(), parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = None, is_original = False, ) ) partition.configurations.extend(new_configurations) if n_duplicate_skips: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, f"DUPLICATE SKIPS: {n_duplicate_skips}" ) return True def partition_editor( filename_partition_edited: str | None = None, ): """ Wrapper for error handling. """ try: vum: Vum = Vum() vum.screen.clear() # Clear the screen between interactive sessions. program_choice = vum.input("Edit or compare? (e/c)") if program_choice == "e": msg = _partition_editor( filename_partition_edited = filename_partition_edited, vum_wrapper = vum, ) elif program_choice == "c": msg = _partition_compare(vum=vum) else: return except KeyboardInterrupt: curses.endwin() print("Exiting without saving changes...") except curses.error as e: curses.endwin() raise(e) except Exception as e: curses.endwin() raise(e) else: curses.endwin() print(msg) def test_partition_editor( filename_partition: str, filename_interaction: str, filename_partition_edited: str = "test_partition.ptn", ): try: os.remove(filename_partition_edited) except FileNotFoundError: pass vum: VumDummy = VumDummy() _partition_editor( filename_interaction = filename_interaction, filename_partition = filename_partition, filename_partition_edited = filename_partition_edited, vum_wrapper = vum, ) n_lines: int = 0 with open(filename_partition_edited, "r") as infile_edited, open(filename_partition, "r") as infile: for line_edited, line in zip(infile_edited, infile): n_lines += 1 if line_edited != line: line_edited = line_edited.rstrip('\n') line = line.rstrip('\n') msg = ( f"{line_edited} != {line}" ) raise KshellDataStructureError(msg) # else: # print(f"All {n_lines} lines are identical in the files {filename_partition} and {filename_partition_edited}!") try: os.remove(filename_partition_edited) except FileNotFoundError: pass def test_partition_editor_2( filename_partition_edited = "test_partition.ptn", filename_partition = "Ni67_gs8_n.ptn", ): try: os.remove(filename_partition_edited) except FileNotFoundError: pass vum: VumDummy2 = VumDummy2() ans = _partition_editor( filename_interaction = "gs8.snt", filename_partition = filename_partition, filename_partition_edited = filename_partition_edited, vum_wrapper = vum, ) try: os.remove(filename_partition_edited) except FileNotFoundError: pass print(ans) def _partition_editor( vum_wrapper: Vum, filename_interaction: str | None = None, filename_partition: str | None = None, filename_partition_edited: str | None = None, is_recursive = False, ) -> tuple[int, int] | None: """ Extract the model space orbitals from an interaction file. Extract proton and neutron partitions from an accompanying partition file. Prompt the user for new proton and neutron configurations and regenerate the proton-neutron partition based on the existing and new proton and neutron configurations. Here, 'configuration' refers to a specific occupation of protons or neutrons in the model space orbitals while 'partition' refers to the set of all the configurations. Hence, a 'proton configuration' is one specific configuration, like ``` 1 6 4 2 0 2 4 2 0 0 0 0 0 ``` while the 'proton partition' is the set of all the proton configurations, like ``` 1 6 4 2 0 2 4 2 0 0 0 0 0 2 6 4 2 0 3 3 2 0 0 0 0 0 3 6 4 2 0 3 4 1 0 0 0 0 0 ... ``` Parameters ---------- filename_partition_edited : str | None The name of the edited partition file. If None, a name will be generated automatically. """ global return_string return_string = "" # For returning a message to be printed after the screen closes. vum: Vum = vum_wrapper screen = vum.screen input_wrapper = vum.input # screen.clear() # Clear the screen between interactive sessions. if (filename_interaction is None) or (filename_partition is None): tmp = _prompt_user_for_interaction_and_partition(vum=vum, is_compare_mode=False) if not tmp: return "Exiting without saving changes..." filename_interaction, filename_partition = tmp filename_partition_opposite_parity: str = \ filename_partition[0:-5] + ("n" if (filename_partition[-5] == "p") else "p") + filename_partition[-4:] partition_proton: Partition = Partition() partition_neutron: Partition = Partition() partition_combined: Partition = Partition() interaction: Interaction = Interaction() skips: Skips = Skips() threshold_energy: float = inf # Threshold energy for monopole truncation. inf means no truncation. if os.path.isfile(filename_partition_opposite_parity) and not is_recursive: """ Perform a recursive call to this function to determine the min and max ho quanta of the opposite parity partition. """ partition_combined.ho_quanta_min_opposite_parity, partition_combined.ho_quanta_max_opposite_parity = _partition_editor( filename_interaction = filename_interaction, filename_partition = filename_partition_opposite_parity, vum_wrapper = VumDummy(), is_recursive = True, ) elif not os.path.isfile(filename_partition_opposite_parity): """ This is not a problem if the calculations only have a single parity or if there is no hw truncation. """ vum.addstr(vum.n_rows - 2 - vum.command_log_length, 0, ( f"WARNING! Could not find opposite parity partition file," " thus cannot properly calculate min and max H.O. quanta " " for proper treatment of hw truncation." )) time.sleep(DELAY) if filename_partition_edited is None: filename_partition_edited = f"{filename_partition.split('.')[0]}_edited.ptn" load_interaction(filename_interaction=filename_interaction, interaction=interaction) draw_shell_map(vum=vum, model_space=interaction.model_space.orbitals, is_proton=True, is_neutron=True) header = load_partition( filename_partition = filename_partition, interaction = interaction, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, ) if is_recursive: """ This happens only inside the recursive function call. """ return partition_combined.ho_quanta_min_this_parity, partition_combined.ho_quanta_max_this_parity combined_existing_configurations_expected: list[Configuration] = partition_combined.configurations.copy() # For sanity check. while True: _generate_total_configurations( interaction = interaction, threshold_energy = threshold_energy, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, partition_file_parity = partition_combined.parity, skips = skips, ) if len(combined_existing_configurations_expected) != partition_combined.n_configurations: msg = ( "The number of combined configurations is not correct!" f" Expected: {len(combined_existing_configurations_expected)}, calculated: {partition_combined.n_configurations}" ) vum.addstr(vum.n_rows - 1 - vum.command_log_length - 2, 0, msg) msg = ( "This can happen if the .ptn file was generated with monopole" " truncation." ) vum.addstr(vum.n_rows - 1 - vum.command_log_length - 1, 0, msg) while True: check_choice = input_wrapper(".ptn monopole threshold energy or skip the check? (energy/s)") if check_choice == "s": break try: threshold_energy = float(check_choice) except ValueError: continue else: threshold_energy = partition_combined.min_configuration_energy + threshold_energy break if check_choice == "s": break else: break vum.addstr(vum.n_rows - 1 - vum.command_log_length - 2, 0, vum.blank_line) vum.addstr(vum.n_rows - 1 - vum.command_log_length - 1, 0, vum.blank_line) # assert len(combined_existing_configurations_expected) == partition_combined.n_configurations, msg for i in range(partition_combined.n_configurations): if partition_combined.configurations[i].configuration != combined_existing_configurations_expected[i].configuration: p_idx_expected = combined_existing_configurations_expected[i].configuration[0] n_idx_expected = combined_existing_configurations_expected[i].configuration[1] p_idx_calculated = partition_combined.configurations[i].configuration[0] n_idx_calculated = partition_combined.configurations[i].configuration[1] msg = ( f"Combined config with index {i} is incorrectly calculated!" f" Expected: {p_idx_expected, n_idx_expected}, calculated: {p_idx_calculated, n_idx_calculated}" f"\nproton_configurations_formatted [{p_idx_expected:5d}] = {partition_proton.configurations[p_idx_expected].configuration}, ho = {partition_proton.configurations[p_idx_expected].ho_quanta}, parity = {partition_proton.configurations[p_idx_expected].parity}" f"\nneutron_configurations_formatted[{n_idx_expected:5d}] = {partition_neutron.configurations[n_idx_expected].configuration}, ho = {partition_neutron.configurations[n_idx_expected].ho_quanta}, parity = {partition_neutron.configurations[n_idx_expected].parity}" f"\nproton_configurations_formatted [{p_idx_calculated:5d}] = {partition_proton.configurations[p_idx_calculated].configuration}, ho = {partition_proton.configurations[p_idx_calculated].ho_quanta}, parity = {partition_proton.configurations[p_idx_calculated].parity}" f"\nneutron_configurations_formatted[{n_idx_calculated:5d}] = {partition_neutron.configurations[n_idx_calculated].configuration}, ho = {partition_neutron.configurations[n_idx_calculated].ho_quanta}, parity = {partition_neutron.configurations[n_idx_calculated].parity}" f"\nho expected = {partition_proton.configurations[p_idx_expected].ho_quanta + partition_neutron.configurations[n_idx_expected].ho_quanta}" f"\nho calculated = {partition_proton.configurations[p_idx_calculated].ho_quanta + partition_neutron.configurations[n_idx_calculated].ho_quanta}" f"\nho min: {partition_combined.ho_quanta_min_this_parity}" f"\nho max: {partition_combined.ho_quanta_max_this_parity}" ) if partition_combined.configurations[i].configuration not in [c.configuration for c in combined_existing_configurations_expected]: msg += f"\n{partition_combined.configurations[i].configuration} should never appear!" raise KshellDataStructureError(msg) if isinstance(vum, VumDummy): """ Skip dim calculation for testing. """ M = [0] mdim = [0] else: M, mdim, jdim = count_dim( model_space_filename = filename_interaction, partition_filename = None, print_dimensions = False, debug = False, parity = partition_combined.parity, proton_partition = [configuration.configuration for configuration in partition_proton.configurations], neutron_partition = [configuration.configuration for configuration in partition_neutron.configurations], total_partition = [configuration.configuration for configuration in partition_combined.configurations], ) mdim_original: int = mdim[-1] _summary_information( vum = vum, skips = skips, filename_interaction = filename_interaction, filename_partition = filename_partition, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, interaction = interaction, M = M, mdim = mdim, y_offset = y_offset, mdim_original = None, # n_proton_skips = 0, # n_neutron_skips = 0, # n_parity_skips = 0, # n_ho_skips = 0, ) _analyse_existing_configuration( vum = vum, proton_configurations = partition_proton.configurations, neutron_configurations = partition_neutron.configurations, input_wrapper = input_wrapper, model_space = interaction.model_space.orbitals, y_offset = y_offset, n_proton_orbitals = interaction.model_space_proton.n_orbitals, ) while True: configuration_choice = input_wrapper("Add configuration? (y/n)") if configuration_choice == "y": pass elif configuration_choice in ["n", "q"]: break else: continue while True: nucleon_choice = input_wrapper("Proton or neutron? (p/n)") if nucleon_choice == "p": is_proton = True is_neutron = False nucleon = "proton" model_space_slice = interaction.model_space_proton partition = partition_proton n_valence_nucleons = interaction.model_space_proton.n_valence_nucleons break elif nucleon_choice == "n": is_proton = False is_neutron = True nucleon = "neutron" model_space_slice = interaction.model_space_neutron partition = partition_neutron n_valence_nucleons = interaction.model_space_neutron.n_valence_nucleons break elif nucleon_choice == "q": break else: continue while True: draw_shell_map(vum=vum, model_space=interaction.model_space.orbitals, is_proton=is_proton, is_neutron=is_neutron) configuration_type_choice = input_wrapper("Single or range of configurations? (s/r)") if configuration_type_choice == "s": """ Prompt the user for single specific configurations. """ while True: new_configuration = _prompt_user_for_configuration( vum = vum, nucleon = nucleon, model_space = model_space_slice.orbitals, n_valence_nucleons = n_valence_nucleons, input_wrapper = input_wrapper, y_offset = y_offset, ) if new_configuration: is_duplicate_configuration = _check_configuration_duplicate( new_configuration = new_configuration, existing_configurations = partition.configurations, vum = vum, interaction = interaction, is_proton = is_proton, is_neutron = is_neutron, init_orb_idx = 0, n_particles_choice = 0, is_duplicate_warning = False, ) if is_duplicate_configuration: msg = ( "This configuration already exists! Skipping..." ) vum.addstr(vum.n_rows - 1 - vum.command_log_length - 2, 0, "DUPLICATE") vum.addstr(vum.n_rows - 1 - vum.command_log_length - 1, 0, msg) time.sleep(DELAY) draw_shell_map(vum=vum, model_space=interaction.model_space.orbitals, is_proton=is_proton, is_neutron=is_neutron) continue parity_tmp = _calculate_configuration_parity( configuration = new_configuration, model_space = model_space_slice.orbitals ) if parity_tmp == -1: partition.n_new_negative_configurations += 1 elif parity_tmp == +1: partition.n_new_positive_configurations += 1 ho_quanta_tmp = sum([ # The number of harmonic oscillator quanta for each configuration. n*orb.ho_quanta for n, orb in zip(new_configuration, interaction.model_space_proton.orbitals) ]) return_string += f"\n{len(partition_proton.configurations) = }, {len(partition_neutron.configurations) = }, {len(partition_combined.configurations) = }" partition.configurations.append( Configuration( configuration = new_configuration, parity = parity_tmp, ho_quanta = ho_quanta_tmp, energy = None, is_original = False, ) ) return_string += f"\n{len(partition_proton.configurations) = }, {len(partition_neutron.configurations) = }, {len(partition_combined.configurations) = }" _generate_total_configurations( interaction = interaction, threshold_energy = threshold_energy, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, partition_file_parity = partition_combined.parity, allow_invalid = True, skips = skips, ) # try: # n_proton_skips, n_neutron_skips = _generate_total_configurations( # partition_proton = partition_proton, # partition_neutron = partition_neutron, # partition_combined = partition_combined, # partition_file_parity = partition_combined.parity, # allow_invalid = True, # ) # except KshellDataStructureError: # """ # Accept invalid configuration parity for now # since the user might specify more # configurations which may multiplicatively # combine parities to match the .ptn parity. # """ # pass # print(f"n proton, neutron configurations will be skipped because of parity or H.O. mismatch: {n_proton_skips, n_neutron_skips}") return_string += f"\n{len(partition_proton.configurations) = }, {len(partition_neutron.configurations) = }, {len(partition_combined.configurations) = }" # return return_string M, mdim, jdim = count_dim( model_space_filename = filename_interaction, partition_filename = None, print_dimensions = False, debug = False, parity = partition_combined.parity, proton_partition = [configuration.configuration for configuration in partition_proton.configurations], neutron_partition = [configuration.configuration for configuration in partition_neutron.configurations], total_partition = [configuration.configuration for configuration in partition_combined.configurations], ) # vum.addstr(y_offset + 1, 0, f"M-scheme dim (M={M[-1]}): {mdim[-1]:d} ({mdim[-1]:.2e}) (original {mdim_original:d} ({mdim_original:.2e}))") # vum.addstr(y_offset + 2, 0, f"n proton, neutron configurations: {partition_proton.n_existing_configurations} + {partition_proton.n_new_configurations}, {partition_neutron.n_existing_configurations} + {partition_neutron.n_new_configurations}") # vum.addstr(y_offset + 6, 0, f"n proton +, - : {partition_proton.n_existing_positive_configurations} + {partition_proton.n_new_positive_configurations}, {partition_proton.n_existing_negative_configurations} + {partition_proton.n_new_negative_configurations}") # vum.addstr(y_offset + 7, 0, f"n neutron +, - : {partition_neutron.n_existing_positive_configurations} + {partition_neutron.n_new_positive_configurations}, {partition_neutron.n_existing_negative_configurations} + {partition_neutron.n_new_negative_configurations}") # vum.addstr(y_offset + 9, 0, f"n pn configuration combinations: {partition_combined.n_configurations}") _summary_information( vum = vum, filename_interaction = filename_interaction, filename_partition = filename_partition, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, interaction = interaction, M = M, mdim = mdim, y_offset = y_offset, mdim_original = mdim_original, skips = skips, # n_proton_skips = n_proton_skips, # n_neutron_skips = n_neutron_skips, # n_parity_skips = n_parity_skips, # n_ho_skips = n_ho_skips, ) vum.addstr(vum.n_rows - 1 - vum.command_log_length - 2, 0, "Configuration added!") time.sleep(DELAY) elif new_configuration is None: """ Quit signal. Do not keep the current configuration, but keep earlier defined new configurations and quit the prompt. """ draw_shell_map(vum=vum, model_space=interaction.model_space.orbitals, is_proton=is_proton, is_neutron=is_neutron) vum.addstr(vum.n_rows - 3 - vum.command_log_length, 0, " ") # vum.addstr(vum.n_rows - 2 - vum.command_log_length, 0, "Current configuration discarded") vum.addstr(vum.n_rows - 2 - vum.command_log_length, 0, " ") break break elif configuration_type_choice == "r": """ Prompt the user for a range of configurations. Currently only supports 2p2h excitations. """ if input_wrapper("Monopole truncation? (y/n)") == "y": while True: try: threshold_energy = input_wrapper("Monopole trunc threshold energy (relative to min)") threshold_energy = float(threshold_energy) except ValueError: continue if threshold_energy > 0: threshold_energy = partition_combined.min_configuration_energy + threshold_energy break if not _add_npnh_excitations( vum = vum, input_wrapper = input_wrapper, model_space_slice = model_space_slice, interaction = interaction, partition = partition, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, nucleon_choice = nucleon_choice, is_proton = is_proton, is_neutron = is_neutron, ): continue try: _generate_total_configurations( interaction = interaction, threshold_energy = threshold_energy, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, partition_file_parity = partition_combined.parity, skips = skips, ) except KshellDataStructureError: """ Allow parity mismatch for now. """ pass M, mdim, jdim = count_dim( model_space_filename = filename_interaction, partition_filename = None, print_dimensions = False, debug = False, parity = partition_combined.parity, proton_partition = [configuration.configuration for configuration in partition_proton.configurations], neutron_partition = [configuration.configuration for configuration in partition_neutron.configurations], total_partition = [configuration.configuration for configuration in partition_combined.configurations], ) # vum.addstr(y_offset + 1, 0, f"M-schemelol dim (M={M[-1]}): {mdim[-1]:d} ({mdim[-1]:.2e}) (original {mdim_original:d} ({mdim_original:.2e}))") # vum.addstr(y_offset + 2, 0, f"n proton, neutron configurations: {partition_proton.n_existing_configurations} + {partition_proton.n_new_configurations}, {partition_neutron.n_existing_configurations} + {partition_neutron.n_new_configurations}") # vum.addstr(y_offset + 6, 0, f"n proton +, - : {partition_proton.n_existing_positive_configurations} + {partition_proton.n_new_positive_configurations}, {partition_proton.n_existing_negative_configurations} + {partition_proton.n_new_negative_configurations}") # vum.addstr(y_offset + 7, 0, f"n neutron +, - : {partition_neutron.n_existing_positive_configurations} + {partition_neutron.n_new_positive_configurations}, {partition_neutron.n_existing_negative_configurations} + {partition_neutron.n_new_negative_configurations}") # vum.addstr(y_offset + 9, 0, f"n pn configuration combinations: {partition_combined.n_configurations}") _summary_information( vum = vum, filename_interaction = filename_interaction, filename_partition = filename_partition, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, interaction = interaction, M = M, mdim = mdim, y_offset = y_offset, mdim_original = mdim_original, skips = skips, # n_proton_skips = n_proton_skips, # n_neutron_skips = n_neutron_skips, # n_parity_skips = n_parity_skips, # n_ho_skips = n_ho_skips, ) # vum.addstr(vum.n_rows - 1 - vum.command_log_length - 2, 0, "Configurations added!") break elif configuration_type_choice == "q": break else: continue _generate_total_configurations( interaction = interaction, partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, partition_file_parity = partition_combined.parity, threshold_energy = threshold_energy, # NOTE: Maybe this should be inf to avoid removing existing configurations? allow_invalid = False, skips = skips, ) n_new_proton_configurations = partition_proton.n_new_negative_configurations + partition_proton.n_new_positive_configurations n_new_neutron_configurations = partition_neutron.n_new_negative_configurations + partition_neutron.n_new_positive_configurations if not isinstance(vum, VumDummy): """ Dont create a .ptn file if no changes are made, but allow it for unit tests using VumDummy. """ if (not n_new_neutron_configurations) and (not n_new_proton_configurations): return_string += "No new configurations. Skipping creation of new .ptn file." return return_string _sanity_checks( partition_proton = partition_proton, partition_neutron = partition_neutron, partition_combined = partition_combined, interaction = interaction, ) while True: save_changes_choice = input_wrapper("Save changes to new partition file? (y/n)") if save_changes_choice == "n": return_string += "Exiting without saving changes..." return return_string elif save_changes_choice == "y": break with open(filename_partition_edited, "w") as outfile: """ Write edited data to new partition file. """ outfile.write(header) outfile.write(f" {partition_proton.n_configurations} {partition_neutron.n_configurations}\n") outfile.write("# proton partition\n") for i in range(partition_proton.n_configurations): outfile.write( f"{i + 1:6d} " # +1 because .ptn indices start at 1. f"{str(partition_proton.configurations[i].configuration).strip('[]').replace(',', ' ')}" "\n" ) outfile.write("# neutron partition\n") for i in range(partition_neutron.n_configurations): outfile.write( f"{i + 1:6d} " # +1 because .ptn indices start at 1. f"{str(partition_neutron.configurations[i].configuration).strip('[]').replace(',', ' ')}" "\n" ) outfile.write("# partition of proton and neutron\n") outfile.write(f"{partition_combined.n_configurations}\n") for configuration in partition_combined.configurations: outfile.write(f"{configuration.configuration[0] + 1:5d} {configuration.configuration[1] + 1:5d}\n") # +1 because .ptn indices start at 1. return_string += ( f"New configuration saved to {filename_partition_edited}" f" with {n_new_proton_configurations} new proton configurations" f" and {n_new_neutron_configurations} new neutron configurations" ) return return_string def _prompt_user_for_configuration( vum: Vum, nucleon: str, model_space: list[OrbitalParameters], n_valence_nucleons: int, input_wrapper: Callable, y_offset: int, ) -> list | None: """ Prompt the user for a new proton or neutron configuration, meaning that this function prompts the user for the occupation of all the orbitals in the model space and returns the configuration as a list of occupation numbers. Note that the order of the orbitals that the user is prompted for is sorted by the `shell_model_order` dictionary but the occupation number list returned by this function is sorted by the order of the orbitals as defined in the interaction file. Parameters ---------- vum : Vum The Vum object to use for displaying information. nucleon : str The nucleon type to prompt the user for. Must be either "proton" or "neutron". model_space : list[OrbitalParameters] The model space to use for the prompt. n_valence_nucleons : int The number of valence protons or neutrons. Used for making sure that the user does not enter more than this number of nucleons in the configuration. input_wrapper : Callable The input wrapper to use for getting user input. y_offset : int The y-offset to use for displaying information. Returns ------- list | None The occupation of each model space orbitals as a list of occupation numbers. If the user enters "q" to quit, None is returned. """ is_blank_map: bool = True if nucleon == "proton": is_proton = True is_neutron = False elif nucleon == "neutron": is_proton = False is_neutron = True else: msg = f"Invalid nucleon parameter '{nucleon}'!" raise ValueError(msg) model_space_copy = sorted( # Sort the orbitals based on the shell_model_order dict. model_space, key = lambda orbital: shell_model_order[f"{orbital.n}{spectroscopic_conversion[orbital.l]}{orbital.j}"].idx, ) n_remaining_nucleons: int = n_valence_nucleons vum.addstr(vum.n_rows - 3 - vum.command_log_length, 0, " ") vum.addstr(vum.n_rows - 2 - vum.command_log_length, 0, f"Please enter {nucleon} orbital occupation (f to fill, q to quit):") occupation: list[tuple[int, int]] = [] occupation_parity: int = 1 for orbital in model_space_copy: if n_remaining_nucleons == 0: """ If there are no more valence nucleons to use, set the remaining occupations to 0. """ occupation.append((orbital.idx, 0)) vum.addstr(vum.n_rows - 3 - vum.command_log_length, 0, "Occupation of remaining orbitals set to 0.") continue while True: ans = input_wrapper(f"{orbital.idx + 1:2d} {orbital} (remaining: {n_remaining_nucleons})") if is_blank_map: is_blank_map = False draw_shell_map( vum = vum, model_space = model_space, is_proton = is_proton, is_neutron = is_neutron, ) if (ans == "q") or (ans == "quit") or (ans == "exit"): return None if ans == "f": """ Fill the orbital completely or with as many remaining nucleons as possible. """ ans = min(orbital.j + 1, n_remaining_nucleons) try: ans = int(ans) except ValueError: continue if (ans > (orbital.j + 1)) or (ans < 0): vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, f"Allowed occupation for this orbital is [0, 1, ..., {orbital.j + 1}]" ) continue occupation_parity *= orbital.parity**ans vum.addstr(y_offset + PARITY_CURRENT_Y_COORD, 0, f"parity current configuration = {occupation_parity}") n_remaining_nucleons -= ans if ans > 0: """ No point in re-drawing the line if the occupation is unchanged. """ draw_shell_map( vum = vum, model_space = model_space, is_proton = is_proton, is_neutron = is_neutron, occupation = (orbital.idx, ans) ) break occupation.append((orbital.idx, ans)) cum_occupation = sum(tup[1] for tup in occupation) if cum_occupation > n_valence_nucleons: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, f"INVALID: Total occupation ({cum_occupation}) exceeds the number of valence {nucleon}s ({n_valence_nucleons})" ) draw_shell_map( vum = vum, model_space = model_space, is_proton = is_proton, is_neutron = is_neutron, ) return [] cum_occupation = sum(tup[1] for tup in occupation) if cum_occupation < n_valence_nucleons: vum.addstr( vum.n_rows - 3 - vum.command_log_length, 0, f"INVALID: Total occupation ({cum_occupation}) does not use the total number of valence {nucleon}s ({n_valence_nucleons})" ) draw_shell_map( vum = vum, model_space = model_space, is_proton = is_proton, is_neutron = is_neutron, ) return [] vum.addstr(vum.n_rows - 2 - vum.command_log_length, 0, vum.blank_line) occupation.sort(key=lambda tup: tup[0]) # Sort list of tuples based on the orbital.idx. return [tup[1] for tup in occupation] # Return only the occupation numbers now sorted based on the orbital order of the .snt file. <file_sep>from __future__ import annotations import multiprocessing, curses import kshell_utilities as ksutil from vum import Vum import numpy as np from kshell_utilities.data_structures import ( Partition, Interaction ) from .partition_tools import _prompt_user_for_interaction_and_partition def _duplicate_checker( partition_a: Partition, partition_b: Partition, ) -> np.ndarray[bool]: """ Check if the conffigurations in `partition_a` also occur in `partition_b`. """ is_in_both_partitions: np.ndarray[bool] = np.zeros(partition_a.n_configurations, dtype=bool) for idx_a in range(partition_a.n_configurations): config_a = partition_a.configurations[idx_a].configuration for idx_b in range(partition_b.n_configurations): config_b = partition_b.configurations[idx_b].configuration if config_a == config_b: is_in_both_partitions[idx_a] = True break else: is_in_both_partitions[idx_a] = False return is_in_both_partitions def _sanity_checks( filename_partition_a: str, filename_partition_b: str, filename_interaction: str, ): ksutil.test_partition_editor( # Proof that partition_editor perfectly replicates the combined configs. filename_partition = filename_partition_a, filename_partition_edited = filename_partition_a + "testfile.ptn", filename_interaction = filename_interaction, ) ksutil.test_partition_editor( # Proof that partition_editor perfectly replicates the combined configs. filename_partition = filename_partition_b, filename_partition_edited = filename_partition_b + "testfile.ptn", filename_interaction = filename_interaction, ) def partition_compare(): """ Wrapper function for error handling. """ try: vum: Vum = Vum() msg = _partition_compare(vum) except KeyboardInterrupt: print("Exiting without saving changes...") except curses.error as e: raise(e) except Exception as e: raise(e) else: print(msg) def _partition_compare(vum: Vum): tmp = _prompt_user_for_interaction_and_partition( vum = vum, is_compare_mode = True, ) filename_interaction, (filename_partition_a, filename_partition_b) = tmp # filename_interaction = "gs8.snt" interaction: Interaction = Interaction() ksutil.load_interaction( filename_interaction = filename_interaction, interaction = interaction ) # filename_partition_a = "Ni67_gs8_n_edited_2.ptn" partition_proton_a: Partition = Partition() partition_neutron_a: Partition = Partition() partition_combined_a: Partition = Partition() ksutil.load_partition( filename_partition = filename_partition_a, interaction = interaction, partition_proton = partition_proton_a, partition_neutron = partition_neutron_a, partition_combined = partition_combined_a, ) # filename_partition_b = "Ni67_gs8_n.ptn" partition_proton_b: Partition = Partition() partition_neutron_b: Partition = Partition() partition_combined_b: Partition = Partition() ksutil.load_partition( filename_partition = filename_partition_b, interaction = interaction, partition_proton = partition_proton_b, partition_neutron = partition_neutron_b, partition_combined = partition_combined_b, ) sanity_check_process = multiprocessing.Process( # Sanity checks in a separate process to make the program more snappy. target = _sanity_checks, args = (filename_partition_a, filename_partition_b, filename_interaction), ) sanity_check_process.start() _, mdim_a, _ = ksutil.count_dim( model_space_filename = filename_interaction, partition_filename = None, print_dimensions = False, debug = False, parity = partition_combined_a.parity, proton_partition = [configuration.configuration for configuration in partition_proton_a.configurations], neutron_partition = [configuration.configuration for configuration in partition_neutron_a.configurations], total_partition = [configuration.configuration for configuration in partition_combined_a.configurations], ) _, mdim_b, _ = ksutil.count_dim( model_space_filename = filename_interaction, partition_filename = None, print_dimensions = False, debug = False, parity = partition_combined_b.parity, proton_partition = [configuration.configuration for configuration in partition_proton_b.configurations], neutron_partition = [configuration.configuration for configuration in partition_neutron_b.configurations], total_partition = [configuration.configuration for configuration in partition_combined_b.configurations], ) vum.addstr(0, 0, string = f"Compare Partitions :: {filename_interaction} :: (A) {filename_partition_a} :: (B) {filename_partition_b}" ) vum.addstr(2, 33, f"A" ) vum.addstr(2, 40 + 6, f"B", is_blank_line = False, ) vum.addstr(3, 0, f"dim {mdim_a[-1]:14.2e} {mdim_b[-1]:14.2e}" ) vum.addstr(4, 0, f"n proton configs {partition_proton_a.n_configurations:14d} {partition_proton_b.n_configurations:14d}" ) vum.addstr(5, 0, f"n neutron configs {partition_neutron_a.n_configurations:14d} {partition_neutron_b.n_configurations:14d}" ) vum.addstr(6, 0, f"n combined configs {partition_combined_a.n_configurations:14d} {partition_combined_b.n_configurations:14d}" ) min_max_a = str((partition_proton_a.ho_quanta_min_this_parity, partition_proton_a.ho_quanta_max_this_parity))[1:-1]#.replace(" ", "") min_max_b = str((partition_proton_b.ho_quanta_min_this_parity, partition_proton_b.ho_quanta_max_this_parity))[1:-1]#.replace(" ", "") vum.addstr(7, 0, f"H.O. min,max proton {min_max_a:>14s} {min_max_b:>14s}" ) min_max_a = str((partition_neutron_a.ho_quanta_min_this_parity, partition_neutron_a.ho_quanta_max_this_parity))[1:-1]#.replace(" ", "") min_max_b = str((partition_neutron_b.ho_quanta_min_this_parity, partition_neutron_b.ho_quanta_max_this_parity))[1:-1]#.replace(" ", "") vum.addstr(8, 0, f"H.O. min,max neutron {min_max_a:>14s} {min_max_b:>14s}" ) min_max_a = str((partition_combined_a.ho_quanta_min_this_parity, partition_combined_a.ho_quanta_max_this_parity))[1:-1]#.replace(" ", "") min_max_b = str((partition_combined_b.ho_quanta_min_this_parity, partition_combined_b.ho_quanta_max_this_parity))[1:-1]#.replace(" ", "") vum.addstr(9, 0, f"H.O. min,max combined {min_max_a:>14s} {min_max_b:>14s}" ) vum.addstr(11, 29, f"A in B" ) vum.addstr(11, 36 + 6, f"B in A", is_blank_line = False, ) a_in_b = _duplicate_checker( partition_a = partition_proton_a, partition_b = partition_proton_b, ) a_in_b = str(f"{a_in_b.sum()}/{partition_proton_a.n_configurations}") b_in_a = _duplicate_checker( partition_a = partition_proton_b, partition_b = partition_proton_a, ) b_in_a = str(f"{b_in_a.sum()}/{partition_proton_b.n_configurations}") vum.addstr(12, 0, f"n proton configs {a_in_b:>14s} {b_in_a:>14s}" ) a_in_b = _duplicate_checker( partition_a = partition_neutron_a, partition_b = partition_neutron_b, ) a_in_b = str(f"{a_in_b.sum()}/{partition_neutron_a.n_configurations}") b_in_a = _duplicate_checker( partition_a = partition_neutron_b, partition_b = partition_neutron_a, ) b_in_a = str(f"{b_in_a.sum()}/{partition_neutron_b.n_configurations}") vum.addstr(13, 0, f"n neutron configs {a_in_b:>14s} {b_in_a:>14s}" ) vum.input("Enter any char to exit") if __name__ == "__main__": # main() partition_compare() <file_sep>from setuptools import setup # try: # import pypandoc # long_description = pypandoc.convert('README.md', 'rst') # except (IOError, ImportError, OSError): # long_description = "" setup( name = 'kshell-utilities', version = '1.5.1.0', description = 'Handy utilities for handling nuclear shell model calculations from KSHELL', # long_description = long_description, url = 'https://github.com/GaffaSnobb/kshell-utilities', author = ['<NAME>', '<NAME>'], author_email = '<EMAIL>', packages = ['kshell_utilities', 'tests'], install_requires = ['numpy', 'matplotlib', 'seaborn', 'scipy', 'numba', 'vum'], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'Operating System :: MacOS', 'Operating System :: Unix', 'Programming Language :: Python :: 3.11', 'Topic :: Scientific/Engineering :: Physics', ], ) <file_sep>from __future__ import annotations import os from vum import Vum from .data_structures import ( OrbitalParameters, Partition, Interaction, Configuration ) def _sanity_checks( partition_proton: Partition, partition_neutron: Partition, partition_combined: Partition, interaction: Interaction, ): """ A few different sanity checks to make sure that the new configurations are physical. """ for i, configuration in enumerate(partition_proton.configurations): assert len(configuration.configuration) == interaction.model_space_proton.n_orbitals assert sum(configuration.configuration) == interaction.model_space_proton.n_valence_nucleons assert sum([n*orb.ho_quanta for n, orb in zip(configuration.configuration, interaction.model_space_proton.orbitals)]) == configuration.ho_quanta for j in range(i+1, partition_proton.n_configurations): assert partition_proton.configurations[i].configuration != partition_proton.configurations[j].configuration, f"Duplicate proton configs {i} and {j}!" for orbital, occupation in zip(interaction.model_space_proton.orbitals, configuration.configuration): """ Check that max degeneracy is respected. """ assert occupation <= (orbital.j + 1), "Occupation should never be lager than the max degeneracy!" assert (i + 1) == partition_proton.n_configurations for i, configuration in enumerate(partition_neutron.configurations): assert len(configuration.configuration) == interaction.model_space_neutron.n_orbitals assert sum(configuration.configuration) == interaction.model_space_neutron.n_valence_nucleons assert sum([n*orb.ho_quanta for n, orb in zip(configuration.configuration, interaction.model_space_neutron.orbitals)]) == configuration.ho_quanta for j in range(i+1, partition_neutron.n_configurations): assert partition_neutron.configurations[i].configuration != partition_neutron.configurations[j].configuration, f"Duplicate neutron configs {i} and {j}!" for orbital, occupation in zip(interaction.model_space_neutron.orbitals, configuration.configuration): """ Check that max degeneracy is respected. """ assert occupation <= (orbital.j + 1), "Occupation should never be lager than the max degeneracy!" assert (i + 1) == partition_neutron.n_configurations for configuration in partition_combined.configurations: p_idx, n_idx = configuration.configuration assert partition_combined.parity == partition_proton.configurations[p_idx].parity*partition_neutron.configurations[n_idx].parity assert configuration.ho_quanta == partition_proton.configurations[p_idx].ho_quanta + partition_neutron.configurations[n_idx].ho_quanta def _calculate_configuration_parity( configuration: list[int], model_space: list[OrbitalParameters] ) -> int: """ Calculate the parity of a configuration. Parameters ---------- configuration : list[int] The configuration to calculate the parity of. model_space : list[OrbitalParameters] The model space orbitals to use for the calculation. """ if not configuration: msg = "Configuration is empty! Undefined behaviour." raise ValueError(msg) parity: int = 1 for i in range(len(configuration)): if not configuration[i]: continue # Empty orbitals do not count towards the total parity. parity *= model_space[i].parity**configuration[i] return parity def _prompt_user_for_interaction_and_partition( vum: Vum, is_compare_mode: bool, ): """ Parameterss ----------- is_compare_mode : bool User will be prompted for two partition files and they will be returned as a list of the two names. """ filenames_interaction = sorted([i for i in os.listdir() if i.endswith(".snt")]) filenames_partition = sorted([i for i in os.listdir() if i.endswith(".ptn")]) if not filenames_interaction: return f"No interaction file present in {os.getcwd()}. Exiting..." if not filenames_partition: return f"No partition file present in {os.getcwd()}. Exiting..." if len(filenames_interaction) == 1: filename_interaction = filenames_interaction[0] vum.screen.addstr(0, 0, f"{filename_interaction} chosen") vum.screen.refresh() elif len(filenames_interaction) > 1: interaction_choices: str = "" for i in range(len(filenames_interaction)): interaction_choices += f"{filenames_interaction[i]} ({i}), " vum.screen.addstr(vum.n_rows - 1 - vum.command_log_length - 1, 0, "Several interaction files detected.") vum.screen.addstr(vum.n_rows - 1 - vum.command_log_length, 0, interaction_choices) vum.screen.refresh() while True: ans = vum.input("Several interaction files detected. Please make a choice") if ans == "q": return False try: ans = int(ans) except ValueError: continue try: filename_interaction = filenames_interaction[ans] except IndexError: continue break vum.screen.addstr(0, 0, vum.blank_line) vum.screen.addstr(1, 0, vum.blank_line) vum.screen.refresh() if len(filenames_partition) == 1: if is_compare_mode: return "Cannot compare, only one partition file found!" filename_partition = filenames_partition[0] vum.screen.addstr(0, 0, f"{filename_partition} chosen") vum.screen.refresh() elif len(filenames_partition) > 1: if is_compare_mode: filename_partition: list[str] = [] partition_choices: str = "" for i in range(len(filenames_partition)): partition_choices += f"{filenames_partition[i]} ({i}), " while True: vum.screen.addstr(vum.n_rows - 1 - vum.command_log_length - 1, 0, "Several partition files detected.") vum.screen.addstr(vum.n_rows - 1 - vum.command_log_length, 0, partition_choices) vum.screen.refresh() ans = vum.input("Several partition files detected. Please make a choice") if ans == "q": return False try: ans = int(ans) except ValueError: continue try: if is_compare_mode: filename_partition.append(filenames_partition[ans]) else: filename_partition = filenames_partition[ans] except IndexError: continue if is_compare_mode and (len(filename_partition) < 2): continue break vum.screen.addstr(vum.n_rows - 1 - vum.command_log_length - 1, 0, vum.blank_line) vum.screen.addstr(vum.n_rows - 1 - vum.command_log_length, 0, vum.blank_line) vum.screen.refresh() return filename_interaction, filename_partition # def is_configuration_below_energy_threshold( # interaction: Interaction, # threshold_energy: float, # proton_configuration: Configuration, # neutron_configuration: Configuration, # ) -> bool: # """ # Calculate the energy of a pn configuration. Return True if the # energy is lower than the threshold energy and False otherwise. Used # for monopole truncation. # """ # energy = configuration_energy( # interaction = interaction, # proton_configuration = proton_configuration, # neutron_configuration = neutron_configuration, # ) # return energy < threshold_energy def configuration_energy( interaction: Interaction, proton_configuration: Configuration, neutron_configuration: Configuration, ) -> float: """ Code from https://github.com/GaffaSnobb/kshell/blob/6e6edd6ac7ae70513b4bdaa94099cd3a3e32351d/bin/espe.py#L164 """ combined_configuration = proton_configuration.configuration + neutron_configuration.configuration if interaction.fmd_mass == 0: fmd = 1 else: mass = interaction.n_core_neutrons + interaction.n_core_protons mass += interaction.model_space.n_valence_nucleons fmd = (mass/interaction.fmd_mass)**interaction.fmd_power assert len(interaction.spe) == len(combined_configuration) energy: float = 0.0 for spe, occupation in zip(interaction.spe, combined_configuration, strict=True): energy += occupation*spe for i0 in range(len(combined_configuration)): for i1 in range(len(combined_configuration)): if i0 < i1: continue # Why? elif i0 == i1: energy += combined_configuration[i0]*(combined_configuration[i0] - 1)*0.5*interaction.vm[i0, i0]*fmd else: energy += combined_configuration[i0]*combined_configuration[i1]*interaction.vm[i0, i1]*fmd return energy <file_sep>from itertools import zip_longest import numpy as np import kshell_utilities.kshell_utilities def test_file_read_levels(): """ Test that kshell_utilities.loadtxt successfully reads excitation energy output from KSHELL. Note that -1 spin states are supposed to be skipped. Raises ------ AssertionError If the read values are not exactly equal to the expected values. """ res = kshell_utilities.loadtxt( path = "summary_test_text_file.txt", load_and_save_to_file = False, old_or_new = "old" ) E_expected = [ -114.552, -114.044, -113.972, -113.898, -113.762, -113.602, -41.394, -33.378, -9.896, -9.052 ] spin_expected = [ 2*2, 2*5, 2*4, 2*7, 2*2, 2*3, 2*0, 2*3, 2*3/2, 2*7/2 ] parity_expected = [ 1, 1, 1, 1, 1, 1, 1, 1, -1, -1 ] for calculated, expected in zip_longest(res.levels[:, 0], E_expected): msg = f"Error in Ex. Expected: {expected}, got: {calculated}." assert calculated == expected, msg for calculated, expected in zip_longest(res.levels[:, 1], spin_expected): msg = f"Error in spin. Expected: {expected}, got: {calculated}." assert calculated == expected, msg for calculated, expected in zip_longest(res.levels[:, 2], parity_expected): msg = f"Error in parity. Expected: {expected}, got: {calculated}." assert calculated == expected, msg def test_int_vs_floor(): """ Check that floor yields the same result as casting to int. This does not work for negative values. """ res = kshell_utilities.loadtxt( path = "summary_test_text_file.txt", load_and_save_to_file = False, old_or_new = "old" ) res_1 = np.floor(res.transitions_BM1[:, 5]) res_2 = res.transitions_BM1[:, 5].astype(int) for elem_1, elem_2 in zip(res_1, res_2): assert elem_1 == elem_2 def test_file_read_transitions(): """ Test that all values in res.transitions are as expected. """ res = kshell_utilities.loadtxt( path = "summary_test_text_file.txt", load_and_save_to_file = False, old_or_new = "old" ) # BE2 # --- spin_initial_expected = np.array([5, 4, 4, 3, 9/2, 9/2])*2 for i in range(len(res.transitions_BE2[:, 0])): msg = "BE2: Error in spin_initial." msg += f" Expected: {spin_initial_expected[i]}, got {res.transitions_BE2[i, 0]}." assert res.transitions_BE2[i, 0] == spin_initial_expected[i], msg parity_initial_expected = np.array([1, 1, 1, 1, -1, -1]) for i in range(len(res.transitions_BE2[:, 1])): msg = "BE2: Error in parity_initial." msg += f" Expected: {parity_initial_expected[i]}, got {res.transitions_BE2[i, 1]}." assert res.transitions_BE2[i, 1] == parity_initial_expected[i], msg Ex_initial_expected = np.array([0.176, 0.182, 0.182, 0.221, 27.281, 27.281]) for i in range(len(res.transitions_BE2[:, 3])): msg = "BE2: Error in Ex_initial." msg += f" Expected: {Ex_initial_expected[i]}, got {res.transitions_BE2[i, 3]}." assert res.transitions_BE2[i, 3] == Ex_initial_expected[i], msg spin_final_expected = np.array([6, 6, 5, 5, 13/2, 5/2])*2 for i in range(len(res.transitions_BE2[:, 4])): msg = "BE2: Error in spin_final." msg += f" Expected: {spin_final_expected[i]}, got {res.transitions_BE2[i, 4]}." assert res.transitions_BE2[i, 4] == spin_final_expected[i], msg parity_final_expected = np.array([1, 1, 1, 1, -1, -1]) for i in range(len(res.transitions_BE2[:, 5])): msg = "BE2: Error in parity_final." msg += f" Expected: {parity_final_expected[i]}, got {res.transitions_BE2[i, 5]}." assert res.transitions_BE2[i, 5] == parity_final_expected[i], msg Ex_final_expected = np.array([0, 0, 0.176, 0.176, 17.937, 18.349]) for i in range(len(res.transitions_BE2[:, 7])): msg = "BE2: Error in Ex_final." msg += f" Expected: {Ex_final_expected[i]}, got {res.transitions_BE2[i, 7]}." assert res.transitions_BE2[i, 7] == Ex_final_expected[i], msg E_gamma_expected = np.array([0.176, 0.182, 0.006, 0.045, 9.344, 8.932]) for i in range(len(res.transitions_BE2[:, 8])): msg = "BE2: Error in E_gamma." msg += f" Expected: {E_gamma_expected[i]}, got {res.transitions_BE2[i, 8]}." assert res.transitions_BE2[i, 8] == E_gamma_expected[i], msg B_decay_expected = np.array([157, 44.8, 3.1, 35, 0, 1.1]) for i in range(len(res.transitions_BE2[:, 9])): msg = "BE2: Error in B_decay." msg += f" Expected: {B_decay_expected[i]}, got {res.transitions_BE2[i, 9]}." assert res.transitions_BE2[i, 9] == B_decay_expected[i], msg B_excite_expected = np.array([132.9, 31, 2.5, 22.3, 0.0, 1.9]) for i in range(len(res.transitions_BE2[:, 10])): msg = "BE2: Error in B_excite." msg += f" Expected: {B_excite_expected[i]}, got {res.transitions_BE2[i, 10]}." assert res.transitions_BE2[i, 10] == B_excite_expected[i], msg # BM1 # --- spin_initial_expected = np.array([2, 2, 1, 2, 7/2, 7/2])*2 for i in range(len(res.transitions_BM1[:, 0])): msg = "BM1: Error in spin_initial." msg += f" Expected: {spin_initial_expected[i]}, got {res.transitions_BM1[i, 0]}." assert res.transitions_BM1[i, 0] == spin_initial_expected[i], msg parity_initial_expected = np.array([1, 1, 1, 1, -1, -1]) for i in range(len(res.transitions_BM1[:, 1])): msg = "BM1: Error in parity_initial." msg += f" Expected: {parity_initial_expected[i]}, got {res.transitions_BM1[i, 1]}." assert res.transitions_BM1[i, 1] == parity_initial_expected[i], msg Ex_initial_expected = np.array([5.172, 17.791, 19.408, 18.393, 24.787, 24.787]) for i in range(len(res.transitions_BM1[:, 3])): msg = "BM1: Error in Ex_initial." msg += f" Expected: {Ex_initial_expected[i]}, got {res.transitions_BM1[i, 3]}." assert res.transitions_BM1[i, 3] == Ex_initial_expected[i], msg spin_final_expected = np.array([0, 0, 2, 2, 5/2, 5/2])*2 for i in range(len(res.transitions_BM1[:, 4])): msg = "BM1: Error in spin_final." msg += f" Expected: {spin_final_expected[i]}, got {res.transitions_BM1[i, 4]}." assert res.transitions_BM1[i, 4] == spin_final_expected[i], msg parity_final_expected = np.array([1, 1, 1, 1, -1, -1]) for i in range(len(res.transitions_BM1[:, 5])): msg = "BM1: Error in parity_final." msg += f" Expected: {parity_final_expected[i]}, got {res.transitions_BM1[i, 5]}." assert res.transitions_BM1[i, 5] == parity_final_expected[i], msg Ex_final_expected = np.array([0, 0, 17.791, 17.791, 21.486, 21.564]) for i in range(len(res.transitions_BM1[:, 7])): msg = "BM1: Error in Ex_final." msg += f" Expected: {Ex_final_expected[i]}, got {res.transitions_BM1[i, 7]}." assert res.transitions_BM1[i, 7] == Ex_final_expected[i], msg E_gamma_expected = np.array([5.172, 17.791, 1.617, 0.602, 3.301, 3.222]) for i in range(len(res.transitions_BM1[:, 8])): msg = "BM1: Error in E_gamma." msg += f" Expected: {E_gamma_expected[i]}, got {res.transitions_BM1[i, 8]}." assert res.transitions_BM1[i, 8] == E_gamma_expected[i], msg B_decay_expected = np.array([20.5, 0.0, 5.7, 0.1, 0.069, 0.463]) for i in range(len(res.transitions_BM1[:, 9])): msg = "BM1: Error in B_decay." msg += f" Expected: {B_decay_expected[i]}, got {res.transitions_BM1[i, 9]}." assert res.transitions_BM1[i, 9] == B_decay_expected[i], msg B_excite_expected = np.array([102.3, 0.0, 3.4, 0.1, 0.092, 0.617]) for i in range(len(res.transitions_BM1[:, 10])): msg = "BM1: Error in B_excite." msg += f" Expected: {B_excite_expected[i]}, got {res.transitions_BM1[i, 10]}." assert res.transitions_BM1[i, 10] == B_excite_expected[i], msg def _test_file_read_levels_jem(): """ For JEM syntax. NOTE: Currently not working because of https://github.com/GaffaSnobb/kshell-utilities/blob/d0bc1eae743e353671c562040c544b7df4c28d05/kshell_utilities/kshell_utilities.py#L437 Raises ------ AssertionError If the read values are not exactly equal to the expected values. """ res = kshell_utilities.loadtxt( path = "summary_Zn60_jun45_jem_syntax.txt", load_and_save_to_file = False, old_or_new = "jem" )[0] E_expected = [ -50.42584, -49.42999, -47.78510, -46.30908, -46.24604, -45.97338, -45.85816, -45.69709, -45.25258, -45.22663 ] spin_expected = [ 0, 4, 8, 4, 0, 4, 12, 2, 8, 6 ] parity_expected = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] for calculated, expected in zip_longest(res.levels[:, 0], E_expected): msg = f"Error in Ex. Expected: {expected}, got: {calculated}." assert calculated == expected, msg for calculated, expected in zip_longest(res.levels[:, 1], spin_expected): msg = f"Error in spin. Expected: {expected}, got: {calculated}." assert calculated == expected, msg for calculated, expected in zip_longest(res.levels[:, 2], parity_expected): msg = f"Error in parity. Expected: {expected}, got: {calculated}." assert calculated == expected, msg def _test_file_read_transitions_jem(): """ Test that all values in res.transitions are as expected. NOTE: Currently not working because of https://github.com/GaffaSnobb/kshell-utilities/blob/d0bc1eae743e353671c562040c544b7df4c28d05/kshell_utilities/kshell_utilities.py#L437 """ res = kshell_utilities.loadtxt( path = "summary_Zn60_jun45_jem_syntax.txt", load_and_save_to_file = False, old_or_new = "jem" )[0] E_gs = 50.42584 # BE2 # --- spin_initial_expected = np.array([ 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10 ]) for i in range(len(res.transitions_BE2[:, 0])): msg = "BE2: Error in spin_initial." msg += f" Expected: {spin_initial_expected[i]}, got {res.transitions_BE2[i, 0]}." assert res.transitions_BE2[i, 0] == spin_initial_expected[i], msg parity_initial_expected = np.array([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]) for i in range(len(res.transitions_BE2[:, 1])): msg = "BE2: Error in parity_initial." msg += f" Expected: {parity_initial_expected[i]}, got {res.transitions_BE2[i, 1]}." assert res.transitions_BE2[i, 1] == parity_initial_expected[i], msg Ex_initial_expected = E_gs - np.abs(np.array([ -42.834, -42.061, -41.992, -41.210, -41.117, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -50.426, -50.426, -50.426, -50.426, -50.426, -50.426, -50.426, -50.426, -43.879, -43.879, -43.879, -43.879, -43.879 ])) for i in range(len(res.transitions_BE2[:, 3])): msg = "BE2: Error in Ex_initial." msg += f" Expected: {Ex_initial_expected[i]}, got {res.transitions_BE2[i, 3]}." assert res.transitions_BE2[i, 3] == Ex_initial_expected[i], msg spin_final_expected = np.array([ 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 10, 10, 10, 10, 10 ]) for i in range(len(res.transitions_BE2[:, 4])): msg = "BE2: Error in spin_final." msg += f" Expected: {spin_final_expected[i]}, got {res.transitions_BE2[i, 4]}." assert res.transitions_BE2[i, 4] == spin_final_expected[i], msg parity_final_expected = np.array([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1 ]) for i in range(len(res.transitions_BE2[:, 5])): msg = "BE2: Error in parity_final." msg += f" Expected: {parity_final_expected[i]}, got {res.transitions_BE2[i, 5]}." assert res.transitions_BE2[i, 5] == parity_final_expected[i], msg Ex_final_expected = E_gs - np.abs(np.array([ -40.802, -40.802, -40.802, -40.802, -40.802, -40.754, -40.666, -40.412, -40.375, -40.085, -40.060, -39.988, -39.802, -49.430, -46.309, -45.973, -44.988, -44.810, -44.615, -44.470, -43.619, -43.483, -42.618, -42.610, -42.173, -42.140 ])) for i in range(len(res.transitions_BE2[:, 7])): msg = "BE2: Error in Ex_final." msg += f" Expected: {Ex_final_expected[i]}, got {res.transitions_BE2[i, 7]}." assert res.transitions_BE2[i, 7] == Ex_final_expected[i], msg E_gamma_expected = np.array([ 2.032, 1.259, 1.190, 0.408, 0.315, 0.048, 0.136, 0.390, 0.427, 0.717, 0.742, 0.814, 1.000, 0.996, 4.117, 4.452, 5.437, 5.616, 5.811, 5.956, 6.806, 0.396, 1.261, 1.269, 1.706, 1.739 ]) for i in range(len(res.transitions_BE2[:, 8])): msg = "BE2: Error in E_gamma." msg += f" Expected: {E_gamma_expected[i]}, got {res.transitions_BE2[i, 8]}." assert res.transitions_BE2[i, 8] == E_gamma_expected[i], msg B_decay_expected = np.array([ 0.51104070, 16.07765200, 4.57882840, 8.57092480, 0.46591730, 0.13763550, 13.32346160, 2.80866440, 266.60020590, 2.26964570, 1.78483210, 0.08375330, 23.60063140, 675.71309460, 0.32412310, 0.97507780, 19.98328650, 0.28167560, 5.18973520, 0.05644800, 0.90882360, 0.07640840, 1.66964180, 0.84907290, 0.28217940, 5.27947770 ]) for i in range(len(res.transitions_BE2[:, 9])): msg = "BE2: Error in B_decay." msg += f" Expected: {B_decay_expected[i]}, got {res.transitions_BE2[i, 9]}." assert res.transitions_BE2[i, 9] == B_decay_expected[i], msg B_excite_expected = np.array([ 2.55520380, 80.38826020, 22.89414210, 42.85462440, 2.32958690, 0.02752710, 2.66469230, 0.56173280, 53.32004120, 0.45392910, 0.35696640, 0.01675060, 4.72012620, 135.14261890, 0.06482460, 0.19501550, 3.99665730, 0.05633510, 1.03794700, 0.01128960, 0.18176470, 0.07640840, 1.66964180, 0.84907290, 0.28217940, 5.27947770 ]) for i in range(len(res.transitions_BE2[:, 10])): msg = "BE2: Error in B_excite." msg += f" Expected: {B_excite_expected[i]}, got {res.transitions_BE2[i, 10]}." assert res.transitions_BE2[i, 10] == B_excite_expected[i], msg # BM1 # --- spin_initial_expected = np.array([ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2 ]) for i in range(len(res.transitions_BM1[:, 0])): msg = "BM1: Error in spin_initial." msg += f" Expected: {spin_initial_expected[i]}, got {res.transitions_BM1[i, 0]}." assert res.transitions_BM1[i, 0] == spin_initial_expected[i], msg parity_initial_expected = np.array([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1 ]) for i in range(len(res.transitions_BM1[:, 1])): msg = "BM1: Error in parity_initial." msg += f" Expected: {parity_initial_expected[i]}, got {res.transitions_BM1[i, 1]}." assert res.transitions_BM1[i, 1] == parity_initial_expected[i], msg Ex_initial_expected = E_gs - np.abs(np.array([ -43.539, -42.609, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -40.802, -42.467, -42.467, -42.467, -45.697, -45.001, -44.512, -44.439, -44.017, -43.294, -43.063 ])) for i in range(len(res.transitions_BM1[:, 3])): msg = "BM1: Error in Ex_initial." msg += f" Expected: {Ex_initial_expected[i]}, got {res.transitions_BM1[i, 3]}." assert res.transitions_BM1[i, 3] == Ex_initial_expected[i], msg spin_final_expected = np.array([ 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0 ]) for i in range(len(res.transitions_BM1[:, 4])): msg = "BM1: Error in spin_final." msg += f" Expected: {spin_final_expected[i]}, got {res.transitions_BM1[i, 4]}." assert res.transitions_BM1[i, 4] == spin_final_expected[i], msg parity_final_expected = np.array([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1 ]) for i in range(len(res.transitions_BM1[:, 5])): msg = "BM1: Error in parity_final." msg += f" Expected: {parity_final_expected[i]}, got {res.transitions_BM1[i, 5]}." assert res.transitions_BM1[i, 5] == parity_final_expected[i], msg Ex_final_expected = E_gs - np.abs(np.array([ -40.802, -40.802, -40.786, -40.700, -40.178, -40.068, -39.878, -39.615, -39.376, -39.254, -39.167, -35.222, -35.217, -35.174, -42.351, -42.351, -42.351, -42.351, -42.351, -42.351, -42.351 ])) for i in range(len(res.transitions_BM1[:, 7])): msg = "BM1: Error in Ex_final." msg += f" Expected: {Ex_final_expected[i]}, got {res.transitions_BM1[i, 7]}." assert res.transitions_BM1[i, 7] == Ex_final_expected[i], msg E_gamma_expected = np.array([ 2.737, 1.808, 0.016, 0.101, 0.624, 0.734, 0.924, 1.187, 1.425, 1.548, 1.635, 7.246, 7.250, 7.293, 3.346, 2.649, 2.161, 2.087, 1.665, 0.943, 0.711 ]) for i in range(len(res.transitions_BM1[:, 8])): msg = "BM1: Error in E_gamma." msg += f" Expected: {E_gamma_expected[i]}, got {res.transitions_BM1[i, 8]}." assert res.transitions_BM1[i, 8] == E_gamma_expected[i], msg B_decay_expected = np.array([ 0.00000640, 0.00013110, 0.00023580, 0.00232120, 6.16214940, 0.00008630, 0.00388720, 0.00055320, 0.00001990, 0.72079000, 0.00458170, 0.00000170, 0.00142630, 0.00016040, 0.00543100, 0.44305110, 0.00001740, 0.00056840, 0.00007460, 0.10609890, 0.02403140 ]) for i in range(len(res.transitions_BM1[:, 9])): msg = "BM1: Error in B_decay." msg += f" Expected: {B_decay_expected[i]}, got {res.transitions_BM1[i, 9]}." assert res.transitions_BM1[i, 9] == B_decay_expected[i], msg B_excite_expected = np.array([ 0.00001940, 0.00039350, 0.00007860, 0.00077370, 2.05404980, 0.00002870, 0.00129570, 0.00018440, 0.00000660, 0.24026330, 0.00152720, 0.00000050, 0.00047540, 0.00005340, 0.01629320, 1.32915340, 0.00005220, 0.00170520, 0.00022400, 0.31829690, 0.07209440 ]) for i in range(len(res.transitions_BM1[:, 10])): msg = "BM1: Error in B_excite." msg += f" Expected: {B_excite_expected[i]}, got {res.transitions_BM1[i, 10]}." assert res.transitions_BM1[i, 10] == B_excite_expected[i], msg if __name__ == "__main__": test_file_read_levels() test_int_vs_floor() test_file_read_transitions() # test_file_read_levels_jem() # test_file_read_transitions_jem()
6ac7c6cc7b7aefa9f670fa5e23340700df2d429e
[ "Markdown", "Python" ]
20
Python
JonKDahl/kshell_utilities
271321369b933c6c8678b8a592529cb0935431d3
77dc3b016e30330d430ad8e3979a342c6649a309
refs/heads/master
<file_sep># Hydrological Flow Model Implementation of the D8 algorithm, a lake identification and flow algorithm with python and matplotlib. This code implements a flow algorithm using a DEM and rainfall data. It further identifies and fills pitflags / lakes and develops a drainage algorithm using a gravitation model towards the lake outflow. For more information and pseudo-code of the drainage algorithm see: [www.geo-blog.com/lake-flow-algorithm](http://www.geo-blog.com/lake-flow-algorithm/) The code is split into four different tasks (see comments in Driver.py). ## TASK 1 The output diagram "Network structure - before lakes" displays a flow network structure before removing pitflags (the networks are not connected). ![task1](img/task1.png) The background in this figure represents the elevation, with yellow colours representing higher raster cells and blue colours indicating low raster cells. The lines represent the flow direction. The flow direction is calculated with the standard algorithm D8, introduced by O’Callaghan & Mark (1984), which looks at the 8 neighbour cells and sets the flow direction to the lowest neighbour (see also setDownnode() method of FlowRaster class in Flow.py). Furthermore, when no neighbouring cell is lower than the cell itself it is marked with a red point in Figure 1, representing a “pitflag”. Pitflags are raster cells that don’t have a downnode, i.e. the water can’t flow in any other cell from this cell. ## TASK 2 Task 2 calculates flow rates (assuming constant rainfall) using the network structure from task 1. The flow rates are calculated in the recursive function *getFlow()*. Note that water seems to disappear in a lake / pitflag because the networks are not joined yet. ![task1](img/task2.png) This figure shows the river flow rates with constant rain (1mm per cell). Yellow values indicate a high flow rate while blue values indicate a low flow rate. ## TASK 3 Task 3 repeats task 2 using non-constant rainfall (randomly generated) ## TASK 4 Task 4 makes the hydrological model more realistic by joining the catchment areas. To do this, sinks and lakes are identified and outflows of the lakes are calculated. This was carried out in three steps. First, lakes are identified by an algorithm starting with each pitflag and creating a path to an edge with always choosing the lowest neighbour (similar to the D8 algorithm). The highest point of this path represents the outflow of the lake. In a second step, the identified lakes are filled up to the same height as the outflow. Third, a new flow with gravitation towards the lake outflow is calculated for each lake. To test the implemented algorithm the incoming rainfall and the summed flow at pitflags on an edge were compared. The two values had to be the same. ![algorithm](img/algorithm.jpg) Algorithm for calculating flow with gravitation towards the lake outflow. ![task4](img/task40.png) ![task4](img/task41.png) ![task4](img/task42.png) ## TASK 5 For task 5 real raster data (rainfall and DEM) is imported and converted to the same resolution. ![task5](img/task5.png) <file_sep># -*- coding: utf-8 -*- """ """ import numpy as np class Raster(object): '''A class to represent 2-D Rasters''' def __init__(self,data,xorg,yorg,cellsize,nodata=-999.999): """Constructor of a Raster, sets all the object variables Origin: xorg=0 and yorg=0 is left down corner of a cell Input Parameter: data xorg – An Integer describing x-origin yorg – An Integer describing y-origin cellsize – A Number describing cellsize (e.g. 1) nodata – No data representation """ self._data=np.array(data) self._orgs=(xorg,yorg) self._cellsize=cellsize self._nodata=nodata def getData(self): return self._data def getShape(self): """return the shape of the data array""" return self._data.shape def getRows(self): return self._data.shape[0] def getCols(self): return self._data.shape[1] def getOrgs(self): """Returns raster origin Returns: self._orgs – a tuple of (xorg, yorg) """ return self._orgs def getCellsize(self): return self._cellsize def getNoData(self): return self._nodata def createWithIncreasedCellsize(self, factor): """returns a new Raster with cell size larger by a factor (which must be an integer) Input Parameter: factor – factor of increased cellsize Returns: resampled Raster, a Raster object """ if factor== 1: #doesnt do anything return self else: return self.resample(factor) def resample(self, factor): """Resamples the raster Input Parameter: factor – factor of cellsize Returns: resampled Raster, a Raster object """ nrows=self.getRows() // factor #floor division, calcucate new number of rows ncols=self.getCols() // factor #floor division, calcucate new number of cols newdata=np.zeros([nrows, ncols]) #create empty array for i in range(nrows): #iterate for j in range(ncols): #iterate sumCellValue=0.0 #set sum to zero at the start for k in range(factor): #smaller box iterates through values in a (new) cell for l in range(factor): #"i*factor + k" calculates y position of data in original raster sumCellValue += self._data[i*factor + k, j*factor +l] #add new value to sum newdata[i,j]=sumCellValue / factor / factor + 100 #dividing by number of cells return Raster(newdata, self.getOrgs()[0],self.getOrgs()[1], self._cellsize*factor) #return new raster def __repr__(self): """String representation """ return str(self.getData())<file_sep># -*- coding: utf-8 -*- """ Created on Mon Nov 05 00:46:36 2012 @author: nrjh """ import math class Point2D(object): '''A class to represent 2-D points''' def __init__(self,x,y): """Constructor for Point2D Input Parameter: x – x-coordinate, an integer or float y – y–coordinate, an integer or float """ self._x=x*1. #ensure points are always floats self._y=y*1. def clone(self): """returns a clone of self (another identical Point2D object) """ return Point2D(self._x,self._y) def get_x(self): """returns x coordinate""" return self._x def get_y(self): """returns y coordinate""" return self._y def get_coord(self,arg): """return x coord if arg=0, else y coord""" if arg==0: return self._x else: return self._y def get_xys(self): """returns x,y tupel""" return (self.x,self._y) def move(self,x_move,y_move): """moves points by specified x-y vector""" self._x = self._x + x_move self._y = self._y + y_move def distance(self, other_point): """calculates and return distance""" xd=self._x-other_point._x yd=self._y-other_point._y return math.sqrt((xd*xd)+(yd*yd)) def samePoint(self,point): if point==self: return True def sameCoords(self,point,absolute=True,tol=1e-12): if absolute: return (point.get_x()==self._x and point.get_y()==self._y) else: xequiv=math.abs((self.get_x()/point.get_x())-1.)<tol yequiv=math.abs((self.get_y()/point.get_y())-1.)<tol return xequiv and yequiv #End of class Point 2D #******************************************************** class PointField(object): '''A class to represent a field (collection) of points''' def __init__(self,PointsList=None): self._allPoints = [] if isinstance(PointsList, list): self._allPoints = [] for point in PointsList: if isinstance(point, Point2D): self._allPoints.append(point.clone()) def getPoints(self): return self._allPoints def size(self): return len(self._allPoints) def move(self,x_move,y_move): for p in self._allPoints: p.move(x_move,y_move) def append(self,p): self._allPoints.append(p.clone()) #method nearestPoint def nearestPoint(self,p,exclude=False): """A simple method to find the nearest Point to the passed Point2D object, p. Exclude is a boolean we can use at some point to deal with what happens if p is in the point set of this object, i.e we can choose to ignore calculation of the nearest point if it is in the same set""" #check we're been passed a point if isinstance(p,Point2D): #set first point to be the initial nearest distance nearest_p=self._allPoints[0] nearest_d=p.distance(nearest_p) # now itereate through all the other points in the PointField # testing for each point, i.e start at index 1 for testp in self._allPoints[1:]: # calculate the distance to each point (as a test point) d=p.distance(testp) # if the test point is closer than the existing closest, update # the closest point and closest distance if d<nearest_d: nearest_p=testp nearest_d=d # return the nearest point return nearest_p #else not a Point passed, return nothing else: return None def sortPoints(self): """ A method to sort points in x using raw position sort """ self._allPoints.sort(pointSorterOnX) class Point3D (Point2D): def __init__(self, x, y, z): print ('I am a Point3D object') Point2D.__init__(self, x, y) self._z = z print ('My z coordinate is ' + str(self._z)) print ('My x coordinate is ' + str(self._x)) print ('My x coordinate is ' + str(self._y)) def clone(self): return Point3D(self._x, self._y, self._z) def get_z(self): return self._z def move(self, x_move, y_move, z_move): Point2D.move(self,x_move, y_move) self._z = self._z + z_move def distance(self, other_point): zd=self._z-other_point.get_z() # xd=self._x-other_point.get_x() # yd=self._y-other_point.get_y() d2=Point2D.distance(self,other_point) d3=math.sqrt((d2*d2)+(zd*zd)) return d3 def pointSorterOnX(p1,p2): x1=p1.get_x() x2=p2.get_x() if (x1<x2): return -1 elif (x1==x2): return 0 else: return 1 def pointSorterOnY(p1,p2): y1=p1.get_y() y2=p2.get_y() if (y1<y2): return -1 elif (y1==y2): return 0 else: return 1 <file_sep>from RasterHandler import createRanRasterSlope import matplotlib.pyplot as mp import Flow as Flow from RasterHandler import readRaster """This is the driver - <NAME> S1790173""" def plotstreams(flownode,colour): """Recursively plots upnodes in given colour Input Parameter: flownode – a FlowNode object colour – a colour, e.g. "red" """ for node in flownode.getUpnodes(): x1=flownode.get_x() y1=flownode.get_y() x2=node.get_x() y2=node.get_y() mp.plot([x1,x2],[y1,y2],color=colour) if (node.numUpnodes()>0): plotstreams(node,colour) def plotFlowNetwork(originalRaster, flowRaster, title="", plotLakes=True): """Plots a flow network Input Parameter: originalRaster – a Raster object flowRaster – a FlowRaster object title – plot title, a string plotLake – binary variable stating if lakes should be plotted True if lakes should be plotted False if lakes should be ignored """ print ("\n\n{}".format(title)) mp.imshow(originalRaster.extractValues(Flow.ElevationExtractor())) mp.colorbar() colouri=-1 colours=["black","red","magenta","yellow","green","cyan","white","orange","grey","brown"] for i in range(flowRaster.getRows()): for j in range(flowRaster.getCols()): node = flowRaster._data[i,j] if (node.getPitFlag()): # dealing with a pit mp.scatter(node.get_x(),node.get_y(), color="red") colouri+=1 plotstreams(node, colours[colouri%len(colours)]) if (plotLakes and node.getLakeDepth() > 0): #if lakedepth is zero, it is not a lake mp.scatter(node.get_x(),node.get_y(), color="blue") mp.show() def plotExtractedData(flowRaster, extractor, title=""): """Plots extracted data Input Parameter: flowRaster – FlowRaster class object extractor – FlowExtractor class object, or LakedepthExtractor object title – String of chart title """ print ("\n\n{}".format(title)) mp.imshow(flowRaster.extractValues(extractor)) mp.colorbar() mp.show() def plotRaster(araster, title=""): """Plots a raster Input Parameter: araster – Raster class object title – plot title, a string """ print ("\n\n{}, shape is {}".format(title, araster.shape)) mp.imshow(araster) mp.colorbar() mp.show() def calculateFlowsAndPlot(elevation, rain, resampleF): """Calculates all the flows and plots them Input Parameter: elevation – a Raster class object containing elevation rain – a Raster class object containing rainfall resampleF – an Integer """ # plot input rasters plotRaster(elevation.getData(), "Original elevation (m)") #plot elevation plotRaster(rain.getData(), "Rainfall") #plot rainfall resampledElevations = elevation.createWithIncreasedCellsize(resampleF) ################# step 1 find and plot the intial network ####### fr=Flow.FlowRaster(resampledElevations) #create FlowRaster plotFlowNetwork(fr, fr, "Task 1: Network structure - before lakes", plotLakes=False) #plot flow raster ################Step 2 ###################################### plotExtractedData(fr, Flow.FlowExtractor(1), "Task 2: River flow rates - constant rain") ################# step 3 ####################################### #handle variable rainfall fr.addRainfall(rain.getData()) plotExtractedData(fr, Flow.FlowExtractor(), "Task 3: River flow rates - variable rainfall") ############# step 4 and step 5 ####################################### # handle lakes fr.calculateLakes() plotFlowNetwork(fr, fr, "Task 4: Network structure (i.e. watersheds) - with lakes") plotExtractedData(fr, Flow.LakeDepthExtractor(), "Task 4: Lake depth") plotExtractedData(fr, Flow.FlowExtractor(), "Parallel Flows") #TESTING #this line tests if total raster outflow is equal to total rainfall on the raster assert round(fr.getTotalFlow(), 2) == round(fr.getTotalRainfall(),2) ############# step 5 ####################################### maxflow=fr.getMaximumFlow() print("Task 5: Maximum Flow: {} mm, at FlowNode object: {}".format(round(maxflow[0], 3), maxflow[1])) ############# step 1 to 4 ####################################### # Create Random Raster rows=40 cols=40 xorg=0. yorg=0. xp=5 yp=5 nodata=-999.999 cellsize=1. levels=4 datahi=100. datalow=0 randpercent=0.1 resampleFactorA = 1 elevationRasterA=createRanRasterSlope(rows,cols,cellsize,xorg,yorg,nodata,levels,datahi,datalow,xp,yp,randpercent) rainrasterA=createRanRasterSlope(rows//resampleFactorA,cols//resampleFactorA,cellsize*resampleFactorA,xorg,yorg,nodata,levels,4000,1,36,4,.1) ##random raster calculateFlowsAndPlot(elevationRasterA, rainrasterA, resampleFactorA) ############# step 5 ####################################### #calculateFlowsAndPlot(readRaster('ascifiles/dem_hack.txt'), readRaster('ascifiles/rain_small_hack.txt'), 10) <file_sep># -*- coding: utf-8 -*- """ Created on Thu Jan 31 01:00:00 2013 @author: nrjh """ import numpy as np from Raster import Raster import random import math def readRaster(fileName): """Generates a raster object from a ARC-INFO ascii format file """ lines = [] myFile=open(fileName,'r') end_header=False xll=0. yll=0. nodata=-999.999 cellsize=1.0 while (not end_header): line=myFile.readline() items=line.split() keyword=items[0].lower() value=items[1] if (keyword=='ncols'): ncols=int(value) elif (keyword=='nrows'): nrows=int(value) elif (keyword=='xllcorner'): xll=float(value) elif (keyword=='yllcorner'): yll=float(value) elif (keyword=='nodata_value'): nodata=float(value) elif (keyword=='cellsize'): cellsize=float(value) else: end_header=True if (nrows==None or ncols==None): print ("Row or Column size not specified for Raster file read") return None items=line.split() datarows=[] items=line.split() row=[] for item in items: row.append(float(item)) datarows.append(row) for line in myFile.readlines(): lines.append(line) items=line.split() row=[] for item in items: row.append(float(item)) datarows.append(row) data=np.array(datarows) return Raster(data,xll,yll,cellsize,nodata) def createRanRaster(rows=20,cols=30,cellsize=1,xorg=0,yorg=0,nodata=-999.999,levels=5,datahi=100.,datalo=0.): """Creates a random raster""" levels=min(levels,rows) levels=min(levels,cols) data=np.zeros([levels,rows,cols]) dataout=np.zeros([rows,cols]) for x in np.nditer(data,op_flags=['readwrite']): x[...]=random.uniform(datalo,datahi) for i in range(levels): lin=((i)*2)+1 lin2=lin*lin iterator=np.zeros([lin2,2], dtype=int) for itx in range(lin): for ity in range(lin): iterator[itx*lin+ity,0]=(itx-i) part=data[i] new=np.zeros([rows,cols]) for j in range(rows): for k in range(cols): for it in range(lin2): r=(j+iterator[it,0])%rows c=(k+iterator[it,1])%cols new[j,k]=new[j,k]+part[r,c] minval=np.min(new) maxval=np.max(new) ran=maxval-minval data[i]=((new-minval)/ran)*(2**i) dataout=dataout+data[i] minval=np.min(dataout) maxval=np.max(dataout) ran=maxval-minval datarange=datahi-datalo dataout=(((dataout-minval)/ran)*(datarange))+datalo return Raster(dataout,xorg,yorg,cellsize,nodata) def createRanRasterSlope(rows=20,cols=30,cellsize=1,xorg=0,yorg=0,nodata=-999.999,levels=5,datahi=100.,datalo=0.,focusx=None,focusy=None,ranpart=0.5): """Generates a Random Slope Raster """ if (focusx==None): focusx=cols/2 if (focusy==None): focusy=rows/2 rast=createRanRaster(rows,cols,cellsize,xorg,yorg,nodata,levels,1.,0.) slope_data=np.zeros([rows,cols]) maxdist=math.sqrt(rows*rows+cols*cols) for i in range(rows): for j in range(cols): xd=focusx-j yd=focusy-i dist=maxdist-math.sqrt((xd*xd)+(yd*yd)) slope_data[i,j]=dist/maxdist minval=np.min(slope_data) maxval=np.max(slope_data) ran=maxval-minval slope_data=((slope_data-minval)/ran) ran_data=rast.getData() data_out=slope_data*(1.-ranpart)+ran_data*(ranpart) minval=np.min(data_out) maxval=np.max(data_out) ran=maxval-minval datarange=datahi-datalo data_out=(((data_out-minval)/ran)*datarange)+datalo return Raster(data_out,xorg,yorg,cellsize) <file_sep>import numpy as np from Points import Point2D from Raster import Raster class FlowNode(Point2D): """Class representing nodes (points) in a Flow Raster Inherits from Point2D class """ def __init__(self,x,y, value, rainfall=None): """Constructor for FlowNode Input Parameter: x – x-position of node within grid y – y-position of node within grid value – value at the node position (e.g. elevation) """ Point2D.__init__(self,x,y) #use constructor of super class self._downnode=None #is set with setDownnode() self._upnodes=[] self._pitflag=True #set to true as FlowNode doesn't have a downnode at the moment self._value=value self._rainfall=rainfall self._lakedepth=0 def setDownnode(self, newDownNode): """Sets the downnode of a FlowNode object, sets itself as an upnode Can also be used to change a previous downnode to a new downnode as it removes itself as an upnode Input Parameter: newDownNode – a FlowNode object representing the downnode """ self._pitflag=(newDownNode==None) #sets pitflag to True if downnode exists, else to false if (self._downnode!=None): # change previous self._downnode._removeUpnode(self) #remove itself as upnode (from thre downnode) if (newDownNode!=None): # insert itself as new upnode newDownNode._addUpnode(self) self._downnode=newDownNode # set downnode def getDownnode(self): """ Returns: self._downnode – a FlowNode class object """ return self._downnode def setRainfall(self, rainfall): """Setter for self._rainfall, sets the rainfall at the node Input Parameter: rainfall – rain at FlowNode object in mm """ self._rainfall = rainfall def getRainfall(self): """Getter for self._rainfall Returns: self._rainfall – rain at FlowNode object in mm """ return self._rainfall def getUpnodes(self): """Getter for self._upnodes Returns: self._upnodes – a list of FlowNode class objects """ return self._upnodes def _removeUpnode(self, nodeToRemove): """Removes an upnode Input Parameter: nodeToRemove – a FlowNode object """ self._upnodes.remove(nodeToRemove) def _addUpnode(self, nodeToAdd): """Adds an upnode Input Parameter: nodeToAdd – a FlowNode object """ self._upnodes.append(nodeToAdd) def numUpnodes(self): """ Returns: number of Upnodes """ return len(self._upnodes) def getPitFlag(self): """Getter for self._pitflag Returns: self._pitflag – True or False: True when it is a pitFlag(=no downnodes) False when it is not (=has downnodes) """ return self._pitflag def setLakeDepth(self, depth): """Sets the depth of a lake Input Parameter: depth – lake depth in meter, should be 0 when it is not a lake """ self._lakedepth += depth def getLakeDepth(self): """Getter for depth of lake Returns: self._lakedepth – number, zero when node is not a pitfall """ return self._lakedepth def getFlow(self, constRain=None): """recursively adds the flow of all upnodes and its upnodes etc. If constant rain input parameter is null, flow is calculated from recorded rainfall per node using self._rainfall If both, constant and self._rainfall are None, it calculates with 0mm rain Input Parameter: constRain – constant rain per node in mm, if left out the rainfall per node value is used """ flow=0 #set to zero if constRain is not None: flow=constRain #initial flow is set to constant rain elif self.getRainfall() is not None: #if no constant rain is given it checks if a rainfall at this node is recorded flow=self.getRainfall() #initial flow is set to rainfall on cell for upnode in self.getUpnodes(): #iterare through upnotes flow+=upnode.getFlow(constRain) #add up flow by calling the function recursively with next upnode return flow #return result def getElevation(self): """Getter for Elevation Returns: self._value – a number representing elevation in m at the FlowNode """ return self._value def fill(self, elevation): """Fills the node with water up to a new elevation. Calculates the depth. Input Parameter: elevation – new elevation """ assert elevation >= self.getElevation() self.setLakeDepth(elevation - self.getElevation()) #set new lake depth self._value = elevation def __str__(self): """String representation of FlowNode object """ downnode= -999 if self.getDownnode() is not None: downnode =self.getDownnode().getElevation() return "Flownode y={}, x={}, elevation={} downnode={}".format(self.get_y(), self.get_x(), self.getElevation(), downnode) def __repr__(self): """Representation of FlowNode object """ return self.__str__() class FlowRaster(Raster): """A class containing a Raster with FlowNodes Inherits from Raster """ def __init__(self,araster): """Constructor for FlowRaster Input Parameter: araster – a Raster class object """ #create a new raster out of araster without data super().__init__(None,araster.getOrgs()[0],araster.getOrgs()[1],araster.getCellsize())#call init of raster class data = araster.getData() #get elevation of input raster nodes=[] #insert data for i in range(data.shape[0]): for j in range(data.shape[1]): y=(i)*self.getCellsize()+self.getOrgs()[0] #x-position of node within grid x=(j)*self.getCellsize()+self.getOrgs()[1] #y-position of node within grid nodes.append(FlowNode(x,y, data[i,j]))#add node nodearray=np.array(nodes) #convert list to array nodearray.shape=data.shape #reshape 1d array to shape of the raster self._data = nodearray self.__neighbourIterator=np.array([1,-1,1,0,1,1,0,-1,0,1,-1,-1,-1,0,-1,1] ) #neighbours self.__neighbourIterator.shape=(8,2) self.setDownnodes() #calculate downnodes self._lakes=[] def getPitflags(self): """Returns a list of pitflag nodes Pitflags are nodes without a downnode Returns: pitflags – a list of pitflag nodes """ pitflags=[] for i in range(self._data.shape[0]): for j in range(self._data.shape[1]): if self._data[i,j].getPitFlag(): pitflags.append(self._data[i,j]) return pitflags def calculateLakes(self): """Calculates lakes and creates Lake class objects Calculates lakes from pitflags, calculates depth for each lake node, Readjusts elevation of lake nodes to lake surface (i.e. fills lakes) and resets downnodes between the lake nodes using a gravity algorithm towards the lake outflow The lakes are stored in self._lakes, a list with Lake objects """ for pitflag in self.getPitflags(): #iterate through pitflags i,j = int(pitflag.get_y()/self.getCellsize()), int(pitflag.get_x()/self.getCellsize()) edgecase = i==0 or j==0 or i==(self._data.shape[0]-1) or j==(self._data.shape[1]-1) #check again if pitflag because it might have changed when two lakes grow together if pitflag.getPitFlag() and not(edgecase): self._lakes.append(self.createLake(i,j)) #create a lake object for lake in self._lakes: self.setLakeDownnodes(lake) #set new downnodes assert not(lake._outflow.getPitFlag()) assert not(lake._nodes[-2].getPitFlag()) def createLake(self, i,j): """Creates a lake at position i,j Calculates its size and nodes, calculates depths for each lake node and readjusts elevation of lake nodes to lake surface Input Parameter: i – x position (int) j – y position (int) Returns: lake – a Lake class object """ assert self._data[i,j].getPitFlag() ##assert that it's a pitflag lake=Lake(self._data[i,j]) #create new Lake object lake.addNeighbours(self.getNeighbours(i,j)) #add initial lake neighbours while(lake._outflow is None): #while lake has no outflow lowest=lake.lowestNeighbour() r,c=int(lowest.get_y()/self.getCellsize()), int(lowest.get_x()/self.getCellsize()) #row and col lake.addNode(lowest) #adds a new node to the lake, this also removes the node from neighbours lake.addNeighbours(self.getNeighbours(r,c)) #add new neighbours edgecase = r==0 or c==0 or r==(self._data.shape[0]-1) or c==(self._data.shape[1]-1) if lowest.getPitFlag() and edgecase: #yeah we arrived at an edge pitfall, no more searching is needed lake.finalise() # finalise the lake return lake def setLakeDownnodes(self, lake): """Recalculates the downnodes for each lake node using a gravitation algorithm towards the outflow. Recalculates the outflow downnode. Input Parameter: lake – a Lake object """ checked=[] #stores checked nodes checknode=lake._outflow #stores the current node to be checked tocheck=[lake._outflow] #stores the future nodes to be checked while (len(tocheck)+len(checked))<(len(lake._nodes)): #while not every downnode is reset r,c=int(checknode.get_y()/self.getCellsize()), int(checknode.get_x()/self.getCellsize()) neighbours = self.getNeighbours(r,c) #get new neighbours of checknode for n in neighbours: if lake.isLake(n) and n not in tocheck and n not in checked: #if downnode is not set yet n.setDownnode(checknode) #set a downnode from neighbour to checknode tocheck.append(n) #append the new neigbours tocheck.remove(checknode) #remove the checknode checked.append(checknode) #append the checked to checked nearest=self.getNearest(lake._outflow, tocheck) #nearest from outflow checknode=nearest #set lake downnode of outflow x=int(lake._outflow.get_x()/self.getCellsize()) y=int(lake._outflow.get_y()/self.getCellsize()) lake._outflow.setDownnode(self.lowestNeighbour(y,x)) #set outflows downnodes def getNearest(self, node, nodelist): """Returns nearest point from nodelist to node Input Parameter: node – origin node, a Flow node object nodelist – list with FlowNode object Returns: pNearest – the nearest point to a node, a FlowNode object """ dNearest=None pNearest=None for n in nodelist: d = node.distance(n) if dNearest is None or d<dNearest: dNearest=d pNearest=n return pNearest def getNeighbours(self, r, c): """ Returns the eight neighbours of a cell Input Parameter: r – x-coordinate of the cell c – y-coordinate of the cell Returns: neighbours – a list of 8 neighbour FlowNode objects """ neighbours=[] for i in range(8): rr=r+self.__neighbourIterator[i,0] cc=c+self.__neighbourIterator[i,1] if (rr>-1 and rr<self.getRows() and cc>-1 and cc<self.getCols()): neighbours.append(self._data[rr,cc]) return neighbours def lowestNeighbour(self,r,c): """Calculates the lowest neighbour, excluding itself Input Parameter: r – x-coordinate of the cell c – y-coordinate of the cell Returns: lownode - the node representing the lowest neighbour, a FlowNode object """ lownode=None for neighbour in self.getNeighbours(r,c): if lownode==None or neighbour.getElevation() < lownode.getElevation(): lownode=neighbour return lownode def setDownnodes(self): """Calculates Downnodes and sets them for each FlowNode object """ for r in range(self.getRows()): for c in range(self.getCols()): lowestN = self.lowestNeighbour(r,c) if (lowestN.getElevation() < self._data[r,c].getElevation()): self._data[r,c].setDownnode(lowestN) #set downnode, upnode is set within the FlowNode class def getMaximumFlow(self): """Calculates the maximum flow within the FlowRaster Returns: a tuple – (maxrate, maxnode) maxrate: maximum flow rate, a float maxnode: node with maximum flow rate, a Flownode object """ flow=self.extractValues(FlowExtractor()) #get flow data maxrate=None maxnode=None for i in range(flow.shape[0]): #iterate through data for j in range(flow.shape[1]): #iterate through data if maxrate is None or flow[i,j]>maxrate: maxrate=flow[i,j] maxnode=(i,j) return (maxrate, self._data[maxnode[0],maxnode[1]]) def getTotalRainfall(self): """Calculates the total rainfall over all cells Returns: total rainfall – a number """ rainfall=self.extractValues(RainfallExtractor()) total=0 for i in range(rainfall.shape[0]): #iterate through data for j in range(rainfall.shape[1]): #iterate through data total+=rainfall[i,j] #add rainfall return total def getTotalFlow(self): """Calculates the total flow over all cells Returns: total flow – a number """ flow=self.extractValues(FlowExtractor()) total=0 for i in range(flow.shape[0]): #iterate through data for j in range(flow.shape[1]): #iterate through data edgecase = i==0 or j==0 or i==(self._data.shape[0]-1) or j==(self._data.shape[1]-1) if self._data[i,j].getPitFlag() and edgecase: total+=flow[i,j] return total def extractValues(self, extractor): """Extract values from FlowRaster object Input Parameter: extractor – A FlowExtractor class object """ values=[] for i in range(self._data.shape[0]): #iterate through data for j in range(self._data.shape[1]): #iterate through data values.append(extractor.getValue(self._data[i,j])) valuesarray=np.array(values) #convert to numpy array valuesarray.shape=self._data.shape #reshape return valuesarray def addRainfall(self, rainfall): """Adds rainfall to the Raster by adding the rainfall value to each FlowNode Input Parameter: rainfall – numpy.ndarray containing rainfall for each cell expected to have the same size an shape as the raster data """ assert rainfall.shape[0]==self._data.shape[0] #assert that same shape assert rainfall.shape[1]==self._data.shape[1] #assert that same shape for i in range(rainfall.shape[0]): #iterate through array for j in range(rainfall.shape[1]): #iterate through array self._data[i,j].setRainfall(rainfall[i,j]) #set cells rainfall class Lake(): """A class representing lakes Helper for the calculation of lakes """ def __init__(self, startNode): """Contructor for Lake class Input Parameter: startNode – pitflag to start calculating the lake """ assert startNode.getPitFlag() self._neighbours = [] self._nodes = [] self.addNode(startNode) self._outflow=None def addNeighbours(self, neighbours): """Adds new neighbours to self._neighbours ¨¨ Input Parameter: neighbours – a list of neighbour nodes """ for node in neighbours: #check if already in lake or already in neighbours if node not in self._neighbours and node not in self._nodes: self._neighbours.append(node) def removeNeighbour(self, node): """Removes neighbours from self._neighbours Input Parameter: node – a FlowNode object which should be removed """ if node in self._neighbours: self._neighbours.remove(node) def lowestNeighbour(self): """Calculates the lowest neighbour of the lake Returns: lownode - the node representing the lowest neighbour, a FlowNode object """ lownode=None for neighbour in self._neighbours: if lownode==None or neighbour.getElevation() < lownode.getElevation(): lownode=neighbour return lownode def addNode(self, node): """adds a new node to the lake, removes the node from self._neighbours Input Parameter: node – to be added, a FlowNode object """ assert node not in self._nodes self.removeNeighbour(node) self._nodes.append(node) for node in self._nodes: assert node not in self._neighbours def isLake(self, node): """Returns true if the input node is in the Lake Input Parameter: node – a FlowNode object """ return node in self._nodes def finalise(self): """Finalises a lake. Calculates the lake outflow (highest point) and removes nodes within self._nodes visited after the outflow. The lake path must have arrived at an edge pitflag to call this method """ assert self._nodes[-1].getPitFlag() #must arrive at a pitflag highest = self.getHighestPosition() self._outflow=self._nodes[highest] self._nodes=self._nodes[:highest+1] for node in self._nodes: node.fill(self._outflow.getElevation()) def getHighestPosition(self): """Calculates highest position of a lake pathe Returns: an index of the position of the highest point within self._node list """ highest=None index=None for i, node in enumerate(self._nodes): if highest==None or node.getElevation() >= highest.getElevation(): #>= because it should replace when equal highest=node index=i return index class FlowExtractor(): """A class responsible for extracting flow values """ def __init__(self, rain=None): """Constructor of FlowExtractor if a constant rain parameter is given the flow will be calculated with the constant rain. Input Parameter: rain – an optional constant rain parameter (per cell) in mm """ self._constantRain=rain def getValue(self, node): """extracts the flow value of a node Input Parameter: node – A FlowNode class object """ return node.getFlow(self._constantRain) class LakeDepthExtractor(): """A class responsible for extracting lake depth values """ def getValue(self, node): """extracts the flow value of a node Input Parameter: node – A FlowNode class object """ return node.getLakeDepth() class ElevationExtractor(): """A class responsible for extracting elevation values """ def getValue(self, node): """extracts the flow value of a node Input Parameter: node – A FlowNode class object """ return node.getElevation() class RainfallExtractor(): """A class responsible for extracting rainfall values """ def getValue(self, node): """extracts the flow value of a node Input Parameter: node – A FlowNode class object """ return node.getRainfall()
5c90e048c16ee9a3961af6015362b0d0bfb0cabc
[ "Markdown", "Python" ]
6
Markdown
liviajakob/hydrological-model
593180367532cc19c5803dfa55c1d70ec3dd0e68
a64bb1c0e499460c4205fa18072e4b9e5f227e55
refs/heads/main
<repo_name>singletube/dobl_prot<file_sep>/main.py from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired from flask import Flask, render_template, redirect app = Flask(__name__) app.config['SECRET_KEY'] = 'yandexlyceum_secret_key' class LoginForm(FlaskForm): username = StringField('id Астронавта', validators=[DataRequired()]) password = PasswordField('<PASSWORD>', validators=[DataRequired()]) username_cap = StringField('id Капитана', validators=[DataRequired()]) password_cap = PasswordField('<PASSWORD>', validators=[DataRequired()]) submit = SubmitField('Доступ') @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): return redirect('/success') return render_template('index.html', title='Миссия колонизации марса', form=form) if __name__ == '__main__': print('http://127.0.0.1:8080/login') app.run(port=8080, host='127.0.0.1')
1335dd3d389d7d0a5c7e6f4d6eaa21e86b9e0e8c
[ "Python" ]
1
Python
singletube/dobl_prot
f369b580d018002b9c821f3eae17cee8814000fa
825d71494404f8678f3c5c731269196889c93305
refs/heads/master
<repo_name>SeeminglyScience/PSLambda<file_sep>/src/PSLambda/Empty.cs using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides utility methods for empty elements. /// </summary> internal static class Empty { /// <summary> /// Gets an empty <see cref="IScriptExtent" />. /// </summary> internal static IScriptExtent Extent => new EmptyScriptExtent(); /// <summary> /// Gets an empty <see cref="IScriptPosition" />. /// </summary> internal static IScriptPosition Position => new EmptyScriptPosition(); private class EmptyScriptExtent : IScriptExtent { public int EndColumnNumber => 0; public int EndLineNumber => 0; public int EndOffset => 0; public IScriptPosition EndScriptPosition => Position; public string File => string.Empty; public int StartColumnNumber => 0; public int StartLineNumber => 0; public int StartOffset => 0; public IScriptPosition StartScriptPosition => Position; public string Text => string.Empty; } private class EmptyScriptPosition : IScriptPosition { public int ColumnNumber => 0; public string File => string.Empty; public string Line => string.Empty; public int LineNumber => 0; public int Offset => 0; public string GetFullScript() => string.Empty; } } } <file_sep>/src/PSLambda/Commands/ICommandHandler.cs using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda.Commands { /// <summary> /// Provides handling for a custom command. /// </summary> internal interface ICommandHandler { /// <summary> /// Gets the name of the command. /// </summary> string CommandName { get; } /// <summary> /// Creates a Linq expression for a <see cref="CommandAst" /> representing /// the custom command. /// </summary> /// <param name="commandAst">The AST to convert.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the expression.</param> /// <returns>An expression representing the command.</returns> Expression ProcessAst(CommandAst commandAst, CompileVisitor visitor); } } <file_sep>/src/PSLambda/LabelScope.cs using System; using System.Linq.Expressions; namespace PSLambda { /// <summary> /// Represents the a scope in which the <c>return</c> keyword will work. /// </summary> internal class LabelScope { /// <summary> /// The parent scope. /// </summary> internal readonly LabelScope _parent; private LabelTarget _label; /// <summary> /// Initializes a new instance of the <see cref="LabelScope" /> class. /// </summary> internal LabelScope() { } /// <summary> /// Initializes a new instance of the <see cref="LabelScope" /> class. /// </summary> /// <param name="parent">The parent <see cref="LabelScope" />.</param> internal LabelScope(LabelScope parent) { _parent = parent; } /// <summary> /// Gets or sets a value indicating whether an explicit return statement has been used. /// </summary> public bool IsReturnRequested { get; set; } /// <summary> /// Gets or sets the implied or explicit return type. /// </summary> public Type ReturnType { get; set; } /// <summary> /// Gets the current <c>return</c> label. /// </summary> public LabelTarget Label { get { if (_label != null) { return _label; } _label = Expression.Label(ReturnType); return _label; } } } } <file_sep>/src/PSLambda/ExpressionExtensions.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides utility methods for creating <see cref="Expression" /> objects. /// </summary> internal static class ExpressionExtensions { private static readonly Expression[] s_emptyExpressions = new Expression[0]; /// <summary> /// Compile all asts in a given <see cref="IList{TAst}" />. /// </summary> /// <param name="asts">The <see cref="Ast" /> objects to compile.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the compile.</param> /// <typeparam name="TAst">The type of <see cref="Ast" /> to expect in the list.</typeparam> /// <returns>The compiled <see cref="Expression" /> objects.</returns> public static Expression[] CompileAll<TAst>(this IList<TAst> asts, CompileVisitor visitor) where TAst : Ast { if (asts == null || asts.Count == 0) { return s_emptyExpressions; } var expressions = new Expression[asts.Count]; for (var i = 0; i < asts.Count; i++) { expressions[i] = (Expression)asts[i].Visit(visitor); } return expressions; } /// <summary> /// Compile a <see cref="Ast" /> into a <see cref="Expression" />. /// </summary> /// <param name="ast">The <see cref="Ast" /> to compile.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the compile.</param> /// <returns>The compiled <see cref="Expression" /> object.</returns> public static Expression Compile(this Ast ast, CompileVisitor visitor) { try { return (Expression)ast.Visit(visitor); } catch (ArgumentException e) { visitor.Errors.ReportParseError(ast.Extent, e); return Expression.Empty(); } catch (InvalidOperationException e) { visitor.Errors.ReportParseError(ast.Extent, e); return Expression.Empty(); } } } } <file_sep>/src/PSLambda/PSLambdaAssemblyInitializer.cs using System; using System.Collections.Generic; using System.Management.Automation; namespace PSLambda { /// <summary> /// Provides initialization services when the module is imported. /// </summary> public class PSLambdaAssemblyInitializer : IModuleAssemblyInitializer { private const string TypeAcceleratorTypeName = "System.Management.Automation.TypeAccelerators"; private const string GetPropertyName = "Get"; /// <summary> /// Attempts to create the type accelerator for <see cref="PSDelegate" />. /// </summary> public void OnImport() { var accelType = typeof(PSObject).Assembly.GetType(TypeAcceleratorTypeName); if (accelType == null) { return; } var getProperty = accelType.GetProperty(GetPropertyName); if (getProperty == null) { return; } if (!(getProperty.GetValue(null) is Dictionary<string, Type> existing)) { return; } if (existing.ContainsKey(Strings.PSDelegateTypeAcceleratorName)) { return; } var addMethod = accelType.GetMethod( Strings.AddMethodName, new[] { typeof(string), typeof(Type) }); if (addMethod == null) { return; } try { addMethod.Invoke( null, new object[] { Strings.PSDelegateTypeAcceleratorName, typeof(PSDelegate) }); } catch (Exception) { return; } } } } <file_sep>/src/PSLambda/VariableScope.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace PSLambda { /// <summary> /// Represents the variable scope for a single block <see cref="Expression" />. /// </summary> internal class VariableScope { private static readonly string[] s_dollarUnderNameCache = { "PSItem", "PSItem2", "PSItem3", "PSItem4", "PSItem5", "PSItem6", "PSItem7", "PSItem8", "PSItem9", "PSItem10", }; private (ParameterExpression Parameter, int Version) _dollarUnder; /// <summary> /// Initializes a new instance of the <see cref="VariableScope" /> class. /// </summary> /// <param name="parameters">Parameters to include in the scope.</param> public VariableScope(ParameterExpression[] parameters) { Parameters = parameters.ToDictionary(p => p.Name); } /// <summary> /// Initializes a new instance of the <see cref="VariableScope" /> class. /// </summary> /// <param name="parent">The parent <see cref="VariableScope" /> object.</param> public VariableScope(VariableScope parent) { Parent = parent; } /// <summary> /// Gets the parent <see cref="VariableScope" />. /// </summary> internal VariableScope Parent { get; } /// <summary> /// Gets the parameter <see cref="Expression" /> objects for the current scope. /// </summary> internal Dictionary<string, ParameterExpression> Parameters { get; } = new Dictionary<string, ParameterExpression>(); /// <summary> /// Gets the variable <see cref="Expression" /> objects for the current scope. /// </summary> internal Dictionary<string, ParameterExpression> Variables { get; } = new Dictionary<string, ParameterExpression>(); /// <summary> /// Creates a new variable expression without looking at previous scopes. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="type">The type of the variable.</param> /// <returns>The variable <see cref="Expression" />.</returns> internal ParameterExpression NewVariable(string name, Type type) { ParameterExpression variable = Expression.Variable(type, name); Variables.Add(name, variable); return variable; } /// <summary> /// Gets an already defined variable <see cref="Expression" /> if it already exists, /// otherwise one is created. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="type">The type of the variable.</param> /// <returns>The variable <see cref="Expression" />.</returns> internal ParameterExpression GetOrCreateVariable(string name, Type type) { return GetOrCreateVariable(name, type, out _); } /// <summary> /// Gets an already defined variable <see cref="Expression" /> if it already exists, /// otherwise one is created. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="type">The type of the variable.</param> /// <param name="alreadyDefined"> /// A value indicating whether the variable has already been defined. /// </param> /// <returns>The variable <see cref="Expression" />.</returns> internal ParameterExpression GetOrCreateVariable(string name, Type type, out bool alreadyDefined) { if (TryGetVariable(name, out ParameterExpression existingVar)) { alreadyDefined = true; return existingVar; } alreadyDefined = false; var newVariable = Expression.Parameter(type ?? typeof(object), name); Variables.Add(name, newVariable); return newVariable; } /// <summary> /// Gets an already defined variable <see cref="Expression" /> if it already exists, /// otherwise one is created. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="typeGetter"> /// A function that retrieves the variable's type if it has not already been defined. /// </param> /// <returns>The variable <see cref="Expression" />.</returns> internal ParameterExpression GetOrCreateVariable(string name, Func<Type> typeGetter) { if (TryGetVariable(name, out ParameterExpression existingVar)) { return existingVar; } var newVariable = Expression.Parameter(typeGetter() ?? typeof(object), name); Variables.Add(name, newVariable); return newVariable; } /// <summary> /// Attempts to get a variable that has already been defined. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="existingVariable">The already defined variable <see cref="Expression" />.</param> /// <returns> /// A value indicating whether an existing variable <see cref="Expression" /> was found. /// </returns> internal bool TryGetVariable(string name, out ParameterExpression existingVariable) { if (Variables.TryGetValue(name, out existingVariable)) { return true; } if (Parameters.TryGetValue(name, out existingVariable)) { return true; } if (Parent != null && Parent.TryGetVariable(name, out existingVariable)) { return true; } return false; } /// <summary> /// Gets the automatic variable <c>$_</c> or <c>$PSItem</c> from the /// current scope, or closest parent scope where it is defined. /// </summary> /// <returns> /// The parameter expression referencing dollar under if defined; /// otherwise <see langword="null" />. /// </returns> internal ParameterExpression GetDollarUnder() { for (VariableScope current = this; current != null; current = current.Parent) { if (current._dollarUnder.Parameter != null) { return current._dollarUnder.Parameter; } } return null; } /// <summary> /// Sets the automatic variable <c>$_</c> or <c>$PSItem</c> in the current /// scope. If the variable exists in a parent scope and the type is the same, /// then the parent variable will be used. If the variable exists in a parent /// scope but the type is not the same, the variable will be renamed behind /// the scenes. /// </summary> /// <param name="type"> /// The static type that dollar under should contain. /// </param> /// <returns> /// The parameter expression referencing dollar under. /// </returns> internal ParameterExpression SetDollarUnder(Type type) { static string GetDollarUnderName(int version) { if (version < s_dollarUnderNameCache.Length) { return s_dollarUnderNameCache[version]; } return string.Concat("PSItem", version); } for (VariableScope scope = Parent; scope != null; scope = scope.Parent) { var dollarUnder = scope._dollarUnder; if (dollarUnder.Parameter == null) { continue; } if (_dollarUnder.Parameter.Type == type) { _dollarUnder = dollarUnder; return _dollarUnder.Parameter; } var version = dollarUnder.Version + 1; _dollarUnder = (Expression.Parameter(type, GetDollarUnderName(version)), version); return _dollarUnder.Parameter; } _dollarUnder = (Expression.Parameter(type, "PSItem"), 0); return _dollarUnder.Parameter; } } } <file_sep>/src/PSLambda/SpecialVariables.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Management.Automation; using System.Management.Automation.Host; namespace PSLambda { /// <summary> /// Provides information about special variables created by the PowerShell engine. /// </summary> internal static class SpecialVariables { /// <summary> /// Contains the names and types of variables that should be available from any scope. /// </summary> internal static readonly Dictionary<string, Type> AllScope = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) { { "?", typeof(bool) }, { "ExecutionContext", typeof(EngineIntrinsics) }, { "Home", typeof(string) }, { "Host", typeof(PSHost) }, { "PID", typeof(int) }, { "PSCulture", typeof(string) }, { "PSHome", typeof(string) }, { "PSUICulture", typeof(string) }, { "PSVersionTable", typeof(System.Collections.Hashtable) }, { "PSEdition", typeof(string) }, { "ShellId", typeof(string) }, { "MaximumHistoryCount", typeof(int) }, }; /// <summary> /// Provides the names and constant <see cref="Expression" /> objects for variables that /// should are language features like <c>true</c>. /// </summary> internal static readonly Dictionary<string, Expression> Constants = new Dictionary<string, Expression>(StringComparer.OrdinalIgnoreCase) { { Strings.TrueVariableName, Expression.Constant(true, typeof(bool)) }, { Strings.FalseVariableName, Expression.Constant(false, typeof(bool)) }, { Strings.NullVariableName, Expression.Constant(null) }, }; /// <summary> /// Provides the names of variables that should be ignored when aquiring local /// scope variables. /// </summary> internal static readonly HashSet<string> IgnoreLocal = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "?", "ExecutionContext", "Home", "Host", "PID", "PSCulture", "PSHome", "PSUICulture", "PSVersionTable", "PSEdition", "ShellId", "MaximumHistoryCount", "MyInvocation", "OFS", "OutputEncoding", "VerboseHelpErrors", "LogEngineHealthEvent", "LogEngineLifecycleEvent", "LogCommandHealthEvent", "LogCommandLifecycleEvent", "LogProviderHealthEvent", "LogProviderLifecycleEvent", "LogSettingsEvent", "PSLogUserData", "NestedPromptLevel", "CurrentlyExecutingCommand", "PSBoundParameters", "Matches", "LASTEXITCODE", "PSDebugContext", "StackTrace", "^", "$", "?", "args", "input", "error", "PSEmailServer", "PSDefaultParameterValues", "PSScriptRoot", "PSCommandPath", "PSSenderInfo", "foreach", "switch", "PWD", "null", "true", "false", "PSModuleAutoLoadingPreference", "IsLinux", "IsMacOS", "IsWindows", "IsCoreCLR", "DebugPreference", "WarningPreference", "ErrorActionPreference", "InformationPreference", "ProgressPreference", "VerbosePreference", "WhatIfPreference", "ConfirmPreference", "ErrorView", "PSSessionConfigurationName", "PSSessionApplicationName", "ExecutionContext", "Host", "PID", "PSCulture", "PSHOME", "PSUICulture", "PSVersionTable", "PSEdition", "ShellId", }; } } <file_sep>/src/PSLambda/ParseWriterExtensions.cs using System; using System.Globalization; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides utility methods for reporting specific types of /// <see cref="ParseError" /> objects. /// </summary> internal static class ParseWriterExtensions { /// <summary> /// Generate a <see cref="ParseError" /> citing an unsupported <see cref="Ast" /> type. /// </summary> /// <param name="writer">The <see cref="IParseErrorWriter" /> that should issue the report.</param> /// <param name="ast">The <see cref="Ast" /> that is not supported.</param> internal static void ReportNotSupportedAstType( this IParseErrorWriter writer, Ast ast) { writer.ReportNotSupported( ast.Extent, ast.GetType().Name, string.Format( CultureInfo.CurrentCulture, ErrorStrings.AstNotSupported, ast.GetType().Name)); } /// <summary> /// Generate a <see cref="ParseError" /> citing an unsupported element. /// </summary> /// <param name="writer">The <see cref="IParseErrorWriter" /> that should issue the report.</param> /// <param name="extent">The <see cref="IScriptExtent" /> of the unsupported element.</param> /// <param name="id">The ID to be shown in the <see cref="ParseError" />.</param> /// <param name="message">The message to be shown in the <see cref="ParseError" />.</param> internal static void ReportNotSupported( this IParseErrorWriter writer, IScriptExtent extent, string id, string message) { writer.ReportParseError( extent, string.Format( CultureInfo.CurrentCulture, "{0}.{1}", nameof(ErrorStrings.ElementNotSupported), id), string.Format( CultureInfo.CurrentCulture, ErrorStrings.ElementNotSupported, message)); } /// <summary> /// Generate a <see cref="ParseError" /> citing a missing element. /// </summary> /// <param name="writer">The <see cref="IParseErrorWriter" /> that should issue the report.</param> /// <param name="extent">The <see cref="IScriptExtent" /> of the missing element.</param> /// <param name="id">The ID to be shown in the <see cref="ParseError" />.</param> /// <param name="message">The message to be shown in the <see cref="ParseError" />.</param> internal static void ReportMissing( this IParseErrorWriter writer, IScriptExtent extent, string id, string message) { writer.ReportParseError( extent, string.Format( CultureInfo.CurrentCulture, "{0}.{1}", nameof(ErrorStrings.ElementMissing), id), string.Format( CultureInfo.CurrentCulture, ErrorStrings.ElementMissing, message)); } /// <summary> /// Generate a <see cref="ParseError" />. /// </summary> /// <param name="writer">The <see cref="IParseErrorWriter" /> that should issue the report.</param> /// <param name="extent">The <see cref="IScriptExtent" /> of element in error.</param> /// <param name="id">The ID to be shown in the <see cref="ParseError" />.</param> /// <param name="message">The message to be shown in the <see cref="ParseError" />.</param> internal static void ReportParseError( this IParseErrorWriter writer, IScriptExtent extent, string id = nameof(ErrorStrings.CompileTimeParseError), string message = "") { if (string.IsNullOrWhiteSpace(message)) { message = ErrorStrings.CompileTimeParseError; } writer.ReportParseError(extent, id, message); } /// <summary> /// Generate a <see cref="ParseError" />. /// </summary> /// <param name="writer">The <see cref="IParseErrorWriter" /> that should issue the report.</param> /// <param name="extent">The <see cref="IScriptExtent" /> of element in error.</param> /// <param name="exception"> /// The exception housing the message to be shown in the <see cref="ParseError" />. /// </param> /// <param name="id">The ID to be shown in the <see cref="ParseError" />.</param> internal static void ReportParseError( this IParseErrorWriter writer, IScriptExtent extent, Exception exception, string id = "") { if (string.IsNullOrEmpty(id)) { id = exception.GetType().Name; } writer.ReportParseError( extent, id, exception.Message); } /// <summary> /// Generate a <see cref="ParseError" />. /// </summary> /// <param name="writer">The <see cref="IParseErrorWriter" /> that should issue the report.</param> /// <param name="extent">The <see cref="IScriptExtent" /> of element in error.</param> internal static void ReportNonConstantTypeAs( this IParseErrorWriter writer, IScriptExtent extent) { writer.ReportNotSupported( extent, nameof(ErrorStrings.NonConstantTypeAs), ErrorStrings.NonConstantTypeAs); } } } <file_sep>/src/PSLambda/DelegateSyntaxVisitor.cs using System; using System.Collections.Generic; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides the ability to reshape a <see cref="ScriptBlockAst" /> when it fits /// the custom syntax for anonymous method expressions. /// </summary> internal class DelegateSyntaxVisitor : ICustomAstVisitor { private readonly IParseErrorWriter _errorWriter; private readonly List<Tuple<ITypeName, VariableExpressionAst>> _variables = new List<Tuple<ITypeName, VariableExpressionAst>>(); private IScriptExtent _paramBlockExtent; private bool _failed; /// <summary> /// Initializes a new instance of the <see cref="DelegateSyntaxVisitor" /> class. /// </summary> /// <param name="errorWriter">The <see cref="IParseErrorWriter" /> to report errors to.</param> internal DelegateSyntaxVisitor(IParseErrorWriter errorWriter) { _errorWriter = errorWriter; } #pragma warning disable SA1600 public object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { return scriptBlockExpressionAst.ScriptBlock.Visit(this); } public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { if (scriptBlockAst.ParamBlock != null) { return scriptBlockAst; } if (scriptBlockAst.BeginBlock != null) { _errorWriter.ReportNotSupported( scriptBlockAst.BeginBlock.Extent, nameof(CompilerStrings.BeginBlock), CompilerStrings.BeginBlock); return null; } if (scriptBlockAst.ProcessBlock != null) { _errorWriter.ReportNotSupported( scriptBlockAst.ProcessBlock.Extent, nameof(CompilerStrings.ProcessBlock), CompilerStrings.ProcessBlock); return null; } if (scriptBlockAst.EndBlock == null) { _errorWriter.ReportMissing( scriptBlockAst.Extent, nameof(CompilerStrings.EndBlock), CompilerStrings.EndBlock); return null; } var body = scriptBlockAst.EndBlock.Visit(this); if (_failed) { return scriptBlockAst; } _errorWriter.ThrowIfAnyErrors(); var parameters = new ParameterAst[_variables.Count]; for (var i = 0; i < parameters.Length; i++) { parameters[i] = new ParameterAst( _variables[i].Item2.Extent, (VariableExpressionAst)_variables[i].Item2.Copy(), new[] { new TypeConstraintAst(_variables[i].Item1.Extent, _variables[i].Item1) }, null); } var paramBlock = new ParamBlockAst( _paramBlockExtent, Array.Empty<AttributeAst>(), parameters); return new ScriptBlockAst( scriptBlockAst.Extent, paramBlock, null, null, (NamedBlockAst)((Ast)body).Copy(), null); } public object VisitNamedBlock(NamedBlockAst namedBlockAst) { if (namedBlockAst.Statements == null || namedBlockAst.Statements.Count == 0) { _errorWriter.ReportMissing( namedBlockAst.Extent, nameof(CompilerStrings.EndBlock), CompilerStrings.EndBlock); return null; } if (namedBlockAst.Statements.Count > 1) { _failed = true; return null; } var body = namedBlockAst.Statements[0].Visit(this); if (body == null) { _failed = true; return null; } return body; } public object VisitPipeline(PipelineAst pipelineAst) { return pipelineAst.PipelineElements[0].Visit(this); } public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { _paramBlockExtent = assignmentStatementAst.Left.Extent; DelegateParameterVisitor.AddVariables( assignmentStatementAst.Left, _variables); if (!(assignmentStatementAst.Right is PipelineAst pipeline)) { return null; } if (!(pipeline.PipelineElements[0] is CommandAst commandAst) || commandAst.GetCommandName() != Strings.DelegateSyntaxCommandName || commandAst.CommandElements.Count != 2) { return null; } if (commandAst.CommandElements[1] is ScriptBlockExpressionAst sbAst) { return sbAst.ScriptBlock.EndBlock; } var expression = commandAst.CommandElements[1] as ExpressionAst; var statements = new StatementAst[] { new CommandExpressionAst( expression.Extent, (ExpressionAst)expression.Copy(), Array.Empty<RedirectionAst>()), }; var statementBlockAst = new StatementBlockAst( commandAst.CommandElements[1].Extent, statements, Array.Empty<TrapStatementAst>()); return new NamedBlockAst( commandAst.CommandElements[1].Extent, TokenKind.End, statementBlockAst, unnamed: true); } #pragma warning restore SA1600 private class DelegateParameterVisitor : AstVisitor { private static readonly ITypeName s_objectTypeName = new TypeName( Empty.Extent, typeof(object).FullName); private List<Tuple<ITypeName, VariableExpressionAst>> _variables = new List<Tuple<ITypeName, VariableExpressionAst>>(); private DelegateParameterVisitor() { } public static void AddVariables( ExpressionAst expression, List<Tuple<ITypeName, VariableExpressionAst>> variables) { var visitor = new DelegateParameterVisitor { _variables = variables, }; expression.Visit(visitor); } public override AstVisitAction VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { if (convertExpressionAst.Child is VariableExpressionAst variable) { _variables.Add( Tuple.Create( convertExpressionAst.Attribute.TypeName, variable)); return AstVisitAction.SkipChildren; } return AstVisitAction.StopVisit; } public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) { _variables.Add( Tuple.Create( s_objectTypeName, variableExpressionAst)); return AstVisitAction.SkipChildren; } } #pragma warning disable SA1600, SA1201, SA1516 public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) => null; public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) => null; public object VisitAttribute(AttributeAst attributeAst) => null; public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) => null; public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) => null; public object VisitBlockStatement(BlockStatementAst blockStatementAst) => null; public object VisitBreakStatement(BreakStatementAst breakStatementAst) => null; public object VisitCatchClause(CatchClauseAst catchClauseAst) => null; public object VisitCommand(CommandAst commandAst) => null; public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) => null; public object VisitCommandParameter(CommandParameterAst commandParameterAst) => null; public object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) => null; public object VisitContinueStatement(ContinueStatementAst continueStatementAst) => null; public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) => null; public object VisitDataStatement(DataStatementAst dataStatementAst) => null; public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) => null; public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) => null; public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) => null; public object VisitErrorStatement(ErrorStatementAst errorStatementAst) => null; public object VisitExitStatement(ExitStatementAst exitStatementAst) => null; public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) => null; public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) => null; public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) => null; public object VisitForStatement(ForStatementAst forStatementAst) => null; public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) => null; public object VisitHashtable(HashtableAst hashtableAst) => null; public object VisitIfStatement(IfStatementAst ifStmtAst) => null; public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) => null; public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) => null; public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) => null; public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) => null; public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) => null; public object VisitParamBlock(ParamBlockAst paramBlockAst) => null; public object VisitParameter(ParameterAst parameterAst) => null; public object VisitParenExpression(ParenExpressionAst parenExpressionAst) => null; public object VisitReturnStatement(ReturnStatementAst returnStatementAst) => null; public object VisitStatementBlock(StatementBlockAst statementBlockAst) => null; public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => null; public object VisitSubExpression(SubExpressionAst subExpressionAst) => null; public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) => null; public object VisitThrowStatement(ThrowStatementAst throwStatementAst) => null; public object VisitTrap(TrapStatementAst trapStatementAst) => null; public object VisitTryStatement(TryStatementAst tryStatementAst) => null; public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) => null; public object VisitTypeExpression(TypeExpressionAst typeExpressionAst) => null; public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) => null; public object VisitUsingExpression(UsingExpressionAst usingExpressionAst) => null; public object VisitVariableExpression(VariableExpressionAst variableExpressionAst) => null; public object VisitWhileStatement(WhileStatementAst whileStatementAst) => null; #pragma warning restore SA1600, SA1201, SA1516 } } <file_sep>/src/PSLambda/DelegateTypeConverter.cs using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides conversion from <see cref="PSDelegate" /> to any <see cref="Delegate" /> type. /// </summary> public class DelegateTypeConverter : PSTypeConverter { private static readonly Dictionary<PSDelegate, Dictionary<Type, Delegate>> s_delegateCache = new Dictionary<PSDelegate, Dictionary<Type, Delegate>>(); private static readonly object s_syncObject = new object(); /// <summary> /// Determines if a object can be converted to a specific type. /// </summary> /// <param name="sourceValue">The value to convert.</param> /// <param name="destinationType">The type to conver to.</param> /// <returns>A value indicating whether the object can be converted.</returns> public override bool CanConvertFrom(object sourceValue, Type destinationType) { return sourceValue is PSDelegate && typeof(Delegate).IsAssignableFrom(destinationType); } /// <summary> /// Determines if a object can be converted to a specific type. /// </summary> /// <param name="sourceValue">The value to convert.</param> /// <param name="destinationType">The type to conver to.</param> /// <returns>A value indicating whether the object can be converted.</returns> public override bool CanConvertTo(object sourceValue, Type destinationType) { return sourceValue is PSDelegate && typeof(Delegate).IsAssignableFrom(destinationType); } /// <summary> /// Converts a <see cref="PSDelegate" /> object to a <see cref="Delegate" /> type. /// </summary> /// <param name="sourceValue">The <see cref="PSDelegate" /> to convert.</param> /// <param name="destinationType"> /// The type inheriting from <see cref="Delegate" /> to convert to. /// </param> /// <param name="formatProvider">The parameter is not used.</param> /// <param name="ignoreCase">The parameter is not used.</param> /// <returns>The converted <see cref="Delegate" /> object.</returns> public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { return ConvertToDelegate((PSDelegate)sourceValue, destinationType); } /// <summary> /// Converts a <see cref="PSDelegate" /> object to a <see cref="Delegate" /> type. /// </summary> /// <param name="sourceValue">The <see cref="PSDelegate" /> to convert.</param> /// <param name="destinationType"> /// The type inheriting from <see cref="Delegate" /> to convert to. /// </param> /// <param name="formatProvider">The parameter is not used.</param> /// <param name="ignoreCase">The parameter is not used.</param> /// <returns>The converted <see cref="Delegate" /> object.</returns> public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { return ConvertToDelegate((PSDelegate)sourceValue, destinationType); } private Delegate ConvertToDelegate(PSDelegate psDelegate, Type destinationType) { lock (s_syncObject) { if (!s_delegateCache.TryGetValue(psDelegate, out Dictionary<Type, Delegate> cacheEntry)) { cacheEntry = new Dictionary<Type, Delegate>(); s_delegateCache.Add(psDelegate, cacheEntry); } if (!cacheEntry.TryGetValue(destinationType, out Delegate compiledDelegate)) { compiledDelegate = CompileVisitor.CompileAst( psDelegate.EngineIntrinsics, (ScriptBlockAst)psDelegate.ScriptBlock.Ast, psDelegate.Locals.Values.ToArray(), destinationType); cacheEntry.Add(destinationType, compiledDelegate); } return compiledDelegate; } } } } <file_sep>/src/PSLambda/MemberBinder.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Management.Automation; using System.Management.Automation.Language; using System.Reflection; using System.Runtime.CompilerServices; namespace PSLambda { /// <summary> /// Provides member binding for method invocation expressions. /// </summary> internal class MemberBinder { private static readonly PSVariable[] s_emptyVariables = new PSVariable[0]; private static readonly ParameterAst[] s_emptyParameterAsts = new ParameterAst[0]; private readonly BindingFlags _instanceFlags; private readonly BindingFlags _staticFlags; private readonly string[] _namespaces; private MethodInfo[] _extensionMethods; /// <summary> /// Initializes a new instance of the <see cref="MemberBinder" /> class. /// </summary> /// <param name="accessFlags"> /// The <see cref="BindingFlags" /> to use while resolving members. Only pass /// access modifiers (e.g. <see cref="BindingFlags.Public" /> or /// <see cref="BindingFlags.NonPublic" />.</param> /// <param name="namespaces">The namespaces to resolve extension methods in.</param> public MemberBinder(BindingFlags accessFlags, string[] namespaces) { _instanceFlags = accessFlags | BindingFlags.IgnoreCase | BindingFlags.Instance; _staticFlags = accessFlags | BindingFlags.IgnoreCase | BindingFlags.Static; _namespaces = new string[namespaces.Length]; namespaces.CopyTo(_namespaces, 0); } /// <summary> /// Determines the correct member for an expression and creates a /// <see cref="Expression" /> representing it's invocation. /// </summary> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the bind.</param> /// <param name="instance">The instance <see cref="Expression" /> for the invocation.</param> /// <param name="name">The member name to use while resolving the method.</param> /// <param name="arguments">The arguments to use while resolving the method.</param> /// <param name="genericArguments">The generic arguments to use while resolving the method.</param> /// <returns> /// A <see cref="BindingResult" /> that either contains the /// <see cref="Expression" /> or the <see cref="ArgumentException" /> and /// error ID. /// </returns> internal BindingResult BindMethod( CompileVisitor visitor, Expression instance, string name, Ast[] arguments, Type[] genericArguments) { return BindMethod( visitor, instance.Type, name, arguments, instance, genericArguments); } /// <summary> /// Determines the correct member for an expression and creates a /// <see cref="Expression" /> representing it's invocation. /// </summary> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the bind.</param> /// <param name="sourceType">The source <see cref="Type" /> for the invocation.</param> /// <param name="name">The member name to use while resolving the method.</param> /// <param name="arguments">The arguments to use while resolving the method.</param> /// <param name="genericArguments">The generic arguments to use while resolving the method.</param> /// <returns> /// A <see cref="BindingResult" /> that either contains the /// <see cref="Expression" /> or the <see cref="ArgumentException" /> and /// error ID. /// </returns> internal BindingResult BindMethod( CompileVisitor visitor, Type sourceType, string name, Ast[] arguments, Type[] genericArguments) { return BindMethod( visitor, sourceType, name, arguments, null, genericArguments); } private BindingResult BindMethod( CompileVisitor visitor, Type sourceType, string name, Ast[] arguments, Expression instance, Type[] genericArguments) { var methodArgs = new MethodArgument[arguments.Length]; for (var i = 0; i < methodArgs.Length; i++) { methodArgs[i] = (MethodArgument)arguments[i]; } var didFindName = false; var isInstance = instance != null; var methods = sourceType.GetMethods(isInstance ? _instanceFlags : _staticFlags); MethodInfo boundMethod; BindingResult bindingResult = default; for (var i = 0; i < methods.Length; i++) { if (!methods[i].Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) { continue; } if (!didFindName) { didFindName = true; } if (genericArguments.Length > 0 && (!methods[i].IsGenericMethod || !AreGenericArgumentsValid(methods[i], genericArguments))) { continue; } if (genericArguments.Length > 0) { methods[i] = methods[i].MakeGenericMethod(genericArguments); } if (ShouldBind(methods[i], methodArgs, visitor, out boundMethod)) { var expressions = new Expression[methodArgs.Length]; for (var j = 0; j < methodArgs.Length; j++) { expressions[j] = methodArgs[j].Expression; } bindingResult.Expression = Expression.Call(instance, boundMethod, expressions); return bindingResult; } } if (!isInstance) { bindingResult.Reason = new ArgumentException( string.Format( CultureInfo.CurrentCulture, ErrorStrings.NoMemberArgumentMatch, sourceType.FullName, name)); bindingResult.Id = nameof(ErrorStrings.NoMemberArgumentMatch); return bindingResult; } var extensionArgs = new MethodArgument[methodArgs.Length + 1]; extensionArgs[0] = (MethodArgument)instance; for (var i = 1; i < extensionArgs.Length; i++) { extensionArgs[i] = methodArgs[i - 1]; } methods = GetExtensionMethods(); for (var i = 0; i < methods.Length; i++) { if (!methods[i].Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) { continue; } if (!didFindName) { didFindName = true; } if (genericArguments.Length > 0 && (!methods[i].IsGenericMethod || !AreGenericArgumentsValid(methods[i], genericArguments))) { continue; } if (genericArguments.Length > 0) { methods[i] = methods[i].MakeGenericMethod(genericArguments); } if (ShouldBind(methods[i], extensionArgs, visitor, out boundMethod)) { var expressions = new Expression[extensionArgs.Length]; for (var j = 0; j < extensionArgs.Length; j++) { expressions[j] = extensionArgs[j].Expression; } bindingResult.Expression = Expression.Call(boundMethod, expressions); return bindingResult; } } if (!didFindName) { bindingResult.Reason = new ArgumentException( string.Format( CultureInfo.CurrentCulture, ErrorStrings.NoMemberNameMatch, sourceType.FullName, name)); bindingResult.Id = nameof(ErrorStrings.NoMemberNameMatch); return bindingResult; } bindingResult.Reason = new ArgumentException( string.Format( CultureInfo.CurrentCulture, ErrorStrings.NoMemberArgumentMatch, sourceType.FullName, name)); bindingResult.Id = nameof(ErrorStrings.NoMemberArgumentMatch); return bindingResult; } private MethodInfo[] GetExtensionMethods() { if (_extensionMethods != null) { return _extensionMethods; } var extensionMethods = new List<MethodInfo>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var module in assembly.GetModules()) { foreach (var type in module.GetTypes()) { if (string.IsNullOrEmpty(type.Namespace)) { continue; } if (!_namespaces.Any(ns => ns.Equals(type.Namespace, StringComparison.InvariantCultureIgnoreCase))) { continue; } foreach (var method in type.GetMethods(_staticFlags)) { if (method.IsDefined(typeof(ExtensionAttribute), inherit: false)) { extensionMethods.Add(method); } } } } } _extensionMethods = extensionMethods.ToArray(); return _extensionMethods; } private bool AreGenericArgumentsValid(MethodInfo method, Type[] genericArguments) { var genericParameters = method.GetGenericArguments(); if (genericParameters.Length != genericArguments.Length) { return false; } for (var i = 0; i < genericParameters.Length; i++) { var constraints = genericParameters[i].GetGenericParameterConstraints(); for (var j = 0; j < constraints.Length; j++) { if (!constraints[j].IsAssignableFrom(genericParameters[i])) { return false; } } } return true; } private bool ShouldBind( MethodInfo method, MethodArgument[] arguments, CompileVisitor visitor, out MethodInfo resolvedMethod) { var parameters = method.GetParameters(); if (parameters.Length != arguments.Length) { resolvedMethod = null; return false; } BindingStatus status; status._map = new Dictionary<Type, Type>(); status._hasGenericParams = method.IsGenericMethod; for (var i = 0; i < parameters.Length; i++) { if (arguments[i].Ast != null && (arguments[i].Ast is ScriptBlockExpressionAst || arguments[i].Ast is ScriptBlockAst)) { if (!(typeof(Delegate).IsAssignableFrom(parameters[i].ParameterType) || typeof(LambdaExpression).IsAssignableFrom(parameters[i].ParameterType))) { resolvedMethod = null; return false; } if (status.IsDelegateMatch(parameters[i].ParameterType, arguments[i], visitor)) { continue; } resolvedMethod = null; return false; } if (arguments[i].Expression == null) { arguments[i].Expression = arguments[i].Ast.Compile(visitor); } if (!status.IsTypeMatch(parameters[i].ParameterType, arguments[i].Expression.Type)) { resolvedMethod = null; return false; } } if (!status._hasGenericParams || !method.IsGenericMethodDefinition) { resolvedMethod = method; return true; } var genericParameters = method.GetGenericArguments(); var genericArguments = new Type[genericParameters.Length]; for (var i = 0; i < genericParameters.Length; i++) { genericArguments[i] = status._map[genericParameters[i]]; } resolvedMethod = method.MakeGenericMethod(genericArguments); return true; } /// <summary> /// Represents the result of a method binding attempt. /// </summary> internal struct BindingResult { /// <summary> /// The generated <see cref="Expression" />. Can be <see langkeyword="null" /> /// if the binding attempt was unsuccessful. /// </summary> internal Expression Expression; /// <summary> /// The <see cref="Exception" /> that describes the binding failure. Can be /// <see langkeyword="null" /> if the binding was successful. /// </summary> internal Exception Reason; /// <summary> /// The ID that should be attached to the <see cref="ParseException" />. Can /// be <see langkeyword="null" /> if the binding attempt was successful. /// </summary> internal string Id; } private struct BindingStatus { internal Dictionary<Type, Type> _map; internal bool _hasGenericParams; internal bool IsTypeMatch(Type parameterType, Type argumentType) { if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); } if (parameterType.IsAssignableFrom(argumentType)) { return true; } if (!_hasGenericParams) { return false; } if (argumentType.IsArray && parameterType.IsGenericType && parameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { argumentType = typeof(IEnumerable<>).MakeGenericType( argumentType.GetElementType()); } if (parameterType.IsPointer != argumentType.IsPointer) { return false; } if (parameterType.HasElementType && parameterType.HasElementType) { parameterType = parameterType.GetElementType(); argumentType = argumentType.GetElementType(); } if (parameterType.IsGenericType && parameterType.IsGenericType) { var parameterGenerics = parameterType.GetGenericArguments(); var argumentGenerics = argumentType.GetGenericArguments(); if (parameterGenerics.Length != argumentGenerics.Length) { return false; } for (var i = 0; i < parameterGenerics.Length; i++) { if (!IsTypeMatch(parameterGenerics[i], argumentGenerics[i])) { return false; } } var constructedParameterType = parameterType .GetGenericTypeDefinition() .MakeGenericType(argumentGenerics); return constructedParameterType.IsAssignableFrom(argumentType); } if (!parameterType.IsGenericParameter) { return false; } if (_map.TryGetValue(parameterType, out Type existingResolvedType)) { return existingResolvedType.IsAssignableFrom(argumentType); } foreach (var constraint in parameterType.GetGenericParameterConstraints()) { if (!constraint.IsAssignableFrom(argumentType)) { return false; } } _map.Add(parameterType, argumentType); return true; } internal bool IsDelegateMatch(Type parameterType, MethodArgument argument, CompileVisitor visitor) { ScriptBlockAst sbAst; if (argument.Ast is ScriptBlockExpressionAst sbExpression) { sbAst = (ScriptBlockAst)sbExpression.ScriptBlock.Visit( new DelegateSyntaxVisitor(visitor.Errors)); } else { sbAst = (ScriptBlockAst)((ScriptBlockAst)argument.Ast).Visit( new DelegateSyntaxVisitor(visitor.Errors)); } argument.Ast = sbAst; var parameterMethod = parameterType.GetMethod(Strings.DelegateInvokeMethodName); if (parameterMethod == null && typeof(Expression).IsAssignableFrom(parameterType)) { parameterMethod = parameterType .GetGenericArguments()[0] .GetMethod(Strings.DelegateInvokeMethodName); } var astHasExplicitReturn = ExplicitReturnVisitor.TryFindExplicitReturn( sbAst, out PipelineBaseAst returnValue); if (astHasExplicitReturn) { if (parameterMethod.ReturnType == typeof(void) && returnValue != null) { return false; } } var parameterParameters = parameterMethod.GetParameters(); ParameterAst[] sbParameters; if (sbAst.ParamBlock != null) { sbParameters = new ParameterAst[sbAst.ParamBlock.Parameters.Count]; for (var i = 0; i < sbParameters.Length; i++) { sbParameters[i] = sbAst.ParamBlock.Parameters[i]; } } else { sbParameters = s_emptyParameterAsts; } if (parameterParameters.Length != sbParameters.Length) { return false; } var expectedParameterTypes = new Type[parameterParameters.Length]; for (var i = 0; i < parameterParameters.Length; i++) { if (parameterParameters[i].ParameterType.IsGenericParameter) { if (_map.TryGetValue(parameterParameters[i].ParameterType, out Type resolvedType)) { expectedParameterTypes[i] = resolvedType; continue; } // TODO: Check if parameter is strongly typed in the AST and use that to // resolve the targ. return false; } expectedParameterTypes[i] = parameterParameters[i].ParameterType; } var expectedReturnType = parameterMethod.ReturnType.IsGenericParameter ? null : parameterMethod.ReturnType; if (expectedReturnType == null) { _map.TryGetValue(parameterMethod.ReturnType, out expectedReturnType); } var oldErrorWriter = visitor.Errors; try { visitor.Errors = ParseErrorWriter.CreateNull(); argument.Expression = visitor.CompileAstImpl( sbAst, s_emptyVariables, expectedParameterTypes, expectedReturnType, null); } catch (Exception) { // TODO: Better reporting here if all method resolution fails. return false; } finally { visitor.Errors = oldErrorWriter; } if (parameterMethod.ReturnType.IsGenericParameter && !_map.ContainsKey(parameterMethod.ReturnType)) { _map.Add(parameterMethod.ReturnType, ((LambdaExpression)argument.Expression).ReturnType); } if (parameterType.IsGenericType) { var genericParameters = parameterType.GetGenericArguments(); var newGenericParameters = new Type[genericParameters.Length]; for (var i = 0; i < genericParameters.Length; i++) { if (genericParameters[i].IsGenericParameter) { _map.TryGetValue(genericParameters[i], out Type resolvedType); newGenericParameters[i] = resolvedType; continue; } newGenericParameters[i] = genericParameters[i]; } parameterType = parameterType .GetGenericTypeDefinition() .MakeGenericType(newGenericParameters); } argument.Expression = Expression.Lambda( parameterType, ((LambdaExpression)argument.Expression).Body, ((LambdaExpression)argument.Expression).Parameters); return true; } } private class MethodArgument { internal Ast Ast; internal Expression Expression; public static explicit operator Expression(MethodArgument argument) { return argument.Expression; } public static explicit operator MethodArgument(Ast ast) { var argument = new MethodArgument { Ast = ast }; return argument; } public static explicit operator MethodArgument(Expression expression) { var argument = new MethodArgument { Expression = expression }; return argument; } } private class ExplicitReturnVisitor : AstVisitor { private bool _wasFound; private PipelineBaseAst _returnPipeline; public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitReturnStatement(ReturnStatementAst returnStatementAst) { _wasFound = true; _returnPipeline = returnStatementAst.Pipeline; return AstVisitAction.StopVisit; } internal static bool TryFindExplicitReturn(Ast ast, out PipelineBaseAst returnValue) { var visitor = new ExplicitReturnVisitor(); ast.Visit(visitor); returnValue = visitor._returnPipeline; return visitor._wasFound; } } } } <file_sep>/src/PSLambda/VariableScopeStack.cs using System; using System.Linq; using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Represents the current set of variable scopes for a block <see cref="Expression" /> objects. /// </summary> internal class VariableScopeStack { private static readonly ParameterExpression[] s_emptyParameters = new ParameterExpression[0]; private VariableScope _current; /// <summary> /// Initializes a new instance of the <see cref="VariableScopeStack" /> class. /// </summary> internal VariableScopeStack() { _current = new VariableScope(s_emptyParameters); } /// <summary> /// Creates a new variable scope. /// </summary> /// <returns> /// A <see cref="IDisposable" /> handle that will return to the previous scope when disposed. /// </returns> internal IDisposable NewScope() { _current = new VariableScope(_current); return new ScopeHandle(() => _current = _current?.Parent); } /// <summary> /// Creates a new variable scope. /// </summary> /// <param name="parameters">Parameters that should be available from the new scope.</param> /// <returns> /// A <see cref="IDisposable" /> handle that will return to the previous scope when disposed. /// </returns> internal IDisposable NewScope(ParameterExpression[] parameters) { var handle = NewScope(); var currentScope = _current; foreach (var parameter in parameters) { currentScope.Parameters.Add(parameter.Name, parameter); } return handle; } /// <summary> /// Creates a new variable expression without looking at previous scopes. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="type">The type of the variable.</param> /// <returns>The variable <see cref="Expression" />.</returns> internal ParameterExpression NewVariable(string name, Type type) { return _current.NewVariable(name, type); } /// <summary> /// Gets a variable <see cref="Expression" /> from the current or a parent scope. /// </summary> /// <param name="variableExpressionAst"> /// The <see cref="VariableExpressionAst" /> to obtain a variable <see cref="Expression" /> for. /// </param> /// <param name="alreadyDefined"> /// A value indicating whether the variable has already been defined. /// </param> /// <returns>The resolved variable <see cref="Expression" />.</returns> internal ParameterExpression GetVariable( VariableExpressionAst variableExpressionAst, out bool alreadyDefined) { return _current.GetOrCreateVariable(variableExpressionAst.VariablePath.UserPath, variableExpressionAst.StaticType, out alreadyDefined); } /// <summary> /// Gets a variable <see cref="Expression" /> from the current or a parent scope. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="type">The type of the variable.</param> /// <returns>The resolved variable <see cref="Expression" />.</returns> internal ParameterExpression GetVariable(string name, Type type) { return _current.GetOrCreateVariable(name, type); } /// <summary> /// Gets all variables declared in the current scope. /// </summary> /// <returns> /// The variable <see cref="Expression" /> objects declared in the current scope. /// </returns> internal ParameterExpression[] GetVariables() { return _current.Variables.Values.ToArray(); } /// <summary> /// Gets all parameters declared in the current scope. /// </summary> /// <returns> /// The parameter <see cref="Expression" /> objects declared in the current scope. /// </returns> internal ParameterExpression[] GetParameters() { return _current.Parameters.Values.ToArray(); } /// <summary> /// Gets the automatic variable <c>$_</c> or <c>$PSItem</c> from the /// current scope, or closest parent scope where it is defined. /// </summary> /// <param name="dollarUnder"> /// The parameter expression referencing dollar under if defined; /// otherwise <see langword="null" />. /// </param> /// <returns> /// <see langword="true" /> if a defined dollar under variable was /// found; otherwise <see langword="false" />. /// </returns> internal bool TryGetDollarUnder(out ParameterExpression dollarUnder) { dollarUnder = GetDollarUnder(); return dollarUnder != null; } /// <summary> /// Gets the automatic variable <c>$_</c> or <c>$PSItem</c> from the /// current scope, or closest parent scope where it is defined. /// </summary> /// <returns> /// The parameter expression referencing dollar under if defined; /// otherwise <see langword="null" />. /// </returns> internal ParameterExpression GetDollarUnder() => _current.GetDollarUnder(); /// <summary> /// Sets the automatic variable <c>$_</c> or <c>$PSItem</c> in the current /// scope. If the variable exists in a parent scope and the type is the same, /// then the parent variable will be used. If the variable exists in a parent /// scope but the type is not the same, the variable will be renamed behind /// the scenes. /// </summary> /// <param name="type"> /// The static type that dollar under should contain. /// </param> /// <returns> /// The parameter expression referencing dollar under. /// </returns> internal ParameterExpression SetDollarUnder(Type type) => _current.SetDollarUnder(type); } } <file_sep>/src/PSLambda/CompileVisitor.cs using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Management.Automation; using System.Management.Automation.Language; using System.Reflection; using PSLambda.Commands; using static System.Linq.Expressions.Expression; using static PSLambda.ExpressionUtils; namespace PSLambda { /// <summary> /// Provides the ability to compile a PowerShell <see cref="Ast" /> object into a /// Linq <see cref="Expression" /> tree. /// </summary> internal class CompileVisitor : ICustomAstVisitor, ICustomAstVisitor2 { private static readonly HashSet<string> s_defaultNamespaces = new HashSet<string>() { "System.Linq", }; private static readonly CommandService s_commands = new CommandService(); private static readonly Dictionary<PSVariable, Expression> s_wrapperCache = new Dictionary<PSVariable, Expression>(); private static readonly ParameterExpression[] s_emptyParameters = new ParameterExpression[0]; private static readonly PSVariable[] s_emptyVariables = new PSVariable[0]; private static readonly ParameterModifier[] s_emptyModifiers = new ParameterModifier[0]; private readonly ConstantExpression _engine; private readonly LabelScopeStack _returns = new LabelScopeStack(); private readonly LoopScopeStack _loops = new LoopScopeStack(); private readonly VariableScopeStack _scopeStack = new VariableScopeStack(); private readonly Dictionary<string, PSVariable> _locals = new Dictionary<string, PSVariable>(); private MemberBinder _binder; private Dictionary<string, PSVariable> _allScopes; private CompileVisitor(EngineIntrinsics engine) { _engine = Constant(engine, typeof(EngineIntrinsics)); Errors = ParseErrorWriter.CreateDefault(); } /// <summary> /// Gets or sets the <see cref="Errors" /> we should report errors to. /// </summary> internal IParseErrorWriter Errors { get; set; } #pragma warning disable SA1600 public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) { var elements = arrayExpressionAst.SubExpression.Statements.CompileAll(this); if (elements.Length > 1) { if (elements.GroupBy(e => e.Type).Count() == 1) { return NewArrayInit(elements[0].Type, elements); } return NewArrayInit( typeof(object), elements); } if (elements.Length == 1 && elements[0].Type.IsArray) { return elements[0]; } if (elements.Length == 0) { return NewArrayInit( typeof(object), elements); } return NewArrayInit( elements[0].Type, elements); } public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { var elements = arrayLiteralAst.Elements.CompileAll(this); if (elements.GroupBy(e => e.Type).Count() == 1) { return NewArrayInit(elements[0].Type, elements); } return NewArrayInit(typeof(object), elements); } public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { try { if (assignmentStatementAst.Right is CommandExpressionAst expression && expression.Expression is VariableExpressionAst rhsVariable && rhsVariable.VariablePath.UserPath.Equals( Strings.NullVariableName, StringComparison.OrdinalIgnoreCase)) { var lhs = assignmentStatementAst.Left.Compile(this); return Assign(lhs, Constant(null, lhs.Type)); } VariableExpressionAst variable = assignmentStatementAst.Left as VariableExpressionAst; Type targetType = null; if (variable == null && assignmentStatementAst.Left is ConvertExpressionAst convert) { variable = convert.Child as VariableExpressionAst; if (!TryResolveType(convert.Attribute, out targetType)) { return Empty(); } } if (variable == null) { return MakeAssignment( assignmentStatementAst.Left.Compile(this), assignmentStatementAst.Right.Compile(this), assignmentStatementAst.Operator, assignmentStatementAst.ErrorPosition); } if (_locals.ContainsKey(variable.VariablePath.UserPath) || SpecialVariables.AllScope.ContainsKey(variable.VariablePath.UserPath) || SpecialVariables.Constants.ContainsKey(variable.VariablePath.UserPath)) { return MakeAssignment( assignmentStatementAst.Left.Compile(this), assignmentStatementAst.Right.Compile(this), assignmentStatementAst.Operator, assignmentStatementAst.ErrorPosition); } if (targetType != null) { return MakeAssignment( _scopeStack.GetVariable(variable.VariablePath.UserPath, targetType), assignmentStatementAst.Right.Compile(this), assignmentStatementAst.Operator, assignmentStatementAst.ErrorPosition); } var rhs = assignmentStatementAst.Right.Compile(this); return MakeAssignment( _scopeStack.GetVariable(variable.VariablePath.UserPath, rhs.Type), rhs, assignmentStatementAst.Operator, assignmentStatementAst.ErrorPosition); } catch (ArgumentException e) { Errors.ReportParseError(assignmentStatementAst.Extent, e); return Empty(); } } public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { var lhs = binaryExpressionAst.Left.Compile(this); var rhs = binaryExpressionAst.Right.Compile(this); Type rhsTypeConstant = (rhs as ConstantExpression)?.Value as Type; switch (binaryExpressionAst.Operator) { case TokenKind.DotDot: return PSDotDot(lhs, rhs); case TokenKind.Format: return PSFormat(lhs, rhs); case TokenKind.Join: return PSJoin(lhs, rhs); case TokenKind.Ireplace: return PSReplace(lhs, rhs, false); case TokenKind.Creplace: return PSReplace(lhs, rhs, true); case TokenKind.Isplit: return PSSplit(lhs, rhs, false); case TokenKind.Csplit: return PSSplit(lhs, rhs, true); case TokenKind.Iin: return PSIsIn(lhs, rhs, false); case TokenKind.Cin: return PSIsIn(lhs, rhs, true); case TokenKind.Inotin: return Not(PSIsIn(lhs, rhs, false)); case TokenKind.Cnotin: return Not(PSIsIn(lhs, rhs, true)); case TokenKind.Icontains: return PSIsIn(rhs, lhs, false); case TokenKind.Ccontains: return PSIsIn(rhs, lhs, true); case TokenKind.Inotcontains: return Not(PSIsIn(rhs, lhs, false)); case TokenKind.Cnotcontains: return Not(PSIsIn(rhs, lhs, true)); case TokenKind.Ige: return Or(PSGreaterThan(lhs, rhs, false), PSEquals(lhs, rhs, false)); case TokenKind.Cge: return Or(PSGreaterThan(lhs, rhs, true), PSEquals(lhs, rhs, true)); case TokenKind.Ile: return Or(PSLessThan(lhs, rhs, false), PSEquals(lhs, rhs, false)); case TokenKind.Cle: return Or(PSLessThan(lhs, rhs, true), PSEquals(lhs, rhs, true)); case TokenKind.Igt: return PSGreaterThan(lhs, rhs, false); case TokenKind.Cgt: return PSGreaterThan(lhs, rhs, true); case TokenKind.Ilt: return PSLessThan(lhs, rhs, false); case TokenKind.Clt: return PSLessThan(lhs, rhs, true); case TokenKind.Ilike: return PSLike(lhs, rhs, isCaseSensitive: false); case TokenKind.Clike: return PSLike(lhs, rhs, isCaseSensitive: true); case TokenKind.Inotlike: return Not(PSLike(lhs, rhs, isCaseSensitive: false)); case TokenKind.Cnotlike: return Not(PSLike(lhs, rhs, isCaseSensitive: true)); case TokenKind.Imatch: return PSMatch(lhs, rhs, isCaseSensitive: false); case TokenKind.Cmatch: return PSMatch(lhs, rhs, isCaseSensitive: true); case TokenKind.Inotmatch: return Not(PSMatch(lhs, rhs, isCaseSensitive: false)); case TokenKind.Cnotmatch: return Not(PSMatch(lhs, rhs, isCaseSensitive: true)); case TokenKind.Ieq: return PSEquals(lhs, rhs, isCaseSensitive: false); case TokenKind.Ceq: return PSEquals(lhs, rhs, isCaseSensitive: true); case TokenKind.Ine: return Not(PSEquals(lhs, rhs, isCaseSensitive: false)); case TokenKind.Cne: return Not(PSEquals(lhs, rhs, isCaseSensitive: true)); case TokenKind.And: return AndAlso(PSIsTrue(lhs), PSIsTrue(rhs)); case TokenKind.Or: return OrElse(PSIsTrue(lhs), PSIsTrue(rhs)); case TokenKind.Band: return PSBitwiseOperation(ExpressionType.And, lhs, rhs); case TokenKind.Bor: return PSBitwiseOperation(ExpressionType.Or, lhs, rhs); case TokenKind.Is: if (rhsTypeConstant == null) { Errors.ReportNonConstantTypeAs(binaryExpressionAst.Right.Extent); return Empty(); } return TypeIs(lhs, rhsTypeConstant); case TokenKind.IsNot: if (rhsTypeConstant == null) { Errors.ReportNonConstantTypeAs(binaryExpressionAst.Right.Extent); return Empty(); } return Not(TypeIs(lhs, rhsTypeConstant)); case TokenKind.As: if (rhsTypeConstant == null) { Errors.ReportNonConstantTypeAs(binaryExpressionAst.Right.Extent); return Empty(); } return PSTypeAs(lhs, rhsTypeConstant); case TokenKind.Plus: return MakeBinary(ExpressionType.Add, lhs, rhs); case TokenKind.Minus: return MakeBinary(ExpressionType.Subtract, lhs, rhs); case TokenKind.Divide: return MakeBinary(ExpressionType.Divide, lhs, rhs); case TokenKind.Multiply: return MakeBinary(ExpressionType.Multiply, lhs, rhs); case TokenKind.Rem: return MakeBinary(ExpressionType.Modulo, lhs, rhs); default: Errors.ReportNotSupported( binaryExpressionAst.ErrorPosition, binaryExpressionAst.Operator.ToString(), binaryExpressionAst.Operator.ToString()); return Empty(); } } public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return blockStatementAst.Body.Visit(this); } public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return _loops.Break != null ? Break(_loops.Break) : Return(_returns.GetOrCreateReturnLabel(typeof(void))); } public object VisitCatchClause(CatchClauseAst catchClauseAst) { static Type GetExceptionType(CatchClauseAst ast) { if (ast.IsCatchAll || ast.CatchTypes.Count > 1) { return typeof(Exception); } return ast.CatchTypes.First().TypeName.GetReflectionType() ?? typeof(Exception); } Type catchType = GetExceptionType(catchClauseAst); using (_scopeStack.NewScope()) { ParameterExpression dollarUnder = _scopeStack.SetDollarUnder(catchType); Expression catchBody = catchClauseAst.Body.Compile(this); if (catchBody.Type != typeof(void)) { catchBody = Block(typeof(void), catchBody); } return Catch(dollarUnder, catchBody); } } public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { if (commandExpressionAst.Redirections.Count > 0) { commandExpressionAst.Redirections.CompileAll(this); return Empty(); } return commandExpressionAst.Expression.Visit(this); } public object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) { return Constant( constantExpressionAst.SafeGetValue(), constantExpressionAst.StaticType); } public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return Continue(_loops?.Continue); } public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { if (!TryResolveType(convertExpressionAst.Attribute, out Type resolvedType)) { return Empty(); } if (convertExpressionAst.Child is VariableExpressionAst variableExpression && convertExpressionAst.Parent is AssignmentStatementAst assignment && assignment.Left == convertExpressionAst) { return _scopeStack.GetVariable( variableExpression.VariablePath.UserPath, resolvedType); } return PSConvertTo( convertExpressionAst.Child.Compile(this), resolvedType); } public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return NewBlock(() => { using (_loops.NewScope()) { var body = doUntilStatementAst.Body.Compile(this); return new[] { body, Loop( IfThenElse( Not(PSIsTrue(doUntilStatementAst.Condition.Compile(this))), body, Break(_loops.Break)), _loops.Break, _loops.Continue), }; } }); } public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return NewBlock(() => { using (_loops.NewScope()) { var body = doWhileStatementAst.Body.Compile(this); return new[] { body, Loop( IfThenElse( PSIsTrue(doWhileStatementAst.Condition.Compile(this)), body, Break(_loops.Break)), _loops.Break, _loops.Continue), }; } }); } public object VisitExitStatement(ExitStatementAst exitStatementAst) { if (exitStatementAst.Pipeline == null) { return Throw(New(ReflectionCache.ExitException_Ctor)); } return Throw( New( ReflectionCache.ExitException_Ctor_Object, Convert(exitStatementAst.Pipeline.Compile(this), typeof(object)))); } public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { using (_loops.NewScope()) { var condition = forEachStatementAst.Condition.Compile(this); var canEnumerate = TryGetEnumeratorMethod( condition.Type, out MethodInfo getEnumeratorMethod, out MethodInfo getCurrentMethod); if (!canEnumerate) { Errors.ReportParseError( forEachStatementAst.Condition.Extent, nameof(ErrorStrings.ForEachInvalidEnumerable), string.Format( CultureInfo.CurrentCulture, ErrorStrings.ForEachInvalidEnumerable, condition.Type)); Errors.ThrowIfAnyErrors(); return Empty(); } using (_scopeStack.NewScope()) { var enumeratorRef = _scopeStack.GetVariable( Strings.ForEachVariableName, getEnumeratorMethod.ReturnType); try { return Block( _scopeStack.GetVariables(), Assign(enumeratorRef, Call(condition, getEnumeratorMethod)), Loop( IfThenElse( test: Call(enumeratorRef, ReflectionCache.IEnumerator_MoveNext), ifTrue: NewBlock( () => new[] { Assign( _scopeStack.GetVariable( forEachStatementAst.Variable.VariablePath.UserPath, getCurrentMethod.ReturnType), Call(enumeratorRef, getCurrentMethod)), forEachStatementAst.Body.Compile(this), }), ifFalse: Break(_loops.Break)), _loops.Break, _loops.Continue)); } catch (ArgumentException e) { Errors.ReportParseError(forEachStatementAst.Extent, e); return Empty(); } } } } public object VisitForStatement(ForStatementAst forStatementAst) { return NewBlock( () => { using (_loops.NewScope()) { return new[] { forStatementAst.Initializer.Compile(this), Loop( IfThenElse( forStatementAst.Condition.Compile(this), NewBlock(() => new[] { forStatementAst.Body.Compile(this), forStatementAst.Iterator?.Compile(this) ?? Empty(), }), Break(_loops.Break)), _loops.Break, _loops.Continue), }; } }); } public object VisitHashtable(HashtableAst hashtableAst) { if (hashtableAst.KeyValuePairs.Count == 0) { return New( ReflectionCache.Hashtable_Ctor, Constant(0), Property(null, ReflectionCache.StringComparer_CurrentCultureIgnoreCase)); } var elements = new ElementInit[hashtableAst.KeyValuePairs.Count]; for (var i = 0; i < elements.Length; i++) { elements[i] = ElementInit( ReflectionCache.Hashtable_Add, Convert(hashtableAst.KeyValuePairs[i].Item1.Compile(this), typeof(object)), Convert(hashtableAst.KeyValuePairs[i].Item2.Compile(this), typeof(object))); } return ListInit( New( ReflectionCache.Hashtable_Ctor, Constant(hashtableAst.KeyValuePairs.Count, typeof(int)), Property(null, ReflectionCache.StringComparer_CurrentCultureIgnoreCase)), elements); } public object VisitIfStatement(IfStatementAst ifStmtAst) { return HandleRemainingClauses(ifStmtAst); } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) { var source = indexExpressionAst.Target.Compile(this); if (source.Type.IsArray) { return ArrayIndex( source, indexExpressionAst.Index.Compile(this)); } var defaultMember = source.Type.GetCustomAttribute<DefaultMemberAttribute>(inherit: true); if (defaultMember == null) { Errors.ReportParseError( indexExpressionAst.Extent, nameof(ErrorStrings.UnknownIndexer), string.Format( CultureInfo.CurrentCulture, ErrorStrings.UnknownIndexer, source.Type.FullName)); return Empty(); } var index = indexExpressionAst.Index.Compile(this); var indexerProperty = source.Type .GetProperty(defaultMember.MemberName, new[] { index.Type }); if (indexerProperty == null) { Errors.ReportParseError( indexExpressionAst.Extent, nameof(ErrorStrings.UnknownIndexer), string.Format( CultureInfo.CurrentCulture, ErrorStrings.UnknownIndexer, source.Type.FullName)); return Empty(); } return Property( source, indexerProperty, index); } public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return CompileInvokeMemberExpression(invokeMemberExpressionAst); } public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) { if (!TryResolveConstant(memberExpressionAst.Member, out string memberName)) { return Empty(); } if (memberExpressionAst.Static) { if (!TryResolveType(memberExpressionAst.Expression, out Type resolvedType)) { return Empty(); } var resolvedMember = resolvedType .FindMembers( MemberTypes.Property | MemberTypes.Field, BindingFlags.Public | BindingFlags.Static, Type.FilterNameIgnoreCase, memberName) .OrderBy(m => m.MemberType == MemberTypes.Property) .FirstOrDefault(); if (resolvedMember == null) { Errors.ReportParseError( memberExpressionAst.Extent, nameof(ErrorStrings.MissingMember), string.Format( CultureInfo.CurrentCulture, ErrorStrings.MissingMember, memberName, resolvedType.FullName)); return Empty(); } if (resolvedMember is FieldInfo field) { return Field(null, field); } return Property(null, (PropertyInfo)resolvedMember); } try { return PropertyOrField( memberExpressionAst.Expression.Compile(this), memberName); } catch (ArgumentException e) { Errors.ReportParseError(memberExpressionAst.Extent, e, nameof(ErrorStrings.MissingMember)); return Empty(); } } public object VisitNamedBlock(NamedBlockAst namedBlockAst) { if (namedBlockAst.Statements.Count < 1) { return Empty(); } return NewBlock(() => namedBlockAst.Statements.CompileAll(this)); } public object VisitParamBlock(ParamBlockAst paramBlockAst) { foreach (var parameter in paramBlockAst.Parameters) { parameter.Visit(this); } return Empty(); } public object VisitParameter(ParameterAst parameterAst) { return Parameter( GetParameterType(parameterAst), parameterAst.Name.VariablePath.UserPath); } public object VisitParenExpression(ParenExpressionAst parenExpressionAst) { return parenExpressionAst.Pipeline.Visit(this); } public object VisitPipeline(PipelineAst pipelineAst) { if (pipelineAst.PipelineElements.Count > 1) { Errors.ReportNotSupported( pipelineAst.Extent, nameof(ErrorStrings.Pipeline), ErrorStrings.Pipeline); return Empty(); } if (pipelineAst.PipelineElements.Count == 0) { return Empty(); } return pipelineAst.PipelineElements[0].Visit(this); } public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { if (returnStatementAst.Pipeline == null) { try { return Return(_returns.GetOrCreateReturnLabel(typeof(void))); } catch (ArgumentException e) { Errors.ReportParseError(returnStatementAst.Extent, e); return Empty(); } } Expression pipeline = returnStatementAst.Pipeline.Compile(this); try { return Return( _returns.GetOrCreateReturnLabel(pipeline.Type), pipeline); } catch (ArgumentException e) { Errors.ReportParseError(returnStatementAst.Extent, e); return Empty(); } } public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { if (scriptBlockAst.Parent is ScriptBlockExpressionAst sbExpression && sbExpression.Parent is ConvertExpressionAst convert && TryResolveType(convert.Attribute, out Type resolvedType)) { return CompileAstImpl(scriptBlockAst, s_emptyVariables, resolvedType); } return CompileAstImpl(scriptBlockAst, s_emptyVariables); } public object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { return scriptBlockExpressionAst.ScriptBlock.Visit(this); } public object VisitStatementBlock(StatementBlockAst statementBlockAst) { if (statementBlockAst.Statements.Count == 0) { return Empty(); } using (_scopeStack.NewScope()) { var stmts = new Expression[statementBlockAst.Statements.Count]; for (var i = 0; i < stmts.Length; i++) { stmts[i] = statementBlockAst.Statements[i].Compile(this); } try { return Block(_scopeStack.GetVariables(), stmts); } catch (ArgumentException e) { Errors.ReportParseError(statementBlockAst.Extent, e); return Empty(); } } } public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { return Constant(stringConstantExpressionAst.SafeGetValue(), typeof(string)); } public object VisitSubExpression(SubExpressionAst subExpressionAst) { return subExpressionAst.SubExpression.Visit(this); } public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return NewBlock(() => { using (_loops.NewScope()) { if (switchStatementAst.Clauses.Count == 0) { return new[] { switchStatementAst.Default.Compile(this), Label(_loops.Break), }; } var clauses = new SwitchCase[switchStatementAst.Clauses.Count]; for (var i = 0; i < clauses.Length; i++) { clauses[i] = SwitchCase( NewBlock( () => switchStatementAst.Clauses[i].Item2.Compile(this), typeof(void)), switchStatementAst.Clauses[i].Item1.Compile(this)); } Expression defaultBlock = null; if (switchStatementAst.Default != null) { defaultBlock = NewBlock( () => switchStatementAst.Default.Compile(this), typeof(void)); } return new Expression[] { Switch( switchStatementAst.Condition.Compile(this), defaultBlock, ReflectionCache.ExpressionUtils_PSEqualsIgnoreCase, clauses), Label(_loops.Break), }; } }); } public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { if (throwStatementAst.IsRethrow) { return Rethrow(); } if (throwStatementAst.Pipeline == null) { return Throw( New( ReflectionCache.RuntimeException_Ctor, Constant(CompilerStrings.DefaultThrowMessage))); } var pipeline = throwStatementAst.Pipeline.Compile(this); if (typeof(Exception).IsAssignableFrom(pipeline.Type)) { return Throw(pipeline); } return Throw( New( ReflectionCache.RuntimeException_Ctor, PSConvertTo<string>(pipeline))); } public object VisitTryStatement(TryStatementAst tryStatementAst) { if (tryStatementAst.Finally != null && tryStatementAst.CatchClauses.Any()) { return TryCatchFinally( NewBlock(() => tryStatementAst.Body.Compile(this), typeof(void)), NewBlock(() => tryStatementAst.Finally.Compile(this), typeof(void)), tryStatementAst.CatchClauses .Select(ctch => ctch.Visit(this)) .Cast<CatchBlock>() .ToArray()); } if (tryStatementAst.Finally == null) { return TryCatch( NewBlock(() => tryStatementAst.Body.Compile(this), typeof(void)), tryStatementAst.CatchClauses .Select(ctch => ctch.Visit(this)) .Cast<CatchBlock>() .ToArray()); } return TryFinally( NewBlock(() => tryStatementAst.Body.Compile(this), typeof(void)), NewBlock(() => tryStatementAst.Finally.Compile(this), typeof(void))); } public object VisitTypeExpression(TypeExpressionAst typeExpressionAst) { if (TryResolveType(typeExpressionAst, out Type type)) { return Constant(type, typeof(Type)); } return Empty(); } public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { var child = unaryExpressionAst.Child.Compile(this); switch (unaryExpressionAst.TokenKind) { case TokenKind.PostfixPlusPlus: return Assign(child, Increment(child)); case TokenKind.PostfixMinusMinus: return Assign(child, Decrement(child)); case TokenKind.Not: return Not(PSIsTrue(child)); default: Errors.ReportNotSupported( unaryExpressionAst.Extent, unaryExpressionAst.TokenKind.ToString(), unaryExpressionAst.TokenKind.ToString()); return Empty(); } } public object VisitWhileStatement(WhileStatementAst whileStatementAst) { using (_loops.NewScope()) { return Loop( IfThenElse( PSIsTrue(whileStatementAst.Condition.Compile(this)), whileStatementAst.Body.Compile(this), Break(_loops.Break)), _loops.Break, _loops.Continue); } } public object VisitVariableExpression(VariableExpressionAst variableExpressionAst) { bool isDollarUnder = VariableUtils.IsDollarUnder(variableExpressionAst); if (isDollarUnder && _scopeStack.TryGetDollarUnder(out ParameterExpression dollarUnder)) { return dollarUnder; } if (SpecialVariables.Constants.TryGetValue(variableExpressionAst.VariablePath.UserPath, out Expression expression)) { return expression; } if (_locals.TryGetValue(variableExpressionAst.VariablePath.UserPath, out PSVariable local)) { return GetExpressionForLocal(local); } if (!SpecialVariables.AllScope.ContainsKey(variableExpressionAst.VariablePath.UserPath)) { bool alreadyDefined = false; try { if (!isDollarUnder) { return _scopeStack.GetVariable(variableExpressionAst, out alreadyDefined); } } finally { if (!alreadyDefined && !(variableExpressionAst.Parent is AssignmentStatementAst || (variableExpressionAst.Parent is ConvertExpressionAst && variableExpressionAst.Parent.Parent is AssignmentStatementAst))) { Errors.ReportParseError( variableExpressionAst.Extent, nameof(ErrorStrings.InvalidVariableReference), string.Format( CultureInfo.CurrentCulture, ErrorStrings.InvalidVariableReference, variableExpressionAst.VariablePath.UserPath)); } } } return GetExpressionForAllScope(variableExpressionAst.VariablePath.UserPath); } public object VisitCommand(CommandAst commandAst) { if (commandAst.Redirections.Count > 0) { commandAst.Redirections.CompileAll(this); return Empty(); } if (s_commands.TryProcessAst(commandAst, this, out Expression expression)) { return expression; } Errors.ReportNotSupportedAstType(commandAst); return Empty(); } public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { var sb = new System.Text.StringBuilder(expandableStringExpressionAst.Value); var formatExpressions = new Expression[expandableStringExpressionAst.NestedExpressions.Count]; var reversed = expandableStringExpressionAst.NestedExpressions.Reverse().ToArray(); for (var i = 0; i < reversed.Length; i++) { var startOffset = reversed[i].Extent.StartOffset - expandableStringExpressionAst.Extent.StartOffset - 1; sb.Remove( startOffset, reversed[i].Extent.Text.Length) .Insert( startOffset, string.Format( CultureInfo.InvariantCulture, "{{{0}}}", i)); formatExpressions[i] = PSConvertTo<string>(reversed[i].Compile(this)); } return PSFormat( Constant(sb.ToString()), NewArrayInit(typeof(object), formatExpressions)); } public object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { Errors.ReportNotSupportedAstType(typeDefinitionAst); return Empty(); } public object VisitPropertyMember(PropertyMemberAst propertyMemberAst) { Errors.ReportNotSupportedAstType(propertyMemberAst); return Empty(); } public object VisitFunctionMember(FunctionMemberAst functionMemberAst) { Errors.ReportNotSupportedAstType(functionMemberAst); return Empty(); } public object VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) { Errors.ReportNotSupportedAstType(baseCtorInvokeMemberExpressionAst); return Empty(); } public object VisitUsingStatement(UsingStatementAst usingStatement) { Errors.ReportNotSupportedAstType(usingStatement); return Empty(); } public object VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) { Errors.ReportNotSupportedAstType(configurationDefinitionAst); return Empty(); } public object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) { Errors.ReportNotSupportedAstType(dynamicKeywordAst); return Empty(); } public object VisitCommandParameter(CommandParameterAst commandParameterAst) { Errors.ReportNotSupportedAstType(commandParameterAst); return Empty(); } public object VisitDataStatement(DataStatementAst dataStatementAst) { Errors.ReportNotSupportedAstType(dataStatementAst); return Empty(); } public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { Errors.ReportNotSupportedAstType(errorExpressionAst); return Empty(); } public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { Errors.ReportNotSupportedAstType(errorStatementAst); return Empty(); } public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { Errors.ReportNotSupportedAstType(fileRedirectionAst); return Empty(); } public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { Errors.ReportNotSupportedAstType(functionDefinitionAst); return Empty(); } public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { Errors.ReportNotSupportedAstType(mergingRedirectionAst); return Empty(); } public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { Errors.ReportNotSupportedAstType(namedAttributeArgumentAst); return Empty(); } public object VisitTrap(TrapStatementAst trapStatementAst) { Errors.ReportNotSupportedAstType(trapStatementAst); return Empty(); } public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { Errors.ReportNotSupportedAstType(typeConstraintAst); return Empty(); } public object VisitUsingExpression(UsingExpressionAst usingExpressionAst) { Errors.ReportNotSupportedAstType(usingExpressionAst); return Empty(); } public object VisitAttribute(AttributeAst attributeAst) { Errors.ReportNotSupportedAstType(attributeAst); return Empty(); } public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { Errors.ReportNotSupportedAstType(attributedExpressionAst); return Empty(); } #pragma warning restore SA1600 /// <summary> /// Compiles a <see cref="Ast" /> into a <see cref="Delegate" />. /// </summary> /// <param name="engine">The <see cref="EngineIntrinsics" /> for the current runspace.</param> /// <param name="sbAst">The <see cref="ScriptBlockAst" /> to compile.</param> /// <param name="localVariables"> /// Any <see cref="PSVariable" /> objects that should be accessible from the delegate and /// are not AllScope or Constant. /// </param> /// <param name="delegateType">A type that inherits <see cref="Delegate" />.</param> /// <returns>The compiled <see cref="Delegate" />.</returns> internal static Delegate CompileAst( EngineIntrinsics engine, ScriptBlockAst sbAst, PSVariable[] localVariables, Type delegateType) { var visitor = new CompileVisitor(engine); return visitor.CompileAstImpl(sbAst, localVariables, delegateType).Compile(); } /// <summary> /// Compiles a <see cref="Ast" /> into a <see cref="Delegate" />. /// </summary> /// <param name="engine">The <see cref="EngineIntrinsics" /> for the current runspace.</param> /// <param name="sbAst">The <see cref="ScriptBlockAst" /> to compile.</param> /// <param name="localVariables"> /// Any <see cref="PSVariable" /> objects that should be accessible from the delegate and /// are not AllScope or Constant. /// </param> /// <returns>The compiled <see cref="Delegate" />.</returns> internal static Delegate CompileAst( EngineIntrinsics engine, ScriptBlockAst sbAst, PSVariable[] localVariables) { var visitor = new CompileVisitor(engine); return visitor.CompileAstImpl(sbAst, localVariables).Compile(); } /// <summary> /// Compile an <see cref="InvokeMemberExpressionAst" />. /// </summary> /// <param name="invokeMemberExpressionAst">The AST to interpret.</param> /// <returns>The generated <see cref="Expression" />.</returns> internal Expression CompileInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return CompileInvokeMemberExpression(invokeMemberExpressionAst, Type.EmptyTypes); } /// <summary> /// Compile an <see cref="InvokeMemberExpressionAst" />. /// </summary> /// <param name="invokeMemberExpressionAst">The AST to interpret.</param> /// <param name="genericArguments"> /// The generic type arguments to use while resolving the method. /// </param> /// <returns>The generated <see cref="Expression" />.</returns> internal Expression CompileInvokeMemberExpression( InvokeMemberExpressionAst invokeMemberExpressionAst, Type[] genericArguments) { Ast[] arguments; if (genericArguments.Length < 1 && TryGetGenericArgumentDeclaration(invokeMemberExpressionAst, ref genericArguments)) { arguments = new Ast[invokeMemberExpressionAst.Arguments.Count - 1]; for (var i = 0; i < arguments.Length; i++) { arguments[i] = invokeMemberExpressionAst.Arguments[i + 1]; } } else { arguments = invokeMemberExpressionAst?.Arguments?.ToArray() ?? new Ast[0]; } if (!TryResolveConstant(invokeMemberExpressionAst.Member, out string memberName)) { return Empty(); } if (invokeMemberExpressionAst.Static) { if (!TryResolveType(invokeMemberExpressionAst.Expression, out Type resolvedType)) { return Empty(); } if (memberName.Equals(Strings.ConstructorMemberName, StringComparison.Ordinal)) { var expressions = arguments.CompileAll(this); return New(GetBestConstructor(resolvedType, expressions), expressions); } try { var result = GetBinder(invokeMemberExpressionAst) .BindMethod( this, resolvedType, memberName, arguments, genericArguments); if (result.Expression != null) { return result.Expression; } Errors.ReportParseError( invokeMemberExpressionAst.Member.Extent, result.Reason, result.Id); return Empty(); } catch (InvalidOperationException e) { Errors.ReportParseError(invokeMemberExpressionAst.Extent, e, nameof(ErrorStrings.MissingMember)); return Empty(); } } try { var instance = invokeMemberExpressionAst.Expression.Compile(this); var result = GetBinder(invokeMemberExpressionAst) .BindMethod( this, instance, memberName, arguments, genericArguments); if (result.Expression != null) { return result.Expression; } Errors.ReportParseError( invokeMemberExpressionAst.Member.Extent, result.Reason, result.Id); return Empty(); } catch (InvalidOperationException e) { Errors.ReportParseError(invokeMemberExpressionAst.Extent, e, nameof(ErrorStrings.MissingMember)); return Empty(); } } /// <summary> /// Create a new block under a new variable scope. /// </summary> /// <param name="expressionFactory">A function that generates the body of the block.</param> /// <returns>An <see cref="Expression" /> representing the block.</returns> internal Expression NewBlock(Func<Expression> expressionFactory) { using (_scopeStack.NewScope()) { var expressions = expressionFactory(); return Block(_scopeStack.GetVariables(), expressions); } } /// <summary> /// Create a new block under a new variable scope. /// </summary> /// <param name="expressionFactory">A function that generates the body of the block.</param> /// <returns>An <see cref="Expression" /> representing the block.</returns> internal Expression NewBlock(Func<IEnumerable<Expression>> expressionFactory) { using (_scopeStack.NewScope()) { var expressions = expressionFactory(); return Block(_scopeStack.GetVariables(), expressions); } } /// <summary> /// Create a new block under a new variable scope. /// </summary> /// <param name="expressionFactory">A function that generates the body of the block.</param> /// <param name="blockReturnType">The expected return type for the block.</param> /// <returns>An <see cref="Expression" /> representing the block.</returns> internal Expression NewBlock(Func<Expression> expressionFactory, Type blockReturnType) { using (_scopeStack.NewScope()) { Expression[] expressions; if (blockReturnType == typeof(void)) { expressions = new[] { expressionFactory(), Empty() }; } else { expressions = new[] { expressionFactory() }; } if (blockReturnType == null) { return Block(_scopeStack.GetVariables(), expressions); } return Block(blockReturnType, _scopeStack.GetVariables(), expressions); } } /// <summary> /// Attempt to resolve a type constant from an <see cref="Ast" />. If unable, then generate /// a <see cref="ParseError" />. /// </summary> /// <param name="ast"> /// The <see cref="Ast" /> that is expected to hold a type literal expression. /// </param> /// <param name="resolvedType">The <see cref="Type" /> if resolution was successful.</param> /// <returns><c>true</c> if resolution was successful, otherwise <c>false</c>.</returns> internal bool TryResolveType(Ast ast, out Type resolvedType) { if (ast == null) { resolvedType = null; Errors.ReportParseError( ast.Extent, nameof(ErrorStrings.MissingType), ErrorStrings.MissingType); return false; } if (ast is TypeExpressionAst typeExpression) { return TryResolveType(typeExpression.TypeName, out resolvedType); } if (ast is TypeConstraintAst typeConstraint) { return TryResolveType(typeConstraint.TypeName, out resolvedType); } resolvedType = null; Errors.ReportParseError( ast.Extent, nameof(ErrorStrings.MissingType), ErrorStrings.MissingType); return false; } /// <summary> /// Compiles a <see cref="Ast" /> into a <see cref="LambdaExpression" />. /// </summary> /// <param name="scriptBlockAst">The <see cref="ScriptBlockAst" /> to compile.</param> /// <param name="localVariables"> /// Any <see cref="PSVariable" /> objects that should be accessible from the delegate and /// are not AllScope or Constant. /// </param> /// <param name="delegateType"> /// The type inheriting from <see cref="Delegate" /> that the /// <see cref="LambdaExpression" /> is expected to be. /// </param> /// <returns>The interpreted <see cref="LambdaExpression" />.</returns> internal LambdaExpression CompileAstImpl( ScriptBlockAst scriptBlockAst, PSVariable[] localVariables, Type delegateType) { if (delegateType != null) { var delegateMethod = delegateType.GetMethod("Invoke"); var parameters = delegateMethod.GetParameters(); var parameterTypes = new Type[parameters.Length]; for (var i = 0; i < parameterTypes.Length; i++) { parameterTypes[i] = parameters[i].ParameterType; } return CompileAstImpl( scriptBlockAst, localVariables, parameterTypes, delegateMethod.ReturnType, delegateType); } return CompileAstImpl( scriptBlockAst, localVariables, null, null, null); } /// <summary> /// Compiles a <see cref="Ast" /> into a <see cref="LambdaExpression" />. /// </summary> /// <param name="scriptBlockAst">The <see cref="ScriptBlockAst" /> to compile.</param> /// <param name="localVariables"> /// Any <see cref="PSVariable" /> objects that should be accessible from the delegate and /// are not AllScope or Constant. /// </param> /// <param name="expectedParameterTypes">The parameter types to expect.</param> /// <param name="expectedReturnType">The return type to expect.</param> /// <param name="delegateType"> /// The type inheriting from <see cref="Delegate" /> that the /// <see cref="LambdaExpression" /> is expected to be. /// </param> /// <returns>The interpreted <see cref="LambdaExpression" />.</returns> internal LambdaExpression CompileAstImpl( ScriptBlockAst scriptBlockAst, PSVariable[] localVariables, Type[] expectedParameterTypes, Type expectedReturnType, Type delegateType) { foreach (var local in localVariables) { _locals.Add(local.Name, local); } scriptBlockAst = ConvertToDelegateAst(scriptBlockAst); var lambda = CreateLambda( scriptBlockAst, () => { using (_scopeStack.NewScope()) { var returnsHandle = expectedReturnType == null ? _returns.NewScope() : _returns.NewScope(expectedReturnType); using (returnsHandle) { var requireExplicitReturn = scriptBlockAst.EndBlock.Statements.Count != 1 || !(scriptBlockAst.EndBlock.Statements[0] is CommandBaseAst || scriptBlockAst.EndBlock.Statements[0] is PipelineAst); var body = scriptBlockAst.EndBlock.Compile(this); return Block( _scopeStack.GetVariables(), _returns.WithReturn(new[] { body }, requireExplicitReturn)); } } }, expectedParameterTypes, expectedReturnType, delegateType); Errors.ThrowIfAnyErrors(); return lambda; } private static bool FilterGenericInterfaceDefinition(Type m, object filterCriteria) { return m.IsGenericType && m.GetGenericTypeDefinition() == (Type)filterCriteria; } private ScriptBlockAst ConvertToDelegateAst(ScriptBlockAst scriptBlockAst) { return (ScriptBlockAst)scriptBlockAst.Visit( new DelegateSyntaxVisitor(Errors)); } private bool TryGetGenericArgumentDeclaration(InvokeMemberExpressionAst ast, ref Type[] arguments) { if (ast.Arguments == null || ast.Arguments.Count == 0) { return false; } if (!(ast.Arguments[0] is TypeExpressionAst typeExpression)) { return false; } if (!(typeExpression.TypeName is GenericTypeName genericTypeName)) { return false; } if (!genericTypeName.TypeName.Name.Equals("g", StringComparison.OrdinalIgnoreCase)) { return false; } arguments = new Type[genericTypeName.GenericArguments.Count]; for (var i = 0; i < arguments.Length; i++) { arguments[i] = genericTypeName.GenericArguments[i].GetReflectionType(); if (arguments[i] == null) { Errors.ReportParseError( genericTypeName.GenericArguments[i].Extent, nameof(ErrorStrings.TypeNotFound), string.Format( CultureInfo.CurrentCulture, ErrorStrings.TypeNotFound, genericTypeName.GenericArguments[i].FullName)); Errors.ThrowIfAnyErrors(); return false; } } return true; } private LambdaExpression CompileAstImpl( ScriptBlockAst scriptBlockAst, PSVariable[] localVariables) { return CompileAstImpl( scriptBlockAst, localVariables, null); } private Expression MakeAssignment( Expression lhs, Expression rhs, TokenKind operatorKind, IScriptExtent operationExtent) { try { switch (operatorKind) { case TokenKind.Equals: return Assign(lhs, rhs); case TokenKind.PlusEquals: return MakeBinary(ExpressionType.AddAssign, lhs, rhs); case TokenKind.MinusEquals: return MakeBinary(ExpressionType.SubtractAssign, lhs, rhs); case TokenKind.MultiplyEquals: return MakeBinary(ExpressionType.MultiplyAssign, lhs, rhs); case TokenKind.DivideEquals: return MakeBinary(ExpressionType.DivideAssign, lhs, rhs); case TokenKind.RemainderEquals: return MakeBinary(ExpressionType.ModuloAssign, lhs, rhs); } } catch (InvalidOperationException e) { Errors.ReportParseError(operationExtent, e); return Empty(); } Errors.ReportNotSupported( operationExtent, Strings.OperatorNotSupportedId, operatorKind.ToString()); return Empty(); } private Expression HandleRemainingClauses(IfStatementAst ifStmtAst, int clauseIndex = 0) { if (clauseIndex >= ifStmtAst.Clauses.Count) { if (ifStmtAst.ElseClause != null) { return ifStmtAst.ElseClause.Compile(this); } return Empty(); } return IfThenElse( PSIsTrue(ifStmtAst.Clauses[clauseIndex].Item1.Compile(this)), ifStmtAst.Clauses[clauseIndex].Item2.Compile(this), HandleRemainingClauses(ifStmtAst, clauseIndex + 1)); } private LambdaExpression CreateLambda( ScriptBlockAst scriptBlockAst, Func<Expression> blockFactory, Type[] expectedParameterTypes, Type expectedReturnType, Type delegateType) { if (!(delegateType != null || expectedParameterTypes != null || expectedReturnType != null)) { using (_scopeStack.NewScope(GetParameters(scriptBlockAst?.ParamBlock))) { return Lambda( blockFactory(), _scopeStack.GetParameters()); } } var scope = _scopeStack.NewScope( GetParameters( scriptBlockAst?.ParamBlock, expectedParameterTypes)); using (scope) { if (delegateType == null) { return Lambda( NewBlock( () => blockFactory(), expectedReturnType), _scopeStack.GetParameters()); } return Lambda( delegateType, NewBlock( () => blockFactory(), expectedReturnType), _scopeStack.GetParameters()); } } private ParameterExpression GetParameter(ParameterAst parameterAst, Type expectedType) { return Parameter( expectedType ?? GetParameterType(parameterAst), parameterAst.Name.VariablePath.UserPath); } private Type GetParameterType(ParameterAst parameter) { return parameter.Attributes .OfType<TypeConstraintAst>() .FirstOrDefault() ?.TypeName .GetReflectionType() ?? typeof(object); } private ConstructorInfo GetBestConstructor( Type type, Expression[] arguments) { return (ConstructorInfo)Type.DefaultBinder.SelectMethod( BindingFlags.Default, type.GetConstructors(), arguments.Select(a => a.Type).ToArray(), arguments.Length == 0 ? s_emptyModifiers : new[] { new ParameterModifier(arguments.Length) }); } private MethodInfo GetBestMethod( Type type, string name, Expression[] arguments) { return (MethodInfo)Type.DefaultBinder.SelectMethod( BindingFlags.Default, Array.ConvertAll( type.FindMembers(MemberTypes.Method, BindingFlags.Default, Type.FilterName, name), member => (MethodInfo)member), arguments.Select(a => a.Type).ToArray(), new[] { new ParameterModifier(arguments.Length) }); } private ParameterExpression[] GetParameters(ParamBlockAst ast) { if (ast?.Parameters == null || ast.Parameters.Count == 0) { return s_emptyParameters; } return ast.Parameters.Select(p => (ParameterExpression)p.Visit(this)).ToArray(); } private ParameterExpression[] GetParameters(ParamBlockAst ast, Type[] expectedParameterTypes) { if (ast == null || ast.Parameters.Count == 0) { return s_emptyParameters; } var parameters = new ParameterExpression[ast.Parameters.Count]; for (var i = 0; i < ast.Parameters.Count; i++) { parameters[i] = GetParameter(ast.Parameters[i], expectedParameterTypes[i]); } return parameters; } private Expression CreateWrappedVariableExpression(PSVariable variable, Type variableType) { return Property( Constant( typeof(PSVariableWrapper<>).MakeGenericType(variableType) .GetConstructor(new[] { typeof(PSVariable) }) .Invoke(new[] { variable })), Strings.PSVariableWrapperValuePropertyName); } private Expression GetExpressionForLocal(PSVariable variable) { if (s_wrapperCache.TryGetValue(variable, out Expression cachedExpression)) { return cachedExpression; } var expression = CreateWrappedVariableExpression(variable, GetTypeForVariable(variable)); s_wrapperCache.Add(variable, expression); return expression; } private Expression GetExpressionForAllScope(string name) { if (_allScopes == null) { using var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); _allScopes = pwsh .AddCommand("Microsoft.PowerShell.Utility\\Get-Variable") .AddParameter("Scope", "Global") .Invoke<PSVariable>() .Where(v => v.Options.HasFlag(ScopedItemOptions.AllScope)) .ToDictionary(v => v.Name, StringComparer.OrdinalIgnoreCase); } if (s_wrapperCache.TryGetValue(_allScopes[name], out Expression cachedExpression)) { return cachedExpression; } var expression = CreateWrappedVariableExpression( _allScopes[name], SpecialVariables.AllScope[name]); s_wrapperCache.Add(_allScopes[name], expression); return expression; } private Type GetTypeForVariable(PSVariable variable) { if (SpecialVariables.AllScope.TryGetValue(variable.Name, out Type variableType)) { return variableType; } var transAttribute = variable.Attributes.OfType<ArgumentTransformationAttribute>().FirstOrDefault(); if (transAttribute == null) { return GetTypeForVariableByValue(variable); } if (ReflectionCache.ArgumentTypeConverterAttribute == null || ReflectionCache.ArgumentTypeConverterAttribute_TargetType == null) { return GetTypeForVariableByValue(variable); } if (!ReflectionCache.ArgumentTypeConverterAttribute.IsAssignableFrom(transAttribute.GetType())) { return GetTypeForVariableByValue(variable); } return (Type)ReflectionCache.ArgumentTypeConverterAttribute_TargetType.GetValue(transAttribute); } private Type GetTypeForVariableByValue(PSVariable variable) { if (variable.Value == null) { return typeof(object); } return variable.Value.GetType(); } private bool TryResolveType(ITypeName typeName, out Type resolvedType) { resolvedType = typeName.GetReflectionType(); if (resolvedType != null) { return true; } Errors.ReportParseError( typeName.Extent, nameof(ErrorStrings.TypeNotFound), string.Format( CultureInfo.CurrentCulture, ErrorStrings.TypeNotFound, typeName.FullName)); return false; } private bool TryResolveConstant<TResult>(Ast ast, out TResult resolvedValue) { object rawValue; try { rawValue = ast.SafeGetValue(); } catch (InvalidOperationException) { Errors.ReportParseError( ast.Extent, nameof(ErrorStrings.UnexpectedExpression), ErrorStrings.UnexpectedExpression); resolvedValue = default; return false; } resolvedValue = (TResult)rawValue; return true; } private bool TryFindGenericInterface( Type implementation, Type genericDefinition, out Type resolvedInterface) { resolvedInterface = implementation .FindInterfaces(FilterGenericInterfaceDefinition, genericDefinition) .FirstOrDefault(); return resolvedInterface != null; } private MemberBinder GetBinder(Ast ast) { if (_binder != null) { return _binder; } while (ast.Parent != null) { ast = ast.Parent; } var namespaces = new HashSet<string>(s_defaultNamespaces); foreach (var ns in ((ScriptBlockAst)ast).UsingStatements) { if (ns.UsingStatementKind != UsingStatementKind.Namespace) { continue; } namespaces.Add(ns.Name.Value); } _binder = new MemberBinder(BindingFlags.Public, namespaces.ToArray()); return _binder; } private bool TryGetEnumeratorMethod( Type type, out MethodInfo getEnumeratorMethod, out MethodInfo getCurrentMethod) { var canFallbackToEnumerable = false; var canFallbackToIDictionary = false; var interfaces = type.GetInterfaces(); for (var i = 0; i < interfaces.Length; i++) { if (interfaces[i] == typeof(IEnumerable)) { canFallbackToEnumerable = true; continue; } if (interfaces[i] == typeof(IDictionary)) { canFallbackToIDictionary = true; continue; } if (interfaces[i].IsConstructedGenericType && interfaces[i].GetGenericTypeDefinition() == typeof(IEnumerable<>)) { getEnumeratorMethod = interfaces[i].GetMethod( Strings.GetEnumeratorMethodName, Type.EmptyTypes); getCurrentMethod = getEnumeratorMethod.ReturnType.GetMethod( Strings.EnumeratorGetCurrentMethodName, Type.EmptyTypes); return true; } } if (canFallbackToIDictionary) { getEnumeratorMethod = ReflectionCache.IDictionary_GetEnumerator; getCurrentMethod = ReflectionCache.IDictionaryEnumerator_get_Entry; return true; } if (canFallbackToEnumerable) { getEnumeratorMethod = ReflectionCache.IEnumerable_GetEnumerator; getCurrentMethod = ReflectionCache.IEnumerator_get_Current; return true; } getEnumeratorMethod = null; getCurrentMethod = null; return false; } } } <file_sep>/src/PSLambda/Commands/CommandService.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda.Commands { /// <summary> /// Provides management of custom command handlers. /// </summary> internal class CommandService { private readonly Dictionary<string, ICommandHandler> _commandRegistry = new Dictionary<string, ICommandHandler>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="CommandService" /> class. /// </summary> public CommandService() { RegisterCommand(new DefaultCommand()); RegisterCommand(new WithCommand()); RegisterCommand(new GenericCommand()); RegisterCommand(new LockCommand()); } /// <summary> /// Registers a command handler. /// </summary> /// <param name="handler">The handler to register.</param> public void RegisterCommand(ICommandHandler handler) { if (_commandRegistry.ContainsKey(handler.CommandName)) { return; } _commandRegistry.Add(handler.CommandName, handler); } /// <summary> /// Attempt to process a <see cref="CommandAst" /> as a custom command. /// </summary> /// <param name="commandAst">The <see cref="CommandAst" /> to process.</param> /// <param name="visitor"> /// The <see cref="CompileVisitor" /> requesting the expression. /// </param> /// <param name="expression"> /// The <see cref="Expression" /> result if a command handler was found. /// </param> /// <returns><c>true</c> if a commmand handler was matched, otherwise <c>false</c>.</returns> public bool TryProcessAst(CommandAst commandAst, CompileVisitor visitor, out Expression expression) { if (_commandRegistry.TryGetValue(commandAst.GetCommandName(), out ICommandHandler handler)) { expression = handler.ProcessAst(commandAst, visitor); return true; } expression = null; return false; } } } <file_sep>/src/PSLambda/ExpressionUtils.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Management.Automation; using System.Reflection; using System.Text.RegularExpressions; using static System.Linq.Expressions.Expression; namespace PSLambda { /// <summary> /// Provides utility methods for creating <see cref="Expression" /> objects for /// operations meant to mimic the PowerShell engine. /// </summary> internal static class ExpressionUtils { /// <summary> /// Creates an <see cref="Expression" /> representing a less than comparison operator in /// the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSLessThan(Expression lhs, Expression rhs, bool isCaseSensitive) { return Equal(PSCompare(lhs, rhs, isCaseSensitive), Constant(-1)); } /// <summary> /// Creates an <see cref="Expression" /> representing a greater than comparison operator in /// the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSGreaterThan(Expression lhs, Expression rhs, bool isCaseSensitive) { return Equal(PSCompare(lhs, rhs, isCaseSensitive), Constant(1)); } /// <summary> /// Creates an <see cref="Expression" /> representing a equals comparison operator in /// the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSEquals(Expression lhs, Expression rhs, bool isCaseSensitive) { return Equal(PSCompare(lhs, rhs, isCaseSensitive), Constant(0)); } /// <summary> /// Creates an <see cref="Expression" /> representing a comparison operator in /// the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSCompare(Expression lhs, Expression rhs, bool isCaseSensitive) { return Call( ReflectionCache.LanguagePrimitives_Compare, Convert(lhs, typeof(object)), Convert(rhs, typeof(object)), Constant(!isCaseSensitive, typeof(bool))); } /// <summary> /// Creates an <see cref="Expression" /> representing a match comparision operator in /// the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSMatch(Expression lhs, Expression rhs, bool isCaseSensitive) { return Call( ReflectionCache.Regex_IsMatch, PSConvertTo<string>(lhs), PSConvertTo<string>(rhs), Constant( isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase, typeof(RegexOptions))); } /// <summary> /// Creates an <see cref="Expression" /> representing a like comparision operator in /// the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSLike(Expression lhs, Expression rhs, bool isCaseSensitive) { return Call( New( ReflectionCache.WildcardPattern_Ctor, PSConvertTo<string>(rhs), Constant( isCaseSensitive ? WildcardOptions.None : WildcardOptions.IgnoreCase, typeof(WildcardOptions))), ReflectionCache.WildcardPattern_IsMatch, PSConvertTo<string>(lhs)); } /// <summary> /// Creates an <see cref="Expression" /> representing a conversion operation using the /// PowerShell engine. /// </summary> /// <param name="target">The <see cref="Expression" /> to convert.</param> /// <param name="targetType">The <see cref="Type" /> to convert to.</param> /// <returns>An <see cref="Expression" /> representing the conversion.</returns> public static Expression PSConvertTo(Expression target, Type targetType) { return Convert( Call( ReflectionCache.LanguagePrimitives_ConvertTo, Convert(target, typeof(object)), Constant(targetType, typeof(Type))), targetType); } /// <summary> /// Creates an <see cref="Expression" /> representing a conversion operation using the /// PowerShell engine. /// </summary> /// <param name="target">The <see cref="Expression" /> to convert.</param> /// <typeparam name="T">The <see cref="Type" /> to convert to.</typeparam> /// <returns>An <see cref="Expression" /> representing the conversion.</returns> public static Expression PSConvertTo<T>(Expression target) { return Call( ReflectionCache.LanguagePrimitives_ConvertToGeneric.MakeGenericMethod(new[] { typeof(T) }), Convert(target, typeof(object))); } /// <summary> /// Creates an <see cref="Expression" /> representing a conversion operation using the /// PowerShell engine. /// </summary> /// <param name="source"> /// The <see cref="Expression" /> representing multiple expressions that need to be converted. /// </param> /// <typeparam name="T">The <see cref="Type" /> to convert to.</typeparam> /// <returns>An <see cref="Expression" /> representing the conversion.</returns> public static Expression PSConvertAllTo<T>(Expression source) { var enumeratorVar = Variable(typeof(IEnumerator)); var collectionVar = Variable(typeof(List<T>)); var breakLabel = Label(); return Block( new[] { enumeratorVar, collectionVar }, Assign(collectionVar, New(typeof(List<T>))), Assign( enumeratorVar, Call( ReflectionCache.LanguagePrimitives_GetEnumerator, source)), Loop( IfThenElse( Call(enumeratorVar, ReflectionCache.IEnumerator_MoveNext), Call( collectionVar, Strings.AddMethodName, Type.EmptyTypes, PSConvertTo<T>(Call(enumeratorVar, ReflectionCache.IEnumerator_get_Current))), Break(breakLabel)), breakLabel), Call(collectionVar, Strings.ToArrayMethodName, Type.EmptyTypes)); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of an /// <see cref="Expression" /> as being <c>true</c> using the rules of the PowerShell engine. /// </summary> /// <param name="eval">The <see cref="Expression" /> to evaluate.</param> /// <returns>An <see cref="Expression" /> representing the evaluation.</returns> public static Expression PSIsTrue(Expression eval) { return Call( ReflectionCache.LanguagePrimitives_IsTrue, Convert(eval, typeof(object))); } /// <summary> /// Creates an <see cref="Expression" /> representing the conversion of a type using the /// "as" operator using the conversion rules of the PowerShell engine. /// </summary> /// <param name="eval">The <see cref="Expression" /> to convert.</param> /// <param name="expectedType">The <see cref="Type" /> to convert to.</param> /// <returns>An <see cref="Expression" /> representing the conversion.</returns> public static Expression PSTypeAs(Expression eval, Type expectedType) { var resultVar = Variable(expectedType); return Block( expectedType, new[] { resultVar }, Call( ReflectionCache.LangaugePrimitives_TryConvertToGeneric.MakeGenericMethod(expectedType), Convert(eval, typeof(object)), resultVar), resultVar); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of the "join" operator /// from the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSJoin(Expression lhs, Expression rhs) { return Call( ReflectionCache.String_Join, PSConvertTo<string>(rhs), PSConvertAllTo<string>(lhs)); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of the "replace" operator /// from the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSReplace(Expression lhs, Expression rhs, bool isCaseSensitive) { return Call( ReflectionCache.Regex_Replace, PSConvertTo<string>(lhs), PSConvertTo<string>(ArrayIndex(rhs, Constant(0))), PSConvertTo<string>(ArrayIndex(rhs, Constant(1))), Constant(isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase)); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of the "split" operator /// from the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSSplit(Expression lhs, Expression rhs, bool isCaseSensitive) { return Call( ReflectionCache.Regex_Split, PSConvertTo<string>(lhs), PSConvertTo<string>(rhs), Constant(isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase)); } /// <summary> /// Creates an <see cref="Expression" /> representing a in comparison operator in /// the PowerShell engine. /// </summary> /// <param name="item">The <see cref="Expression" /> on the left hand side.</param> /// <param name="items">The <see cref="Expression" /> on the right hand side.</param> /// <param name="isCaseSensitive"> /// A value indicating whether the operation should be case sensitive. /// </param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSIsIn(Expression item, Expression items, bool isCaseSensitive) { var returnLabel = Label(typeof(bool)); var enumeratorVar = Variable(typeof(IEnumerator)); return Block( new[] { enumeratorVar }, Assign( enumeratorVar, Call( ReflectionCache.LanguagePrimitives_GetEnumerator, items)), Loop( IfThenElse( Call(enumeratorVar, ReflectionCache.IEnumerator_MoveNext), IfThen( PSEquals( item, Call(enumeratorVar, ReflectionCache.IEnumerator_get_Current), isCaseSensitive), Return(returnLabel, SpecialVariables.Constants[Strings.TrueVariableName])), Return(returnLabel, SpecialVariables.Constants[Strings.FalseVariableName]))), Label(returnLabel, SpecialVariables.Constants[Strings.FalseVariableName])); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of the "format" operator /// from the PowerShell engine. /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSFormat(Expression lhs, Expression rhs) { if (rhs.NodeType == ExpressionType.NewArrayInit) { return Call( ReflectionCache.String_Format, Property(null, ReflectionCache.CultureInfo_CurrentCulture), PSConvertTo<string>(lhs), PSConvertAllTo<string>(rhs)); } return Call( ReflectionCache.String_Format, Property(null, ReflectionCache.CultureInfo_CurrentCulture), PSConvertTo<string>(lhs), NewArrayInit(typeof(object), PSConvertTo<string>(rhs))); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of the "DotDot" operator /// from the PowerShell engine (e.g. 0..100). /// </summary> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSDotDot(Expression lhs, Expression rhs) { return Call( ReflectionCache.ExpressionUtils_GetRange, PSConvertTo<int>(lhs), PSConvertTo<int>(rhs)); } /// <summary> /// Creates an <see cref="Expression" /> representing the evaluation of a bitwise comparision /// operator from the PowerShell engine. /// </summary> /// <param name="expressionType">The expression operator.</param> /// <param name="lhs">The <see cref="Expression" /> on the left hand side.</param> /// <param name="rhs">The <see cref="Expression" /> on the right hand side.</param> /// <returns>An <see cref="Expression" /> representing the operation.</returns> public static Expression PSBitwiseOperation( ExpressionType expressionType, Expression lhs, Expression rhs) { var resultType = lhs.Type; if (typeof(Enum).IsAssignableFrom(lhs.Type)) { lhs = Convert(lhs, Enum.GetUnderlyingType(lhs.Type)); } if (typeof(Enum).IsAssignableFrom(rhs.Type)) { rhs = Convert(rhs, Enum.GetUnderlyingType(rhs.Type)); } var resultExpression = MakeBinary(expressionType, lhs, rhs); if (resultType == resultExpression.Type) { return resultExpression; } return PSConvertTo(resultExpression, resultType); } private static bool PSEqualsIgnoreCase(object first, object second) { return LanguagePrimitives.Compare(first, second, ignoreCase: true) == 0; } private static int[] GetRange(int start, int end) { bool shouldReverse = false; if (start > end) { var tempStart = start; start = end; end = tempStart; shouldReverse = true; } var result = new int[end - start + 1]; for (var i = 0; i < result.Length; i++) { result[i] = i + start; } if (!shouldReverse) { return result; } for (var i = 0; i < result.Length / 2; i++) { var temp = result[i]; result[i] = result[result.Length - 1 - i]; result[result.Length - 1 - i] = temp; } return result; } } } <file_sep>/src/PSLambda/PSVariableWrapper.cs using System.Management.Automation; namespace PSLambda { /// <summary> /// Provides a strongly typed wrapper for <see cref="PSVariable" /> objects. /// </summary> /// <typeparam name="TValue">The type of object contained by the <see cref="PSVariable" />.</typeparam> internal class PSVariableWrapper<TValue> { private readonly object _syncObject = new object(); private readonly PSVariable _wrappedVariable; /// <summary> /// Initializes a new instance of the <see cref="PSVariableWrapper{TValue}" /> class. /// </summary> /// <param name="variable">The <see cref="PSVariable" /> to wrap.</param> public PSVariableWrapper(PSVariable variable) { _wrappedVariable = variable; } /// <summary> /// Gets or sets the value of the <see cref="PSVariable" /> object. /// </summary> public TValue Value { get { lock (_syncObject) { return LanguagePrimitives.ConvertTo<TValue>(_wrappedVariable.Value); } } set { lock (_syncObject) { _wrappedVariable.Value = value; } } } } } <file_sep>/src/PSLambda/ReflectionCache.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; using System.Text.RegularExpressions; namespace PSLambda { /// <summary> /// Provides cached objects for generating method and property invocation /// <see cref="System.Linq.Expressions.Expression" /> objects. /// </summary> internal static class ReflectionCache { /// <summary> /// Resolves to <see cref="LanguagePrimitives.GetEnumerator(object)" />. /// </summary> public static readonly MethodInfo LanguagePrimitives_GetEnumerator = typeof(LanguagePrimitives).GetMethod("GetEnumerator", new[] { typeof(object) }); /// <summary> /// Resolves to <see cref="LanguagePrimitives.IsTrue(object)" />. /// </summary> public static readonly MethodInfo LanguagePrimitives_IsTrue = typeof(LanguagePrimitives).GetMethod("IsTrue", new[] { typeof(object) }); /// <summary> /// Resolves to <see cref="LanguagePrimitives.Compare(object, object, bool)" />. /// </summary> public static readonly MethodInfo LanguagePrimitives_Compare = typeof(LanguagePrimitives).GetMethod("Compare", new[] { typeof(object), typeof(object), typeof(bool) }); /// <summary> /// Resolves to <see cref="LanguagePrimitives.ConvertTo{T}(object)" />. /// </summary> public static readonly MethodInfo LanguagePrimitives_ConvertToGeneric = typeof(LanguagePrimitives).GetMethod("ConvertTo", new[] { typeof(object) }); /// <summary> /// Resolves to <see cref="LanguagePrimitives.ConvertTo(object, Type)" />. /// </summary> public static readonly MethodInfo LanguagePrimitives_ConvertTo = typeof(LanguagePrimitives).GetMethod("ConvertTo", new[] { typeof(object), typeof(Type) }); /// <summary> /// Resolves to <see cref="LanguagePrimitives.TryConvertTo{T}(object, out T)" />. /// </summary> public static readonly MethodInfo LangaugePrimitives_TryConvertToGeneric = (MethodInfo)typeof(LanguagePrimitives).FindMembers( MemberTypes.Method, BindingFlags.Static | BindingFlags.Public, (m, filterCriteria) => { var method = m as MethodInfo; if (!method.IsGenericMethod) { return false; } var parameters = method.GetParameters(); return parameters.Length == 2 && parameters[0].ParameterType == typeof(object) && parameters[1].ParameterType.IsByRef; }, null) .FirstOrDefault(); /// <summary> /// Resolves to <see cref="WildcardPattern.WildcardPattern(string, WildcardOptions)" />. /// </summary> public static readonly ConstructorInfo WildcardPattern_Ctor = typeof(WildcardPattern).GetConstructor(new[] { typeof(string), typeof(WildcardOptions) }); /// <summary> /// Resolves to <see cref="Regex.IsMatch(string, string, RegexOptions)" />. /// </summary> public static readonly MethodInfo Regex_IsMatch = typeof(Regex).GetMethod("IsMatch", new[] { typeof(string), typeof(string), typeof(RegexOptions) }); /// <summary> /// Resolves to <see cref="Regex.Replace(string, string, string, RegexOptions)" />. /// </summary> public static readonly MethodInfo Regex_Replace = typeof(Regex).GetMethod("Replace", new[] { typeof(string), typeof(string), typeof(string), typeof(RegexOptions) }); /// <summary> /// Resolves to <see cref="Regex.Split(string, string, RegexOptions)" />. /// </summary> public static readonly MethodInfo Regex_Split = typeof(Regex).GetMethod("Split", new[] { typeof(string), typeof(string), typeof(RegexOptions) }); /// <summary> /// Resolves to <see cref="WildcardPattern.IsMatch(string)" />. /// </summary> public static readonly MethodInfo WildcardPattern_IsMatch = typeof(WildcardPattern).GetMethod("IsMatch", new[] { typeof(string) }); /// <summary> /// Resolves to <see cref="IEnumerator.MoveNext" />. /// </summary> public static readonly MethodInfo IEnumerator_MoveNext = typeof(IEnumerator).GetMethod("MoveNext"); /// <summary> /// Resolves to <see cref="string.Join(string, string[])" />. /// </summary> public static readonly MethodInfo String_Join = typeof(string).GetMethod("Join", new[] { typeof(string), typeof(string[]) }); /// <summary> /// Resolves to <see cref="string.Format(IFormatProvider, string, object[])" />. /// </summary> public static readonly MethodInfo String_Format = typeof(string).GetMethod("Format", new[] { typeof(IFormatProvider), typeof(string), typeof(object[]) }); /// <summary> /// Resolves to <see cref="System.Globalization.CultureInfo.CurrentCulture" />. /// </summary> public static readonly PropertyInfo CultureInfo_CurrentCulture = typeof(System.Globalization.CultureInfo).GetProperty("CurrentCulture"); /// <summary> /// Resolves to the non-public type System.Management.Automation.ArgumentTypeConverterAttribute. /// </summary> public static readonly Type ArgumentTypeConverterAttribute = typeof(PSObject).Assembly.GetType("System.Management.Automation.ArgumentTypeConverterAttribute"); /// <summary> /// Resolves to the non-public property System.Management.Automation.ArgumentTypeConverterAttribute.TargetType. /// </summary> public static readonly PropertyInfo ArgumentTypeConverterAttribute_TargetType = ArgumentTypeConverterAttribute?.GetProperty("TargetType", BindingFlags.Instance | BindingFlags.NonPublic); /// <summary> /// Resolves to <see cref="RuntimeException.RuntimeException(string)" />. /// </summary> public static readonly ConstructorInfo RuntimeException_Ctor = typeof(RuntimeException).GetConstructor(new[] { typeof(string) }); /// <summary> /// Resolves to <see cref="IDisposable.Dispose" />. /// </summary> public static readonly MethodInfo IDisposable_Dispose = typeof(IDisposable).GetMethod("Dispose"); /// <summary> /// Resolves to the indexer for <see cref="System.Collections.IList" />. /// </summary> public static readonly PropertyInfo IList_Item = typeof(IList).GetProperty("Item"); /// <summary> /// Resolves to the indexer for <see cref="System.Collections.IDictionary" />. /// </summary> public static readonly PropertyInfo IDictionary_Item = typeof(IDictionary).GetProperty("Item"); /// <summary> /// Resolves to the non-public parameterless constructor for System.Management.Automation.ExitException. /// </summary> public static readonly ConstructorInfo ExitException_Ctor = typeof(ExitException).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]); /// <summary> /// Resolves to the non-public constructor System.Management.Automation.ExitException(Object). /// </summary> public static readonly ConstructorInfo ExitException_Ctor_Object = typeof(ExitException).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(object) }, new[] { new ParameterModifier(1) }); /// <summary> /// Resolves to <see cref="Hashtable.Add(object, object)" />. /// </summary> public static readonly MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod("Add", new[] { typeof(object), typeof(object) }); /// <summary> /// Resolves to <see cref="Hashtable.Hashtable(int, IEqualityComparer)" />. /// </summary> public static readonly ConstructorInfo Hashtable_Ctor = typeof(Hashtable).GetConstructor(new[] { typeof(int), typeof(IEqualityComparer) }); /// <summary> /// Resolves to <see cref="IEnumerator.get_Current" />. /// </summary> public static readonly MethodInfo IEnumerator_get_Current = typeof(IEnumerator).GetMethod(Strings.EnumeratorGetCurrentMethodName, Type.EmptyTypes); /// <summary> /// Resolves to <see cref="IEnumerable.GetEnumerator" />. /// </summary> public static readonly MethodInfo IEnumerable_GetEnumerator = typeof(IEnumerable).GetMethod(Strings.GetEnumeratorMethodName, Type.EmptyTypes); /// <summary> /// Resolves to <see cref="StringComparer.CurrentCultureIgnoreCase" />. /// </summary> public static readonly PropertyInfo StringComparer_CurrentCultureIgnoreCase = typeof(StringComparer).GetProperty("CurrentCultureIgnoreCase"); /// <summary> /// Resolves to <see cref="ExpressionUtils.PSEqualsIgnoreCase(object, object)" />. /// </summary> public static readonly MethodInfo ExpressionUtils_PSEqualsIgnoreCase = typeof(ExpressionUtils).GetMethod("PSEqualsIgnoreCase", BindingFlags.Static | BindingFlags.NonPublic); /// <summary> /// Resolves to <see cref="ExpressionUtils.GetRange(int, int)" />. /// </summary> public static readonly MethodInfo ExpressionUtils_GetRange = typeof(ExpressionUtils).GetMethod("GetRange", BindingFlags.Static | BindingFlags.NonPublic); /// <summary> /// Resolves to <see cref="System.Threading.Monitor.Enter(object, ref bool)" />. /// </summary> public static readonly MethodInfo Monitor_Enter = typeof(System.Threading.Monitor).GetMethod( "Enter", new[] { typeof(object), typeof(bool).MakeByRefType() }); /// <summary> /// Resolves to <see cref="System.Threading.Monitor.Exit(object)" />. /// </summary> public static readonly MethodInfo Monitor_Exit = typeof(System.Threading.Monitor).GetMethod("Exit", new[] { typeof(object) }); /// <summary> /// Resolves to <see cref="IEnumerable{T}.GetEnumerator" />. /// </summary> public static readonly MethodInfo IEnumerable_T_GetEnumerator = typeof(IEnumerable<>).GetMethod(Strings.GetEnumeratorMethodName, Type.EmptyTypes); /// <summary> /// Resolves to <see cref="IEnumerator{T}.get_Current" />. /// </summary> public static readonly MethodInfo IEnumerator_T_get_Current = typeof(IEnumerator<>).GetMethod(Strings.EnumeratorGetCurrentMethodName, Type.EmptyTypes); /// <summary> /// Resolves to <see cref="IDictionary.GetEnumerator" />. /// </summary> public static readonly MethodInfo IDictionary_GetEnumerator = typeof(IDictionary).GetMethod(Strings.GetEnumeratorMethodName, Type.EmptyTypes); /// <summary> /// Resolves to <see cref="IDictionaryEnumerator.get_Entry" />. /// </summary> public static readonly MethodInfo IDictionaryEnumerator_get_Entry = typeof(IDictionaryEnumerator).GetMethod("get_Entry", Type.EmptyTypes); } } <file_sep>/src/PSLambda/Commands/ObjectAndBodyCommandHandler.cs using System.Globalization; using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda.Commands { /// <summary> /// Provides a base for commands that follow the format of /// `commandName ($objectTarget) { body }`. /// </summary> internal abstract class ObjectAndBodyCommandHandler : ICommandHandler { /// <summary> /// Gets the name of the command. /// </summary> public abstract string CommandName { get; } /// <summary> /// Creates a Linq expression for a <see cref="CommandAst" /> representing /// a custom command. /// </summary> /// <param name="commandAst">The AST to convert.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the expression.</param> /// <returns>An expression representing the command.</returns> public Expression ProcessAst(CommandAst commandAst, CompileVisitor visitor) { if (commandAst.CommandElements.Count != 3) { visitor.Errors.ReportParseError( commandAst.Extent, nameof(ErrorStrings.MissingKeywordElements), string.Format( CultureInfo.CurrentCulture, ErrorStrings.MissingKeywordElements, CommandName)); return Expression.Empty(); } if (!(commandAst.CommandElements[2] is ScriptBlockExpressionAst bodyAst)) { visitor.Errors.ReportParseError( commandAst.Extent, nameof(ErrorStrings.MissingKeywordBody), string.Format( CultureInfo.CurrentCulture, ErrorStrings.MissingKeywordBody, CommandName)); return Expression.Empty(); } return ProcessObjectAndBody( commandAst, commandAst.CommandElements[1], bodyAst, visitor); } /// <summary> /// Creates a Linq expression for a <see cref="CommandAst" /> representing /// a custom command. /// </summary> /// <param name="commandAst">The AST to convert.</param> /// <param name="targetAst">The AST containing the target of the keyword.</param> /// <param name="bodyAst">The AST containing the body of the keyword.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the expression.</param> /// <returns>An expression representing the command.</returns> protected abstract Expression ProcessObjectAndBody( CommandAst commandAst, CommandElementAst targetAst, ScriptBlockExpressionAst bodyAst, CompileVisitor visitor); } } <file_sep>/README.md # PSLambda PSLambda is a runtime compiler for PowerShell ScriptBlock objects. This project is in a very early state and is not currently recommended for use in production environments. This project adheres to the Contributor Covenant [code of conduct](https://github.com/SeeminglyScience/PSLambda/tree/master/docs/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to <EMAIL>. ## Build status |AppVeyor (Windows)|CircleCI (Linux)|CodeCov| |---|---|---| |[![Build status](https://ci.appveyor.com/api/projects/status/8n8alv7moy661rr6?svg=true)](https://ci.appveyor.com/project/SeeminglyScience/pslambda) |[![CircleCI](https://circleci.com/gh/SeeminglyScience/PSLambda.svg?style=svg)](https://circleci.com/gh/SeeminglyScience/PSLambda)|[![codecov](https://codecov.io/gh/SeeminglyScience/PSLambda/branch/master/graph/badge.svg)](https://codecov.io/gh/SeeminglyScience/PSLambda)| ## Features - C# like syntax (due to being compiled from interpreted Linq expression trees) with some PowerShell convenience features built in. (See the "Differences from PowerShell" section) - Run in threads without a `DefaultRunspace` as it does not actually execute any PowerShell code. - Access and change variables local to the scope the delegate was created in (similar to closures in C#) - Runs faster than PowerShell in most situations. - Parse errors similar to the PowerShell parser for compiler errors, including extent of the error. ## Motivation PowerShell is an excellent engine for exploration. When I'm exploring a new API, even if I intend to write the actual project in C# I will do the majority of my exploration from PowerShell. Most of the time there are no issues with doing that. Sometimes though, in projects that make heavy use of delegates you can run into issues. Yes the PowerShell engine can convert from `ScriptBlock` to any `Delegate` type, but it's just a wrapper. It still requires that `ScriptBlock` to be ran in a `Runspace` at some point. Sometimes that isn't possible, or just isn't ideal. Mainly when it comes to API's that are mainly `async`/`await` based. I also just really like the idea of a more strict syntax in PowerShell without losing **too** much flavor, so it was a fun project to get up and running. ## What would I use this for For most folks the answer is probably nothing. This is pretty niche, if you haven't specifically wished something like this existed in the past, it probably isn't applicable to you. The reason cited in "Motivation" (interactive API exploration and prototyping) is the only real application I am specifically planning for. If anyone has any intention of using this more broadly, I'd appreciate it if you could open an issue or shoot me a DM so I can keep your scenario in mind. ## Installation ### Gallery ```powershell Install-Module PSLambda -Scope CurrentUser ``` ### Source ```powershell git clone 'https://github.com/SeeminglyScience/PSLambda.git' Set-Location .\PSLambda Invoke-Build -Task Install -Configuration Release ``` ## How A custom `ICustomAstVisitor2` class visits each node in the abstract syntax tree of the ScriptBlock and interprets it as a `System.Linq.Expressions.Expression`. Most of the PowerShell language features are recreated from scratch as a Linq expression tree, using PowerShell API's where it makes sense to keep some flavor. This is actually more or less what the PowerShell engine does as well, but it's obviously still heavily reliant on the `Runspace`/`SessionState` system. The `psdelegate` type acts as a stand in for the compiled delegate until it is interpreted. Using the PowerShell type conversion system, if it is passed as an argument to a method that requires a specific delegate type it is interpreted and compiled at method invocation. ## Usage There's two main ways to use the module. 1. The `New-PSDelegate` command - this command will take a `ScriptBlock` and optionally a target `Delegate` type. With this method the delegate will be compiled immediately and will need to be recompiled if the delegate type needs to change. 1. The `psdelegate` type accelerator - you can cast a `ScriptBlock` as this type and it will retain the context until converted. This object can then be converted to a specific `Delegate` type later, either by explicittly casting the object as that type or implicitly as a method argument. Local variables are retained from when the `psdelegate` object is created. This method requires that the module be imported into the session as the type will not exist until it is. ### Demonstration of variable scoping and multi-threading ```powershell using namespace System.Threading using namespace System.Threading.Tasks using namespace System.Collections.Concurrent # PowerShell variables $queue = [BlockingCollection[string]]::new() $shouldCancel = [CancellationTokenSource]::new() # Everything inside this is compiled. $delegate = [psdelegate]{ # The ThreadStart block doesn't require "psdelegate" because this is still within the # expression tree, including the resulting nested delegate. Scope is kept. $thread = [Thread]::new([ThreadStart]{ try { # Take from the blocking collection defined in PowerShell, and throw an # OperationCancelledException if the cancellation token source defined in # PowerShell has been cancelled. while ($message = $queue.Take($shouldCancel.Token)) { # All "AllScope" variables are available including $Host $Host.UI.WriteLine($message) # Implicit ScriptBlock to delegate conversion when it can determine the # method argument type correctly $task = [Task]::Run{ [Thread]::Sleep(1000) # More Delegate nesting, still retaining variable scope. $Host.UI.WriteLine("Delayed: $message") } $task.GetAwaiter().GetResult() } # Make sure to catch anything that could throw inside the ThreadStart delegate, uncaught # exceptions will crash PowerShell. Uncaught exceptions are fine outside of the ThreadStart # delegate and will throw like any other method. } catch [OperationCancelledException] { $Host.UI.WriteLine('Thread closed!') } }) $thread.Start() return $thread } $thread = $delegate.Invoke() $queue.Add('This is a test message!') $queue.Add('Another test!') $queue.Add('So many tests') # To close the thread use: # $shouldCancel.Cancel() ``` ### Create a psdelegate to pass to a method ```powershell $a = 0 $delegate = [psdelegate]{ $a += 1 } $actions = $delegate, $delegate, $delegate, $delegate [System.Threading.Tasks.Parallel]::Invoke($actions) $a # 4 ``` Creates a delegate that increments the local `PSVariable` "a", and then invokes it in a different thread four times. Doing the same with `ScriptBlock` objects instead would result in an error stating the the thread does not have a default runspace. *Note*: Access to local variables from the `Delegate` is synced across threads for *some* thread safety, but that doesn't effect anything accessing the variable directly so they are still *not* thread safe. ### Access all scope variables ```powershell $delegate = New-PSDelegate { $ExecutionContext.SessionState.InvokeProvider.Item.Get("\") } $delegate.Invoke() # Directory: # Mode LastWriteTime Length Name # ---- ------------- ------ ---- # d--hs- 3/32/2010 9:61 PM C:\ ``` ### Use alternate C# esque delegate syntax ```powershell $timer = [System.Timers.Timer]::new(1000) $delegate = [psdelegate]{ ($sender, $e) => { $Host.UI.WriteLine($e.SignalTime.ToString()) }} $timer.Enabled = $true $timer.add_Elapsed($delegate) Start-Sleep 10 $timer.remove_Elapsed($delegate) ``` Create a timer that fires an event every 1000 milliseconds, then add a compiled delegated as an event handler. A couple things to note here. 1. Parameter type inference is done automatically during conversion. This is important because the compiled delegate is *not* dynamically typed like PowerShell is. 1. `psdelegate` objects that have been converted to a specific Delegate type are cached, so the instance is the same in both `add_Elapsed` and `remove_Elapsed`. ## Differences from PowerShell While the `ScriptBlock`'s used in the examples look like (and for the most part are) valid PowerShell syntax, very little from PowerShell is actually used. The abstract syntax tree (AST) is read and interpreted into a `System.Linq.Expressions.Expression` tree. The rules are a lot closer to C# than to normal PowerShell. There are some very PowerShell like things thrown in to make it feel a bit more like PowerShell though. ### Supported PowerShell features - All operators, including `like`, `match`, `split`, and all the case sensitive/insensitive comparision operators. These work mostly the exact same as in PowerShell due to using `LanguagePrimitives` under the hood. - PowerShell conversion rules. Explicit conversion (e.g. `[int]$myVar`) is done using `LanguagePrimitives`. This allows for all of the PowerShell type conversions to be accessible from the compiled delegate. However, type conversion is *not* automatic like it often is in PowerShell. Comparision operators are the exception, as they also use `LanguagePrimitives`. - Access to PSVariables. Any variable that is either `AllScope` (like `$Host` and `$ExecutionContext`) is from the most local scope is available as a variable in the delegate. This works similar to closures in C#, allowing the current value to be read as well as changed. Changes to the value will only be seen in the scope the delegate was created in (unless the variable is AllScope). ### Unsupported PowerShell features - The extended type system and dynamic typing in genernal. This means that things like methods, properties and even the specific method overload called by an expression is all determined at compile time. If a method declares a return type of `object`, you'll need to cast it to something else before you can do much with it. - Commands. Yeah that's a big one I know. There's no way to run a command without a runspace, and if I require a runspace to run a command then there isn't a point in any of this. If you absolutely need to run a command, you can use the `$ExecutionContext` or `[powershell]` API's, but they are likely to be unreliable from a thread other than the pipeline thread. - Variables need to assigned before they can be used. If the type is not included in the assignment the type will be inferred from the assignment (similar to C#'s `var` keyword, but implied). - A good amount more. I'll update this list as much as possible as I use this more. If you run into something that could use explaining here, opening an issue on this repo would be very helpful. ## Custom language keywords No support for commands left some room to add some custom keywords that help with some problems that aren't all that applicable to PowerShell, but may be here. ### With ```powershell using namespace System.Management.Automation $delegate = [psdelegate]{ with ($ps = [powershell]::Create([RunspaceMode]::NewRunspace)) { $result = $ps.AddScript('Get-Date').Invoke() $result[0].Properties.Add( [psnoteproperty]::new( 'Runspace', $ps.Runspace)) return $result[0] } } $pso = $delegate.Invoke() $pso # Sunday, April 22, 2018 6:51:04 PM $pso.Runspace # Id Name ComputerName Type State Availability # -- ---- ------------ ---- ----- ------------ # 13 Runspace13 localhost Local Closed None ``` The `with` keyword works like the `using` keyword in C#. The object in the initialization expression (the parenthesis) will be disposed when the statement ends, even if the event of an unhandled exception. ### Default ```powershell $delegate = [psdelegate]{ default([ConsoleColor]) } $delegate.Invoke() # Black $delegate = [psdelegate]{ default([object]) } $delegate.Invoke() # (returns null) ``` Returns the default value for a type. This will return `null` if the type is nullable, otherwise it will return the default value for the that type. ### Generic ```powershell $delegate = [psdelegate]{ generic ([array]::Empty(), [int]) } $delegate.Invoke().GetType() # IsPublic IsSerial Name BaseType # -------- -------- ---- -------- # True True Int32[] System.Array $delegate = [psdelegate]{ generic ([tuple]::Create(10, 'string'), [int], [string]) } $delegate.Invoke() # Item1 Item2 Length # ----- ----- ------ # 10 string 2 ``` I haven't built in any automatic generic argument inference yet (PowerShell has a little bit), so right now this keyword is required to use any generic method. The syntax for the generic type arguments is similar to the `params` keyword. The first "parameter" should be the the member expression, and any additional parameters should be types. The resulting `Expression` is just the member expression with the resolved method. ## Contributions Welcome! We would love to incorporate community contributions into this project. If you would like to contribute code, documentation, tests, or bug reports, please read our [Contribution Guide](https://github.com/SeeminglyScience/PSLambda/tree/master/docs/CONTRIBUTING.md) to learn more. <file_sep>/src/PSLambda/VariableUtils.cs using System; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides utility methods for variable expression operations. /// </summary> internal static class VariableUtils { /// <summary> /// Determines if the specified variable is referencing the automatic /// variable <c>$_</c> or <c>$PSItem</c>. /// </summary> /// <param name="variableExpressionAst">The variable expression to test.</param> /// <returns> /// <see langword="true" /> if the specified variable references /// dollar under, otherwise <see langword="false" />. /// </returns> public static bool IsDollarUnder(VariableExpressionAst variableExpressionAst) => IsDollarUnder(variableExpressionAst.VariablePath.UserPath); /// <summary> /// Determines if the specified variable is referencing the automatic /// variable <c>$_</c> or <c>$PSItem</c>. /// </summary> /// <param name="variableName">The variable name to test.</param> /// <returns> /// <see langword="true" /> if the specified variable references /// dollar under, otherwise <see langword="false" />. /// </returns> public static bool IsDollarUnder(string variableName) { return variableName.Equals("_", StringComparison.Ordinal) || variableName.Equals("PSItem", StringComparison.Ordinal); } } } <file_sep>/src/PSLambda/Commands/GenericCommand.cs using System; using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda.Commands { /// <summary> /// Provides handling for the "generic" custom command. /// </summary> internal class GenericCommand : ICommandHandler { /// <summary> /// Gets the name of the command. /// </summary> public string CommandName { get; } = "generic"; /// <summary> /// Creates a Linq expression for a <see cref="CommandAst" /> representing /// the "generic" command. /// </summary> /// <param name="commandAst">The AST to convert.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the expression.</param> /// <returns>An expression representing the command.</returns> public Expression ProcessAst(CommandAst commandAst, CompileVisitor visitor) { if (commandAst.CommandElements.Count != 2) { return ReportInvalidSyntax(commandAst.Extent, visitor); } if (!(commandAst.CommandElements[1] is ParenExpressionAst paren)) { return ReportInvalidSyntax(commandAst.Extent, visitor); } if (!(paren.Pipeline is PipelineAst pipeline) || pipeline.PipelineElements.Count != 1) { return ReportInvalidSyntax(commandAst.Extent, visitor); } if (!(pipeline.PipelineElements[0] is CommandExpressionAst commandExpression)) { return ReportInvalidSyntax(commandAst.Extent, visitor); } var arrayLiteral = commandExpression.Expression as ArrayLiteralAst; if (arrayLiteral.Elements.Count < 2) { return ReportInvalidSyntax(commandAst.Extent, visitor); } if (!(arrayLiteral.Elements[0] is InvokeMemberExpressionAst memberExpression)) { return ReportInvalidSyntax(commandAst.Extent, visitor); } var genericArguments = new Type[arrayLiteral.Elements.Count - 1]; for (var i = 1; i < arrayLiteral.Elements.Count; i++) { if (visitor.TryResolveType(arrayLiteral.Elements[i], out Type resolvedType)) { genericArguments[i - 1] = resolvedType; continue; } // If a type didn't resolve then a parse error was generated, so exit. return Expression.Empty(); } return visitor.CompileInvokeMemberExpression(memberExpression, genericArguments); } private Expression ReportInvalidSyntax(IScriptExtent extent, CompileVisitor visitor) { visitor.Errors.ReportParseError( extent, nameof(ErrorStrings.InvalidGenericSyntax), ErrorStrings.InvalidGenericSyntax); return Expression.Empty(); } } } <file_sep>/src/PSLambda/IParseErrorWriter.cs using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides uniform writing and management of <see cref="ParseError" /> objects. /// </summary> internal interface IParseErrorWriter { /// <summary> /// Reports a <see cref="ParseError" />. Handling of the <see cref="ParseError" /> /// may defer between implementations. /// </summary> /// <param name="extent"> /// The <see cref="IScriptExtent" /> of the error being reported. /// </param> /// <param name="id">The id of the error.</param> /// <param name="message"> /// The message to display in the <see cref="System.Management.Automation.ParseException" /> /// when parsing is completed. /// </param> void ReportParseError( IScriptExtent extent, string id, string message); /// <summary> /// Throws if the error limit has been hit. Error limit may vary /// between implementations. /// </summary> void ThrowIfErrorLimitHit(); /// <summary> /// Throws if any error has been reported. /// </summary> void ThrowIfAnyErrors(); } } <file_sep>/src/PSLambda/LabelScopeStack.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace PSLambda { /// <summary> /// Represents the current set of scopes in which the <c>return</c> keyword will work. /// </summary> internal class LabelScopeStack { private LabelScope _current; /// <summary> /// Gets the implied or explicit return type. /// </summary> public Type ReturnType => _current?.ReturnType; /// <summary> /// Creates a new scope in which the <c>return</c> keyword will work. /// </summary> /// <returns> /// A <see cref="IDisposable" /> handle that will return to the previous scope when disposed. /// </returns> public IDisposable NewScope() { _current = _current == null ? new LabelScope() : new LabelScope(_current); return new ScopeHandle(() => _current = _current?._parent); } /// <summary> /// Creates a new scope in which the <c>return</c> keyword will work while specifying an /// expected return type. /// </summary> /// <param name="returnType">The expected return type.</param> /// <returns> /// A <see cref="IDisposable" /> handle that will return to the previous scope when disposed. /// </returns> public IDisposable NewScope(Type returnType) { _current = _current == null ? new LabelScope() : new LabelScope(_current); _current.ReturnType = returnType; return new ScopeHandle(() => _current = _current?._parent); } /// <summary> /// Gets the specified statement adding the <c>return</c> label if applicable. /// </summary> /// <param name="expressions">The expressions to precent the label.</param> /// <param name="requireExplicitReturn"> /// A value indicating whether an explicit return statement should be required. /// </param> /// <returns> /// If a <c>return</c> label is required the supplied expressions will be returned followed /// by the required label, otherwise they will be returned unchanged. /// </returns> public Expression[] WithReturn(IEnumerable<Expression> expressions, bool requireExplicitReturn = true) { if (_current.IsReturnRequested) { return expressions.Concat( new[] { Expression.Label( _current.Label, Expression.Default(_current.ReturnType)), }).ToArray(); } if (!requireExplicitReturn) { return expressions.ToArray(); } _current.IsReturnRequested = true; _current.ReturnType = typeof(void); return expressions.Concat(new[] { Expression.Label(_current.Label) }).ToArray(); } /// <summary> /// Gets an existing <c>return</c> label if one has already been defined, otherwise /// one is created. /// </summary> /// <param name="type">The expected return type.</param> /// <returns>The <see cref="LabelTarget" /> requested.</returns> public LabelTarget GetOrCreateReturnLabel(Type type) { if (_current != null && _current.IsReturnRequested) { return _current.Label; } _current.IsReturnRequested = true; _current.ReturnType = type; return _current.Label; } } } <file_sep>/src/PSLambda/LoopScopeStack.cs using System; using System.Linq.Expressions; namespace PSLambda { /// <summary> /// Represents a set of scopes in which the <c>break</c> or <c>continue</c> keywords /// may be used. /// </summary> internal class LoopScopeStack { private LoopScope _current; /// <summary> /// Gets the current label for the <c>break</c> keyword. /// </summary> internal LabelTarget Break => _current?.Break; /// <summary> /// Gets the current label for the <c>continue</c> keyword. /// </summary> internal LabelTarget Continue => _current?.Continue; /// <summary> /// Creates a new scope in which the <c>break</c> or <c>continue</c> keywords /// may be used. /// </summary> /// <returns> /// A <see cref="IDisposable" /> handle that will return to the previous scope when disposed. /// </returns> internal IDisposable NewScope() { _current = new LoopScope() { Parent = _current, Break = Expression.Label(), Continue = Expression.Label(), }; return new ScopeHandle(() => _current = _current?.Parent); } } } <file_sep>/src/PSLambda/Strings.cs namespace PSLambda { /// <summary> /// Provides string constant values for various strings used throughout the project. /// </summary> internal class Strings { /// <summary> /// Constant containing a string similar to "GetEnumerator". /// </summary> public const string GetEnumeratorMethodName = "GetEnumerator"; /// <summary> /// Constant containing a string similar to "get_Current". /// </summary> public const string EnumeratorGetCurrentMethodName = "get_Current"; /// <summary> /// Constant containing a string similar to "psdelegate". /// </summary> public const string PSDelegateTypeAcceleratorName = "psdelegate"; /// <summary> /// Constant containing a string similar to "ExecutionContext". /// </summary> public const string ExecutionContextVariableName = "ExecutionContext"; /// <summary> /// Constant containing a string similar to "foreach". /// </summary> public const string ForEachVariableName = "foreach"; /// <summary> /// Constant containing a string similar to "null". /// </summary> public const string NullVariableName = "null"; /// <summary> /// Constant containing a string similar to "true". /// </summary> public const string TrueVariableName = "true"; /// <summary> /// Constant containing a string similar to "false". /// </summary> public const string FalseVariableName = "false"; /// <summary> /// Constant containing a string similar to "new". /// </summary> public const string ConstructorMemberName = "new"; /// <summary> /// Constant containing a string similar to "OperatorNotSupported". /// </summary> public const string OperatorNotSupportedId = "OperatorNotSupported"; /// <summary> /// Constant containing a string similar to ">". /// </summary> public const string DelegateSyntaxCommandName = ">"; /// <summary> /// Constant containing a string similar to "Invoke". /// </summary> public const string DelegateInvokeMethodName = "Invoke"; /// <summary> /// Constant containing a string similar to "Value". /// </summary> public const string PSVariableWrapperValuePropertyName = "Value"; /// <summary> /// Constant containing a string similar to "Item". /// </summary> public const string DefaultIndexerPropertyName = "Item"; /// <summary> /// Constant containing a string similar to "ElementAtOrDefault". /// </summary> public const string ElementAtOrDefaultMethodName = "ElementAtOrDefault"; /// <summary> /// Constant containing a string similar to "Add". /// </summary> public const string AddMethodName = "Add"; /// <summary> /// Constant containing a string similar to "ToArray". /// </summary> public const string ToArrayMethodName = "ToArray"; } } <file_sep>/src/PSLambda/NewPSDelegateCommand.cs using System; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; namespace PSLambda { /// <summary> /// Represents the New-PSDelegate command. /// </summary> [Cmdlet(VerbsCommon.New, "PSDelegate")] [OutputType(typeof(Delegate))] public class NewPSDelegateCommand : PSCmdlet { /// <summary> /// Gets or sets the value for the parameter "DelegateType". /// </summary> [Parameter] [ValidateNotNull] public Type DelegateType { get; set; } /// <summary> /// Gets or sets the value for the parameter "Expression". /// </summary> [Parameter(Position = 0, Mandatory = true)] [ValidateNotNull] public ScriptBlock Expression { get; set; } /// <summary> /// The EndProcessing method. /// </summary> protected override void EndProcessing() { var variables = SessionState.InvokeCommand.InvokeScript( "Get-Variable -Scope 0", false, PipelineResultTypes.Output, null, null) .Select(pso => pso.BaseObject) .Cast<PSVariable>() .Where(v => !SpecialVariables.IgnoreLocal.Contains(v.Name)); try { if (DelegateType == null) { WriteObject( CompileVisitor.CompileAst( (EngineIntrinsics)SessionState.PSVariable.GetValue(Strings.ExecutionContextVariableName), (ScriptBlockAst)Expression.Ast, variables.ToArray()), enumerateCollection: false); return; } WriteObject( CompileVisitor.CompileAst( (EngineIntrinsics)SessionState.PSVariable.GetValue(Strings.ExecutionContextVariableName), (ScriptBlockAst)Expression.Ast, variables.ToArray(), DelegateType), enumerateCollection: false); } catch (ParseException e) { ThrowTerminatingError(new ErrorRecord(e.ErrorRecord, e)); } } } } <file_sep>/src/PSLambda/Commands/DefaultCommand.cs using System; using System.Linq.Expressions; using System.Management.Automation; using System.Management.Automation.Language; namespace PSLambda.Commands { /// <summary> /// Provides handling for the "default" custom command. /// </summary> internal class DefaultCommand : ICommandHandler { /// <summary> /// Gets the name of the command. /// </summary> public string CommandName { get; } = "default"; /// <summary> /// Creates a Linq expression for a <see cref="CommandAst" /> representing /// the "default" command. /// </summary> /// <param name="commandAst">The AST to convert.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the expression.</param> /// <returns>An expression representing the command.</returns> public Expression ProcessAst(CommandAst commandAst, CompileVisitor visitor) { if (commandAst.CommandElements == null || commandAst.CommandElements.Count != 2) { visitor.TryResolveType(null, out _); return Expression.Empty(); } // Is using syntax "default([TypeName])" if (commandAst.CommandElements[1] is ParenExpressionAst paren && paren.Pipeline is PipelineAst pipeline && pipeline.PipelineElements.Count == 1 && pipeline.PipelineElements[0] is CommandExpressionAst commandExpression && commandExpression.Expression is TypeExpressionAst && visitor.TryResolveType(commandExpression.Expression, out Type resolvedType)) { return Expression.Default(resolvedType); } // Is using syntax "default TypeName" if (commandAst.CommandElements[1] is StringConstantExpressionAst stringConstant && LanguagePrimitives.TryConvertTo(stringConstant.Value, out resolvedType)) { return Expression.Default(resolvedType); } // Unknown syntax, but this method will produce parse errors for us. if (visitor.TryResolveType(commandAst.CommandElements[1], out resolvedType)) { return Expression.Default(resolvedType); } return Expression.Empty(); } } } <file_sep>/src/PSLambda/PSDelegate.cs using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Represents an <see cref="Delegate" /> that is not yet compiled but can be /// converted implicitly by the PowerShell engine. /// </summary> public sealed class PSDelegate { private Delegate _defaultDelegate; /// <summary> /// Initializes a new instance of the <see cref="PSDelegate" /> class. /// </summary> /// <param name="scriptBlock">The <see cref="ScriptBlock" /> to compile.</param> public PSDelegate(ScriptBlock scriptBlock) { using (var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace)) { Locals = pwsh.AddCommand("Microsoft.PowerShell.Utility\\Get-Variable") .AddParameter("Scope", 0) .Invoke<PSVariable>() .Where(v => !SpecialVariables.IgnoreLocal.Contains(v.Name)) .ToDictionary(v => v.Name); pwsh.Commands.Clear(); EngineIntrinsics = pwsh.AddCommand("Microsoft.PowerShell.Utility\\Get-Variable") .AddParameter("Name", "ExecutionContext") .AddParameter("ValueOnly", true) .Invoke<EngineIntrinsics>() .First(); } ScriptBlock = scriptBlock; } /// <summary> /// Initializes a new instance of the <see cref="PSDelegate" /> class. /// </summary> /// <param name="scriptBlock">The <see cref="ScriptBlock" /> to compile.</param> /// <param name="engine"> /// The <see cref="EngineIntrinsics" /> instance for the current runspace. /// </param> /// <param name="locals"> /// Any <see cref="PSVariable" /> objects that are local to the /// current scope with the exception of AllScope variables. /// </param> internal PSDelegate(ScriptBlock scriptBlock, EngineIntrinsics engine, Dictionary<string, PSVariable> locals) { Locals = locals; EngineIntrinsics = engine; ScriptBlock = scriptBlock; } /// <summary> /// Gets the ScriptBlock represented by the delegate. /// </summary> public ScriptBlock ScriptBlock { get; } /// <summary> /// Gets the <see cref="EngineIntrinsics" /> from the origin /// <see cref="System.Management.Automation.Runspaces.Runspace" />. /// </summary> internal EngineIntrinsics EngineIntrinsics { get; } /// <summary> /// Gets the <see cref="PSVariable" /> objects from origin SessionStateScope. /// </summary> internal Dictionary<string, PSVariable> Locals { get; } /// <summary> /// Gets the default <see cref="Delegate" /> that is used for the /// <see cref="PSDelegate.Invoke(object[])" /> method. /// </summary> internal Delegate DefaultDelegate { get { if (_defaultDelegate != null) { return _defaultDelegate; } return _defaultDelegate = CreateDefaultDelegate(); } } /// <summary> /// Invokes the compiled <see cref="Delegate" /> represented by this object. If the /// <see cref="Delegate" /> has not yet been compiled, it will be compiled prior to /// invocation. /// </summary> /// <param name="arguments">Arguments to pass to the <see cref="Delegate" />.</param> /// <returns>The result returned by the <see cref="Delegate" />.</returns> public object Invoke(params object[] arguments) { return DefaultDelegate.DynamicInvoke(arguments); } private Delegate CreateDefaultDelegate() { return CompileVisitor.CompileAst( EngineIntrinsics, (ScriptBlockAst)ScriptBlock.Ast, Locals.Values.ToArray()); } } } <file_sep>/src/PSLambda/ParseErrorWriter.cs using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Language; namespace PSLambda { /// <summary> /// Provides uniform writing and management of <see cref="ParseError" /> objects. /// </summary> internal abstract class ParseErrorWriter : IParseErrorWriter { /// <summary> /// Initializes a new instance of the <see cref="ParseErrorWriter" /> class. /// </summary> protected ParseErrorWriter() { } /// <summary> /// Creates an instance of the default <see cref="ParseErrorWriter" />. This /// error writer will report full error messages and will throw after a maximum /// of three errors. /// </summary> /// <returns>The defualt <see cref="ParseErrorWriter" />.</returns> public static ParseErrorWriter CreateDefault() => new DefaultParseErrorWriter(); /// <summary> /// Creates an instance of the null <see cref="ParseErrorWriter" />. This /// error writer will not report any error messages and will throw immediately /// after the first error has been reported. /// </summary> /// <returns>The null <see cref="ParseErrorWriter" />.</returns> public static ParseErrorWriter CreateNull() => new NullParseErrorWriter(); /// <summary> /// Reports a <see cref="ParseError" />. Handling of the <see cref="ParseError" /> /// may defer between implementations. /// </summary> /// <param name="extent"> /// The <see cref="IScriptExtent" /> of the error being reported. /// </param> /// <param name="id">The id of the error.</param> /// <param name="message"> /// The message to display in the <see cref="System.Management.Automation.ParseException" /> /// when parsing is completed. /// </param> public virtual void ReportParseError(IScriptExtent extent, string id, string message) { } /// <summary> /// Throws if the error limit has been hit. Error limit may vary /// between implementations. /// </summary> public virtual void ThrowIfErrorLimitHit() { } /// <summary> /// Throws if any error has been reported. /// </summary> public virtual void ThrowIfAnyErrors() { } private class NullParseErrorWriter : ParseErrorWriter { private int _errorCount; public override void ReportParseError(IScriptExtent extent, string id, string message) { _errorCount++; throw new ParseException(); } public override void ThrowIfAnyErrors() { if (_errorCount > 0) { throw new ParseException(); } } public override void ThrowIfErrorLimitHit() { if (_errorCount > 0) { throw new ParseException(); } } } private class DefaultParseErrorWriter : ParseErrorWriter { private const int ErrorLimit = 3; private readonly List<ParseError> _errors = new List<ParseError>(); public override void ReportParseError(IScriptExtent extent, string id, string message) { _errors.Add( new ParseError( extent, id, message)); ThrowIfErrorLimitHit(); } public override void ThrowIfErrorLimitHit() { if (_errors.Count < ErrorLimit) { return; } throw new ParseException(_errors.ToArray()); } public override void ThrowIfAnyErrors() { if (_errors.Count < 1) { return; } throw new ParseException(_errors.ToArray()); } } } } <file_sep>/src/PSLambda/Commands/WithCommand.cs using System; using System.Linq.Expressions; using System.Management.Automation.Language; namespace PSLambda.Commands { /// <summary> /// Provides handling for the "with" custom command. /// </summary> internal class WithCommand : ObjectAndBodyCommandHandler { /// <summary> /// Gets the name of the command. /// </summary> public override string CommandName { get; } = "with"; /// <summary> /// Creates a Linq expression for a <see cref="CommandAst" /> representing /// the "with" command. /// </summary> /// <param name="commandAst">The AST to convert.</param> /// <param name="targetAst">The AST containing the target of the keyword.</param> /// <param name="bodyAst">The AST containing the body of the keyword.</param> /// <param name="visitor">The <see cref="CompileVisitor" /> requesting the expression.</param> /// <returns>An expression representing the command.</returns> protected override Expression ProcessObjectAndBody( CommandAst commandAst, CommandElementAst targetAst, ScriptBlockExpressionAst bodyAst, CompileVisitor visitor) { var disposeVar = Expression.Variable(typeof(IDisposable)); return visitor.NewBlock(() => Expression.Block( typeof(void), new[] { disposeVar }, Expression.Assign( disposeVar, Expression.Convert( targetAst.Compile(visitor), typeof(IDisposable))), Expression.TryFinally( bodyAst.ScriptBlock.EndBlock.Compile(visitor), Expression.Call(disposeVar, ReflectionCache.IDisposable_Dispose)))); } } } <file_sep>/src/PSLambda/ScopeHandle.cs using System; namespace PSLambda { /// <summary> /// Represents a handle for the current scope. /// </summary> internal class ScopeHandle : IDisposable { private readonly Action _disposer; private bool _isDisposed; /// <summary> /// Initializes a new instance of the <see cref="ScopeHandle" /> class. /// </summary> /// <param name="disposer">The action that disposes of the scope.</param> public ScopeHandle(Action disposer) { _disposer = disposer; } /// <summary> /// Disposes of the current scope. /// </summary> public void Dispose() { if (_isDisposed) { return; } _disposer?.Invoke(); _isDisposed = true; } } } <file_sep>/src/PSLambda/LoopScope.cs using System.Linq.Expressions; namespace PSLambda { /// <summary> /// Represents a scope in which the <c>break</c> or <c>continue</c> keywords /// may be used. /// </summary> internal class LoopScope { /// <summary> /// Gets or sets the parent scope. /// </summary> public LoopScope Parent { get; set; } /// <summary> /// Gets or sets the label for the <c>break</c> keyword. /// </summary> public LabelTarget Break { get; set; } /// <summary> /// Gets or sets the label for the <c>continue</c> keyword. /// </summary> public LabelTarget Continue { get; set; } } }
4a00505e8555a72866df1a6bfc16ddb34cbb009c
[ "Markdown", "C#" ]
32
C#
SeeminglyScience/PSLambda
fcbfff7d5de2559e9317c19a5bf50b28f4562164
7dbef10d7ab2e0c59c5e1a01c5be678866d4d35e
refs/heads/main
<repo_name>ospych/Inventory-MVP<file_sep>/app/src/main/java/com/example/inventorymvp/InventoryAdapter.java package com.example.inventorymvp; import android.annotation.SuppressLint; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.AsyncDifferConfig; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.ListAdapter; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.inventorymvp.Data.Inventory; public class InventoryAdapter extends ListAdapter<Inventory, InventoryAdapter.Holder> { private OnItemClickListener listener; public InventoryAdapter() {super(DIFF_CALLBACK);} private static final DiffUtil.ItemCallback<Inventory> DIFF_CALLBACK = new DiffUtil.ItemCallback<Inventory>() { @Override public boolean areItemsTheSame(@NonNull Inventory oldItem, @NonNull Inventory newItem) { return oldItem.getId() == newItem.getId(); } @Override public boolean areContentsTheSame(@NonNull Inventory oldItem, @NonNull Inventory newItem) { return oldItem.getTitle().equals(newItem.getTitle()) && oldItem.getSupplier().equals(newItem.getSupplier()) && oldItem.getQuantity() == newItem.getQuantity(); } }; @NonNull @Override public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.inventory_item, parent, false); return new Holder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull Holder holder, int position) { Inventory current = getItem(position); holder.titleTV.setText("Item: " + current.getTitle()); holder.supplierTV.setText("Supplier: " + current.getSupplier()); holder.quantityTV.setText("Quantity: " + current.getQuantity()); holder.priceTV.setText(current.getPrice() + "$"); Glide.with(holder.imageView.getContext()).load(current.getImage()).into(holder.imageView); } public Inventory getItemAt(int position) { return getItem(position); } public class Holder extends RecyclerView.ViewHolder { private TextView titleTV; private TextView supplierTV; private TextView quantityTV; private TextView priceTV; private ImageView imageView; public Holder(@NonNull View itemView) { super(itemView); titleTV = itemView.findViewById(R.id.titleTV); supplierTV = itemView.findViewById(R.id.supplierTV); quantityTV = itemView.findViewById(R.id.quantityTV); priceTV = itemView.findViewById(R.id.priceTV); imageView = itemView.findViewById(R.id.image); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); if (listener != null && position != RecyclerView.NO_POSITION) { listener.onItemClick(getItem(position)); } } }); } } public interface OnItemClickListener { void onItemClick(Inventory inventory); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; } } <file_sep>/app/src/main/java/com/example/inventorymvp/MainActivity.java package com.example.inventorymvp; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.example.inventorymvp.Data.Inventory; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.List; public class MainActivity extends AppCompatActivity { private MainPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FloatingActionButton buttonAddNote = findViewById(R.id.button_add); buttonAddNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, EditActivity.class); startActivity(intent); } }); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); final InventoryAdapter adapter = new InventoryAdapter(); recyclerView.setAdapter(adapter); presenter = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory .getInstance(this.getApplication())) .get(MainPresenter.class); presenter.getItems().observe(this, new Observer<List<Inventory>>() { @Override public void onChanged(List<Inventory> inventories) { adapter.submitList(inventories); } }); new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { presenter.delete(adapter.getItemAt(viewHolder.getAdapterPosition())); Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_SHORT).show(); } }).attachToRecyclerView(recyclerView); adapter.setOnItemClickListener(new InventoryAdapter.OnItemClickListener() { @Override public void onItemClick(Inventory inventory) { Intent intent = new Intent(MainActivity.this, EditActivity.class); intent.putExtra(EditActivity.EXTRA_ID, inventory.getId()); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if ((item.getItemId()) == R.id.delete_all) { DialogButton(); return true; } return super.onOptionsItemSelected(item); } public void DialogButton() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Delete all"); builder.setMessage("Are you sure?"); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { presenter.deleteAllItems(); Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT) .show(); } }); builder.setNegativeButton("Cancel", null); AlertDialog dialog = builder.create(); dialog.show(); } }<file_sep>/app/src/main/java/com/example/inventorymvp/MainContract.java package com.example.inventorymvp; import com.example.inventorymvp.Data.Inventory; public interface MainContract { interface Presenter { void insert(Inventory inventory); void update(Inventory inventory); void delete(Inventory inventory); void deleteAllItems(); } interface View { } } <file_sep>/app/src/main/java/com/example/inventorymvp/EditPresenter.java package com.example.inventorymvp; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import com.example.inventorymvp.Data.Inventory; import com.example.inventorymvp.Data.InventoryRepository; public class EditPresenter extends AndroidViewModel implements EditContract.Presenter { private InventoryRepository repository; LiveData<Inventory> inventory; public EditPresenter(@NonNull Application application) { super(application); repository = new InventoryRepository(application); } @Override public void insert(Inventory inventory) { repository.insert(inventory); } @Override public void getItem(int id) { inventory = repository.getItem(id); } @Override public void update(Inventory inventory) { repository.update(inventory); } @Override public void delete(Inventory inventory) { repository.delete(inventory); } @Override public void save(String title, String supplier, double price, int quantity, String image) { Inventory item = new Inventory(title, supplier, price, quantity, image); if (this.inventory == null){ insert(item); } else { Inventory inventoryItem = this.inventory.getValue(); if (inventoryItem != null) item.setId(inventoryItem.getId()); update(item); } } }
79aed74714785515bec4015b47caad69201867e8
[ "Java" ]
4
Java
ospych/Inventory-MVP
17bd1d6c7863bbf349881de628c80a56cceb3f9c
24d89dfef5554b9a4748f7b6ab27f262f5245d82
refs/heads/main
<file_sep>from django.urls import path from .views import * app_name = 'Furniture' urlpatterns = [ path('mdfwalldecor', mdfwalldecor, name='mdfwalldecor'), path('furniturecafestool', furniturecafestool, name='furniturecafestool'), path('woodkeyholder', woodkeyholder, name='woodkeyholder'), path('storagecase', storagecase, name='storagecase'), path('wallmirror', wallmirror, name='wallmirror'), path('entunit', entunit, name='entunit'), ]<file_sep># Generated by Django 3.2 on 2021-06-01 17:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pid', models.CharField(max_length=10)), ('uid', models.CharField(max_length=10)), ('rating', models.FloatField(default=0)), ('comment', models.CharField(blank=True, max_length=1000, null=True)), ('date', models.DateTimeField()), ], ), migrations.CreateModel( name='Mobiles', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('product_id', models.CharField(max_length=10, unique=True)), ('product_name', models.CharField(max_length=100)), ('product_desc', models.CharField(max_length=200)), ('price', models.CharField(max_length=10)), ('colour', models.CharField(max_length=20)), ('image1', models.ImageField(upload_to='')), ('image2', models.ImageField(upload_to='')), ('image3', models.ImageField(upload_to='')), ('image4', models.ImageField(upload_to='')), ('image5', models.ImageField(upload_to='')), ('os', models.CharField(max_length=10)), ('ram', models.CharField(max_length=10)), ('product_dimensions', models.CharField(max_length=50)), ('batteries', models.CharField(max_length=100)), ('item_model_number', models.CharField(max_length=10)), ('wireless_features', models.CharField(max_length=1000)), ('special_features', models.CharField(max_length=1000)), ('display', models.CharField(max_length=1000)), ('camera', models.CharField(max_length=200)), ('form_factor', models.CharField(max_length=100)), ('battery_power', models.IntegerField()), ('manufacturer', models.CharField(max_length=100)), ('origin', models.CharField(max_length=20)), ('asin', models.CharField(max_length=30)), ('average_customer_rating', models.FloatField(default=0)), ('best_sellers', models.CharField(max_length=200)), ('launch_date', models.CharField(max_length=50)), ('manufacture_address', models.CharField(max_length=200)), ('generic_name', models.CharField(max_length=20)), ('model_rating', models.FloatField(default=0)), ], ), migrations.CreateModel( name='Features', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('features', models.CharField(max_length=500)), ('pid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Mobiles.mobiles', to_field='product_id')), ], ), ] <file_sep># Generated by Django 3.2 on 2021-06-06 10:33 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pid', models.CharField(max_length=10)), ('uid', models.CharField(max_length=10)), ('rating', models.FloatField(default=0)), ('comment', models.CharField(blank=True, max_length=1000, null=True)), ('date', models.DateTimeField()), ], ), ] <file_sep>from django.shortcuts import render from .models import * from django.contrib.auth.models import User from datetime import date import tensorflow as tf import numpy as np from django.db.models import Count # Create your views here. new_model = tf.keras.models.load_model('Machine learning models/stack.tf') def zeellehenga(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'CLO1', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'CLO1', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'CLO1').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'CLO1').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Clothing.objects.get(product_id='CLO1').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Clothing.objects.update_or_create(product_id='CLO1', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='CLO1') row = Clothing.objects.get(product_id='CLO1') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'image1': '../static/images/clothing/taslarbabyjumpsuit/' + str(row.image1), 'image2': '../static/images/clothing/taslarbabyjumpsuit/' + str(row.image2), 'image3': '../static/images/clothing/taslarbabyjumpsuit/' + str(row.image3), 'image4': '../static/images/clothing/taslarbabyjumpsuit/' + str(row.image4), 'image5': '../static/images/clothing/taslarbabyjumpsuit/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Clothing/zeellehenga.html', context=context) def babyjumpsuit(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'CLO6', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'CLO6', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'CLO6').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'CLO6').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Clothing.objects.get(product_id='CLO6').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Clothing.objects.update_or_create(product_id='CLO6', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='CLO6') row = Clothing.objects.get(product_id='CLO6') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'product_dimensions': row.product_dimensions, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Clothing/babyjumpsuit.html', context=context) def mensweatshirt(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'CLO3', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'CLO3', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'CLO3').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'CLO3').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Clothing.objects.get(product_id='CLO3').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Clothing.objects.update_or_create(product_id='CLO3', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='CLO3') row = Clothing.objects.get(product_id='CLO3') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'product_dimensions': row.product_dimensions, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Clothing/mensweatshirt.html', context=context) def menshirt(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'CLO4', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'CLO4', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'CLO4').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'CLO4').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Clothing.objects.get(product_id='CLO4').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Clothing.objects.update_or_create(product_id='CLO4', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='CLO4') row = Clothing.objects.get(product_id='CLO4') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'product_dimensions': row.product_dimensions, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Clothing/menshirt.html', context=context) def babyromper(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'CLO5', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'CLO5', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'CLO5').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'CLO5').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Clothing.objects.get(product_id='CLO5').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Clothing.objects.update_or_create(product_id='CLO5', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='CLO5') row = Clothing.objects.get(product_id='CLO5') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'product_dimensions': row.product_dimensions, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Clothing/babyromper.html', context=context) def bandhejsaree(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'CLO2', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'CLO2', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'CLO2').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'CLO2').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Clothing.objects.get(product_id='CLO2').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Clothing.objects.update_or_create(product_id='CLO2', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='CLO2') row = Clothing.objects.get(product_id='CLO2') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'product_dimensions': row.product_dimensions, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Clothing/bandhejsaree.html', context=context)<file_sep>from django.shortcuts import render from .models import * from django.contrib.auth.models import User from datetime import date import tensorflow as tf import numpy as np from django.db.models import Count # Create your views here. new_model = tf.keras.models.load_model('Machine learning models/stack.tf') def oneplus(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'MOB1', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'MOB1', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'MOB1').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'MOB1').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Mobiles.objects.get(product_id='MOB1').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Mobiles.objects.update_or_create(product_id='MOB1', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='MOB1') row = Mobiles.objects.get(product_id='MOB1') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/mobiles/onepluseightpro/' + str(row.image1), 'image2': '../static/images/mobiles/onepluseightpro/' + str(row.image2), 'image3': '../static/images/mobiles/onepluseightpro/' + str(row.image3), 'image4': '../static/images/mobiles/onepluseightpro/' + str(row.image4), 'image5': '../static/images/mobiles/onepluseightpro/' + str(row.image5), 'os': row.os, 'ram': row.ram, 'product_dimensions': row.product_dimensions, 'batteries': row.batteries, 'item_model_number': row.item_model_number, 'wireless': row.wireless_features, 'special': row.special_features, 'display': row.display, 'camera': row.camera, 'form_factor': row.form_factor, 'battery_power': row.battery_power, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'manufacture_address': row.manufacture_address, 'generic_name': row.generic_name, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Mobiles/onepluseightpro.html', context=context) def redmi9power(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'MOB2', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'MOB2', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'MOB2').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'MOB2').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Mobiles.objects.get(product_id='MOB2').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Mobiles.objects.update_or_create(product_id='MOB2', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='MOB2') row = Mobiles.objects.get(product_id='MOB2') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'os': row.os, 'ram': row.ram, 'product_dimensions': row.product_dimensions, 'batteries': row.batteries, 'item_model_number': row.item_model_number, 'wireless': row.wireless_features, 'special': row.special_features, 'display': row.display, 'camera': row.camera, 'form_factor': row.form_factor, 'battery_power': row.battery_power, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'manufacture_address': row.manufacture_address, 'generic_name': row.generic_name, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Mobiles/redmi9power.html', context=context) def samsunggalaxym51(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'MOB3', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'MOB3', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'MOB3').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'MOB3').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Mobiles.objects.get(product_id='MOB3').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Mobiles.objects.update_or_create(product_id='MOB3', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='MOB3') row = Mobiles.objects.get(product_id='MOB3') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'os': row.os, 'ram': row.ram, 'product_dimensions': row.product_dimensions, 'batteries': row.batteries, 'item_model_number': row.item_model_number, 'wireless': row.wireless_features, 'special': row.special_features, 'display': row.display, 'camera': row.camera, 'form_factor': row.form_factor, 'battery_power': row.battery_power, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'manufacture_address': row.manufacture_address, 'generic_name': row.generic_name, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Mobiles/samsunggalaxym51.html', context=context) def iphone12mini(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'MOB6', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'MOB6', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'MOB6').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'MOB6').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Mobiles.objects.get(product_id='MOB6').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Mobiles.objects.update_or_create(product_id='MOB6', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='MOB6') row = Mobiles.objects.get(product_id='MOB6') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'os': row.os, 'ram': row.ram, 'product_dimensions': row.product_dimensions, 'batteries': row.batteries, 'item_model_number': row.item_model_number, 'wireless': row.wireless_features, 'special': row.special_features, 'display': row.display, 'camera': row.camera, 'form_factor': row.form_factor, 'battery_power': row.battery_power, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'manufacture_address': row.manufacture_address, 'generic_name': row.generic_name, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Mobiles/iphone12mini.html', context=context) def nokia34(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'MOB4', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'MOB4', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'MOB4').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'MOB4').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Mobiles.objects.get(product_id='MOB4').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Mobiles.objects.update_or_create(product_id='MOB4', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='MOB4') row = Mobiles.objects.get(product_id='MOB4') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'os': row.os, 'ram': row.ram, 'product_dimensions': row.product_dimensions, 'batteries': row.batteries, 'item_model_number': row.item_model_number, 'wireless': row.wireless_features, 'special': row.special_features, 'display': row.display, 'camera': row.camera, 'form_factor': row.form_factor, 'battery_power': row.battery_power, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'manufacture_address': row.manufacture_address, 'generic_name': row.generic_name, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Mobiles/nokia3.4.html', context=context) def vivoy20(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'MOB5', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'MOB5', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'MOB5').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'MOB5').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Mobiles.objects.get(product_id='MOB5').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Mobiles.objects.update_or_create(product_id='MOB5', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='MOB5') row = Mobiles.objects.get(product_id='MOB5') features = list(Features.objects.filter(pid=row)) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': row.image1, 'image2': row.image2, 'image3': row.image3, 'image4': row.image4, 'image5': row.image5, 'os': row.os, 'ram': row.ram, 'product_dimensions': row.product_dimensions, 'batteries': row.batteries, 'item_model_number': row.item_model_number, 'wireless': row.wireless_features, 'special': row.special_features, 'display': row.display, 'camera': row.camera, 'form_factor': row.form_factor, 'battery_power': row.battery_power, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'manufacture_address': row.manufacture_address, 'generic_name': row.generic_name, 'features': features, 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Mobiles/vivoy20.html', context=context)<file_sep>from django.urls import path from .views import * app_name = 'Clothing' urlpatterns = [ path('zeellehenga', zeellehenga, name='zeellehenga'), path('babyjumpsuit', babyjumpsuit, name='babyjumpsuit'), path('mensweatshirt', mensweatshirt, name='mensweatshirt'), path('menshirt', menshirt, name='menshirt'), path('babyromper', babyromper, name='babyromper'), path('bandhejsaree', bandhejsaree, name='bandhejsaree'), ]<file_sep>from django.db import models from django.contrib.auth.models import User # Create your models here. class Clothing(models.Model): product_id = models.CharField(max_length=10, unique=True) product_name = models.CharField(max_length=100) product_desc = models.CharField(max_length=200) price = models.CharField(max_length=10) image1 = models.ImageField() image2 = models.ImageField() image3 = models.ImageField() image4 = models.ImageField() image5 = models.ImageField() product_dimensions = models.CharField(max_length=50) launch_date = models.CharField(max_length=50) manufacturer = models.CharField(max_length=100) asin = models.CharField(max_length=30) origin = models.CharField(max_length=20) department = models.CharField(max_length=10) weight = models.CharField(max_length=20) average_customer_rating = models.FloatField(default=0) best_sellers = models.CharField(max_length=200, blank=True) model_rating = models.FloatField(default=0) class Features(models.Model): pid = models.ForeignKey(Clothing, on_delete=models.CASCADE, to_field='product_id') features = models.CharField(max_length=500) class Comments(models.Model): # pid = models.ForeignKey(Clothing, on_delete=models.CASCADE, to_field='product_id') pid = models.CharField(max_length=10) # uid = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username', related_name='clothing_uid') uid = models.CharField(max_length=10) rating = models.FloatField(default=0) comment = models.CharField(max_length=1000, blank=True, null=True) date = models.DateTimeField()<file_sep>from django.conf.urls import include from django.urls import path from . import views as login_views app_name = 'Register_Login' urlpatterns = [ path('register', login_views.register, name='register'), path('login', login_views.user_login, name='user_login'), path('logout', login_views.user_logout, name='user_logout'), ]<file_sep># Generated by Django 3.2 on 2021-06-08 19:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Clothing', '0001_initial'), ] operations = [ ] <file_sep>from django.contrib import admin from .models import * # Register your models here. admin.site.register(Clothing) admin.site.register(Features) admin.site.register(Comments)<file_sep>from django.shortcuts import render from .forms import UserForm from django.contrib.auth.models import User from .models import * from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): return render(request, 'Register_Login/index.html') def register(request): registered = False first_name = '' last_name = '' email = '' username = '' password = '' if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): # print(User.objects.get(username=request.POST.get('username')).exists()) user = user_form.save() user.set_password(user.<PASSWORD>) # Hashing the passwords -> Encrypting them user.save() length = len(Customer.objects.all()) customer = Customer.objects.create(uid='CUS' + str(length + 1), user=user) customer.save() registered = True if user.is_authenticated: return HttpResponseRedirect(reverse('Register_Login:user_login')) else: errors = [(k, v[0]) for k, v in user_form.errors.items()] # print(errors[0][1]) print(errors) for i in errors: print(f'i = {i[0]}, first_name = {first_name}, last_name = {last_name}, email = {email}, username = {username}, password = {password}') if i[0] == 'first_name': first_name = i[1] if i[0] == 'last_name': last_name = i[1] if i[0] == 'email': email = i[1] if i[0] == 'username': username = i[1] if i[0] == 'password': password = i[1] # print(f'Error = {user_form.errors}') else: user_form = UserForm() return render(request, 'Register_Login/register.html', {'user_form': user_form, 'registered': registered, 'first_name': first_name, 'last_name': last_name, 'email': email, 'username': username, 'password': <PASSWORD>}) def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=<PASSWORD>) if user: login(request, user) return HttpResponseRedirect(reverse('index')) else: print("Someone tried to login and failed") print(f'Username: {username} and Password: {password}') return HttpResponse("Invalid login details supplied") return render(request, 'Register_Login/login.html', {}) @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index'))<file_sep>from django.contrib import admin from django.conf.urls import include from django.urls import path from .views import * app_name = 'Mobiles' urlpatterns = [ path('oneplus', oneplus, name = 'oneplus'), path('redmi9power', redmi9power, name = 'redmi9power'), path('samsunggalaxym51', samsunggalaxym51, name = 'samsunggalaxym51'), path('iphone12mini', iphone12mini, name = 'iphone12mini'), path('nokia3.4', nokia34, name = 'nokia3.4'), path('vivoy20', vivoy20, name = 'vivoy20'), ]<file_sep># Generated by Django 3.2 on 2021-06-08 18:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Furniture', '0001_initial'), ] operations = [ migrations.CreateModel( name='Furniture', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('product_id', models.CharField(max_length=10, unique=True)), ('product_name', models.CharField(max_length=100)), ('product_desc', models.CharField(max_length=200)), ('price', models.CharField(max_length=10)), ('colour', models.CharField(max_length=20)), ('image1', models.ImageField(upload_to='')), ('image2', models.ImageField(upload_to='')), ('image3', models.ImageField(upload_to='')), ('image4', models.ImageField(upload_to='')), ('image5', models.ImageField(upload_to='')), ('product_dimensions', models.CharField(max_length=50)), ('assembly_required', models.CharField(max_length=200)), ('primary_material', models.CharField(max_length=50)), ('finish_type', models.CharField(max_length=50)), ('item_shape', models.CharField(max_length=20)), ('manufacturer', models.CharField(max_length=100)), ('origin', models.CharField(max_length=20)), ('asin', models.CharField(max_length=30)), ('average_customer_rating', models.FloatField(default=0)), ('best_sellers', models.CharField(blank=True, max_length=200)), ('launch_date', models.CharField(max_length=50)), ('model_rating', models.FloatField(default=0)), ], ), migrations.CreateModel( name='Features', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('material', models.CharField(max_length=50)), ('dimensions', models.CharField(max_length=70)), ('weight', models.CharField(max_length=20)), ('brand', models.CharField(max_length=20)), ('assembly_required', models.CharField(max_length=200)), ('pid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Furniture.furniture', to_field='product_id')), ], ), ] <file_sep>from django.shortcuts import render from .models import * from django.contrib.auth.models import User from datetime import date import tensorflow as tf import numpy as np from django.db.models import Count # Create your views here. new_model = tf.keras.models.load_model('Machine learning models/stack.tf') def mdfwalldecor(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'FUR1', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'FUR1', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'FUR1').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) # print(rating_count) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'FUR1').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) print(f'rate1 = {rate1}, rate2 = {rate2}, rate3 = {rate3}, rate4 = {rate4}, rate5 = {rate5}') final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Furniture.objects.get(product_id='FUR1').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Furniture.objects.update_or_create(product_id='FUR1', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='FUR1') row = Furniture.objects.get(product_id='FUR1') features = Features.objects.filter(pid=row) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/furniture/mdfwalldecor/' + str(row.image1), 'image2': '../static/images/furniture/mdfwalldecor/' + str(row.image2), 'image3': '../static/images/furniture/mdfwalldecor/' + str(row.image3), 'image4': '../static/images/furniture/mdfwalldecor/' + str(row.image4), 'image5': '../static/images/furniture/mdfwalldecor/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'assembly_required': row.assembly_required, 'primary_material': row.primary_material, 'finish_type': row.finish_type, 'item_shape': row.item_shape, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features[0], 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Furniture/mdfwalldecor.html', context=context) def furniturecafestool(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'FUR2', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'FUR2', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'FUR2').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) # print(rating_count) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'FUR2').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) print(f'rate1 = {rate1}, rate2 = {rate2}, rate3 = {rate3}, rate4 = {rate4}, rate5 = {rate5}') final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Furniture.objects.get(product_id='FUR2').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Furniture.objects.update_or_create(product_id='FUR2', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='FUR2') row = Furniture.objects.get(product_id='FUR2') features = Features.objects.filter(pid=row) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/furniture/mdfwalldecor/' + str(row.image1), 'image2': '../static/images/furniture/mdfwalldecor/' + str(row.image2), 'image3': '../static/images/furniture/mdfwalldecor/' + str(row.image3), 'image4': '../static/images/furniture/mdfwalldecor/' + str(row.image4), 'image5': '../static/images/furniture/mdfwalldecor/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'assembly_required': row.assembly_required, 'primary_material': row.primary_material, 'finish_type': row.finish_type, 'item_shape': row.item_shape, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features[0], 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Furniture/furniturecafestool.html', context=context) def woodkeyholder(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'FUR3', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'FUR3', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'FUR3').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) # print(rating_count) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'FUR3').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) print(f'rate1 = {rate1}, rate2 = {rate2}, rate3 = {rate3}, rate4 = {rate4}, rate5 = {rate5}') final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Furniture.objects.get(product_id='FUR3').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Furniture.objects.update_or_create(product_id='FUR3', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='FUR3') row = Furniture.objects.get(product_id='FUR3') features = Features.objects.filter(pid=row) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/furniture/mdfwalldecor/' + str(row.image1), 'image2': '../static/images/furniture/mdfwalldecor/' + str(row.image2), 'image3': '../static/images/furniture/mdfwalldecor/' + str(row.image3), 'image4': '../static/images/furniture/mdfwalldecor/' + str(row.image4), 'image5': '../static/images/furniture/mdfwalldecor/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'assembly_required': row.assembly_required, 'primary_material': row.primary_material, 'finish_type': row.finish_type, 'item_shape': row.item_shape, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features[0], 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Furniture/a10keyholder.html', context=context) def storagecase(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'FUR4', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'FUR4', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'FUR4').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) # print(rating_count) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'FUR4').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) print(f'rate1 = {rate1}, rate2 = {rate2}, rate3 = {rate3}, rate4 = {rate4}, rate5 = {rate5}') final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Furniture.objects.get(product_id='FUR4').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Furniture.objects.update_or_create(product_id='FUR4', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='FUR4') row = Furniture.objects.get(product_id='FUR4') features = Features.objects.filter(pid=row) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/furniture/mdfwalldecor/' + str(row.image1), 'image2': '../static/images/furniture/mdfwalldecor/' + str(row.image2), 'image3': '../static/images/furniture/mdfwalldecor/' + str(row.image3), 'image4': '../static/images/furniture/mdfwalldecor/' + str(row.image4), 'image5': '../static/images/furniture/mdfwalldecor/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'assembly_required': row.assembly_required, 'primary_material': row.primary_material, 'finish_type': row.finish_type, 'item_shape': row.item_shape, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features[0], 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Furniture/storagecase.html', context=context) def wallmirror(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'FUR5', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'FUR5', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'FUR5').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) # print(rating_count) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'FUR5').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) print(f'rate1 = {rate1}, rate2 = {rate2}, rate3 = {rate3}, rate4 = {rate4}, rate5 = {rate5}') final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Furniture.objects.get(product_id='FUR5').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Furniture.objects.update_or_create(product_id='FUR5', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='FUR5') row = Furniture.objects.get(product_id='FUR5') features = Features.objects.filter(pid=row) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/furniture/mdfwalldecor/' + str(row.image1), 'image2': '../static/images/furniture/mdfwalldecor/' + str(row.image2), 'image3': '../static/images/furniture/mdfwalldecor/' + str(row.image3), 'image4': '../static/images/furniture/mdfwalldecor/' + str(row.image4), 'image5': '../static/images/furniture/mdfwalldecor/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'assembly_required': row.assembly_required, 'primary_material': row.primary_material, 'finish_type': row.finish_type, 'item_shape': row.item_shape, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features[0], 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Furniture/wallmirror.html', context=context) def entunit(request): rating = 0 required = '' if request.method == "POST": # product_id can also be received with this code (with correct code - not implemented yet) # Check request.POST -> product_id is also returned data = request.POST.get('rate_value') cmt = request.POST.get('comment') if data and cmt: predictions = new_model.predict([cmt]) rating = np.argmax(predictions[0]) print(f'COMMENT = {cmt}, MODEL PREDICTED RATING = {rating}') comment = Comments(pid = 'FUR6', uid = request.user, comment = cmt, rating = data, date = date.today()) comment.save() elif cmt: required = '<i class="fas fa-exclamation-triangle" style="color: orange;"></i> Please provide a rating first to submit your review!' elif data: comment = Comments(pid = 'FUR6', uid = request.user, rating = data, date = date.today()) comment.save() fieldname = 'rating' rating_count = Comments.objects.filter(pid = 'FUR6').values(fieldname).order_by(fieldname).annotate(the_count = Count(fieldname)) # print(rating_count) rate1 = 0 rate2 = 0 rate3 = 0 rate4 = 0 rate5 = 0 for i in rating_count: if i.get("rating") == 1.0: rate1 = i.get("the_count") elif i.get("rating") == 2.0: rate2 = i.get("the_count") elif i.get("rating") == 3.0: rate3 = i.get("the_count") elif i.get("rating") == 4.0: rate4 = i.get("the_count") elif i.get("rating") == 5.0: rate5 = i.get("the_count") rating_sum = rate1 * 1 + rate2 * 2 + rate3 * 3 + rate4 * 4 + rate5 * 5 total_ratings = rate1 + rate2 + rate3 + rate4 + rate5 word_comments = Comments.objects.filter(pid = 'FUR6').exclude(comment = 'NULL') total_comments = len(word_comments) # for i in word_comments: # print(i.comment) print(f'rate1 = {rate1}, rate2 = {rate2}, rate3 = {rate3}, rate4 = {rate4}, rate5 = {rate5}') final_rating = round((rating_sum / total_ratings), 2) prev_model_rating = Furniture.objects.get(product_id='FUR6').model_rating if rating != 0: model_rating = round(((prev_model_rating * total_comments) + rating) / (total_comments + 1), 2) else: model_rating = prev_model_rating obj, created = Furniture.objects.update_or_create(product_id='FUR6', defaults={'average_customer_rating':final_rating, 'model_rating': model_rating}) obj.save() rating1 = (rate1 / (total_ratings)) * 100 rating2 = (rate2 / (total_ratings)) * 100 rating3 = (rate3 / (total_ratings)) * 100 rating4 = (rate4 / (total_ratings)) * 100 rating5 = (rate5 / (total_ratings)) * 100 final_star = final_rating * 20 # () * 100 / 5 = () * 20 model_star = model_rating * 20 comments = Comments.objects.filter(pid='FUR6') row = Furniture.objects.get(product_id='FUR6') features = Features.objects.filter(pid=row) context = { 'product_name': row.product_name, 'product_specs': row.product_desc, 'price': row.price, 'color': row.colour, 'image1': '../static/images/furniture/mdfwalldecor/' + str(row.image1), 'image2': '../static/images/furniture/mdfwalldecor/' + str(row.image2), 'image3': '../static/images/furniture/mdfwalldecor/' + str(row.image3), 'image4': '../static/images/furniture/mdfwalldecor/' + str(row.image4), 'image5': '../static/images/furniture/mdfwalldecor/' + str(row.image5), 'product_dimensions': row.product_dimensions, 'assembly_required': row.assembly_required, 'primary_material': row.primary_material, 'finish_type': row.finish_type, 'item_shape': row.item_shape, 'manufacturer': row.manufacturer, 'origin': row.origin, 'asin': row.asin, 'average_customer_rating': row.average_customer_rating, 'best_sellers': row.best_sellers, 'launch_date': row.launch_date, 'features': features[0], 'comments': comments, 'final_rating': row.average_customer_rating, 'total_ratings': total_ratings, 'rating1': rating5, 'rating2': rating4, 'rating3': rating3, 'rating4': rating2, 'rating5': rating1, 'final_star': final_star, 'model_rating': row.model_rating, 'model_star': model_star, 'comments': word_comments, 'required': required, } return render(request, 'Furniture/tventunit.html', context=context)<file_sep>//jshint esversion:6 $(function () { $('[data-toggle="tooltip"]').tooltip(); });
a7a703d5147494d2fe1cd15374d4d28e12c1ad22
[ "JavaScript", "Python" ]
15
Python
swati-1008/Shoptastic
71eb7047da6c2196f574cc6c08cd43d59b0a012b
dec0eed1bd1f19582d85c9c36beaaf08343d4cf1
refs/heads/master
<repo_name>nathanhollows/flatsAPI<file_sep>/README.md # flatsAPI An API for storing and retrieving flats The API is currently being tested on [nathanhollows.com/flats/](https://nathanhollows.com/flats/) | Method | Url | Action | |:------ |:--- |:------ | | `GET` | /api/flats | Retrives all current flats, sorted by date added | | `POST` | /api/flats | Save a new listing. Returns the ID | | `GET` | /api/flats/id/{id} | Retrieve a flat by ID | | `DELETE` | /api/flats/id/{id} | Remove a flat from the listings | Content type must be `application/x-www-form-urlencoded` (for now) ## Fields | Value | Type | Default | Description | |:----- |:---- |:------- | :---------- | | id | string | UUID | An automatically generated UUID | | price * | int | NULL | The cost per week | | bedrooms * | int | NULL | | | bedrooms * | int | NULL | | | parking * | int | NULL | The number of off street parks | | heroText * | string | NULL | Short description of listing. 100 char limit | | description * | string | NULL | Description of listing | | agent * | string | NULL | | | image * | string | NULL | Image URL | | url * | string | NULL | URL for listing | | type * | string | NULL | To be decided | | dateAdded | timestamp | NOW() | Derived when the listing was first added | | dateAvailable | date | NOW() | When the listing is available | | dateRemoved | timestamp | NULL | Derived when the listing was removed | | pets * | int | 0 | `0`: False, `1`: True | | address * | int | null | A string repesentation of the address | **Note:** * Accepted in POST `/api/flats/` <file_sep>/models/Flats.php <?php namespace App\Models; use Phalcon\Mvc\Model; use Phalcon\Mvc\Model\Message; use Phalcon\Validation; class Flats extends Model { // UUID public $id; public $price; public $bedrooms; public $bathrooms; public $parking; public $heroText; public $description; public $agent; public $image; public $url; public $type; public $dateAdded; public $dateAvailable; public $dateRemoved; public $pets; public $address; public $latitude; public $longtitude; } ?> <file_sep>/index.php <?php error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql; use Phalcon\Di\FactoryDefault; use Phalcon\Http\Response; use Phalcon\Loader; use Phalcon\Mvc\Micro; use Phalcon\Security\Random; $loader = new Loader(); $loader->registerNamespaces( [ 'App\Models' => __DIR__ . '/models/', ] ); $loader->register(); $di = new FactoryDefault(); $di->set( 'db', function() { return new PdoMysql([ 'host' => 'localhost', 'username' => 'user', 'password' => '<PASSWORD>', 'dbname' => 'flats', ]); } ); $app = new Micro($di); $app->get( '/', function() { echo "https://github.com/nathanhollows/flatsAPI"; } ); // I am not proud of this. // TODO: Move to paginator // TODO: Move to query builder $app->get( '/api/flats', function() use ($app) { $listings = $app->modelsManager->createBuilder(); $limit = $app->request->get("limit", "int", 10000); $offset = $app->request->get("offset", "int", 0); $filter = ""; $search = $app->request->getQuery("search", "string", ""); if ($search != "") { $filter = "AND (address LIKE '%$search%' OR heroText LIKE '%$search%' OR description LIKE '%$search%')"; } if ($app->request->hasQuery("priceLow")) { $filter = $filter . " AND price >= " . $app->request->getQuery('priceLow', 'absint', 0); } if ($app->request->hasQuery("priceHigh")) { $filter = $filter . " AND price <= " . $app->request->getQuery('priceHigh', 'absint', 0); } if ($app->request->hasQuery("bedsLow")) { $filter = $filter . " AND bedrooms >= " . $app->request->getQuery('bedsLow', 'absint', 0); } if ($app->request->hasQuery("bedsHigh")) { $filter = $filter . " AND bedrooms <= " . $app->request->getQuery('bedsLow', 'absint', 0); } $phql = "SELECT id, price, bedrooms, bathrooms, parking, heroText, description, agent, image, url, type, dateAdded, dateAvailable, pets, address FROM App\Models\Flats WHERE dateRemoved IS NULL " . $filter . " ORDER BY dateAdded"; $flats = $app->modelsManager->executeQuery($phql); $response = new Response(); $response->setJsonContent([ 'status' => 'OK', 'data' => $flats, ]); return $response; } ); $app->post( '/api/flats', function() use ($app) { $request = $app->request; $phql = 'INSERT INTO App\Models\Flats (id, price, bedrooms, bathrooms, parking, heroText, description, agent, image, type, dateAvailable, pets, address, url) VALUES (:id:, :price:, :bedrooms:, :bathrooms:, :parking:, :heroText:, :description:, :agent:, :image:, :type:, :dateAvailable:, :pets:, :address:, :url:)'; $random = new Random(); $uuid = $random->uuid(); $status = $app->modelsManager->executeQuery( $phql, [ 'id'=> $uuid, 'address' => $request->getPost("address", "string", null), 'price' => $request->getPost("price", "absint", null), 'bedrooms' => $request->getPost("bedrooms", "absint", null), 'bathrooms' => $request->getPost("bathrooms", "absint", null), 'parking' => $request->getPost("parking", "absint", null), 'heroText' => $request->getPost("heroText", "string", null), 'description' => $request->getPost("description", "string", null), 'agent' => $request->getPost("agent", "string", null), 'image' => $request->getPost("image", "string", null), 'url' => $request->getPost("url", "string", null), 'type' => $request->getPost("type", "string", null), 'dateAvailable' => $request->getPost("dateAvailble", null, date("Y-m-d")), 'pets' => $request->getPost("pets", "absint", null), ] ); $response = new Response(); if ($status->success()) { $response->setStatusCode(201, 'Created'); $response->setJsonContent([ 'status' => 'OK', 'data' => $uuid, ]); } else { $response->setStatusCode(409, 'Conflict'); $errors = []; foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent([ 'status' => 'ERROR', 'messages' => $errors, ]); } return $response; } ); $app->get( '/api/flats/id/{id}', function($id) use ($app) { $phql = 'SELECT * FROM App\Models\Flats WHERE id = :id:'; $flats = $app->modelsManager->executeQuery( $phql, ['id' => $id] ); echo json_encode($flats); } ); $app->delete( '/api/flats/id/{id}', function($id) use ($app) { $phql = 'UPDATE App\Models\Flats SET dateRemoved = CURRENT_TIMESTAMP() WHERE id = :id:'; $status = $app->modelsManager->executeQuery( $phql, ['id' => $id] ); $response = new Response(); if ($status->success() === true) { $response->setJsonContent([ 'status' => "OK", ]); } else { $response->setStatusCode(409, 'Conflict'); $errors = []; foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent([ 'status' => 'ERROR', 'messages' => $errors, ]); } return $response; } ); $app->handle();
faa77f99d530d3fe0da139d6ed1d499f2f4bb89f
[ "Markdown", "PHP" ]
3
Markdown
nathanhollows/flatsAPI
fe670f14d1d6f656bfacf921c837bb05bd2eb54f
569f3cc1a1de1b4b77006e2cc381211cf3afced2
refs/heads/master
<repo_name>lk452584833/resume<file_sep>/src/common/js/utils.js /** * 解析url所有参数以对象形式解析 * @example ?id=123&a=1 * @return Object {id:123,a:1} */ function urlParam() { let url = window.location.search let obj = {} let reg = /[?&][^?&]+=[^?&]+/g let arr = url.match(reg) if (arr) { arr.forEach((item) => { let tempArr = item.substring(1).split('=') let key = decodeURIComponent(tempArr[0]) let val = decodeURIComponent(tempArr[1]) obj[key] = val }) } return obj } /* 獲取URL查詢參數指定name */ function getSearch(param) { var search = location.search.substr(1) var locate = search.search(param) var paramString = '' if (locate !== -1) { var searchRest = search.substr(locate) var len = searchRest.length var and = searchRest.search('&') if (and === -1) { paramString = searchRest.substr(param, len) } else { paramString = searchRest.substr(param, and) } var paramArray = paramString.split('=') return paramArray[1] } else { return false } } /* 返回错误信息弹出,需配合reset.css */ function showBackMsg(data) { var $body = document.body var $div = document.createElement('div') $div.innerText = data $div.className = 'errorMsg' $body.appendChild($div) var $errorMsg = document.getElementsByClassName('errorMsg') if ($errorMsg) { setTimeout(function() { $errorMsg[0].parentNode.removeChild($errorMsg[0]) }, 1500) } } /* 獲取并展示上傳圖片 */ /* 说明:fileInput為input:file文檔元素,img為img文檔元素 */ function showImg(fileInput, img) { var file = fileInput.files[0] if (window.FileReader) { var reader = new FileReader() reader.readAsDataURL(file) reader.onloadend = function(e) { // 監聽文件讀取后 img.setAttribute('src', e.target.result)// e.target.result就是最後的路徑地址 } } } /* 將圖片轉化成dataUrl模式 */ function getImgBase64(path, callback) { console.log(path) var img = new Image() img.src = path img.onload = function() { // 圖片加載完後觸發 var canvas = document.createElement('canvas') var ctx = canvas.getContext('2d') // 獲取繪畫上下文 var imgWidth = img.width // 獲取圖片寬度 var imgHeight = img.height // 獲取圖片高度 canvas.width = imgWidth // 設置幕布高度 canvas.height = imgHeight // 設置幕布寬度 ctx.drawImage(img, 0, 0, imgWidth, imgHeight) // 繪製圖片 var dataUrl = canvas.toDataURL('image/jpeg') // 繪製圖片 callback ? callback(dataUrl) : '' } } /* 複製對象 */ function cloneObject(obj) { var newObj = {} for (var item in obj) { newObj[item] = obj[item] } return newObj } /* 複製HTML元素 */ /* **** 導出到Vue **** */ /* main.js中引入 * import utils from './common/js/utils.js' * Vue.use(utils) */ export default { install(Vue, options) { Vue.prototype.$_urlParam = urlParam Vue.prototype.$_showImg = showImg Vue.prototype.$_showBackMsg = showBackMsg Vue.prototype.$_getSearch = getSearch Vue.prototype.$_getImgBase64 = getImgBase64 Vue.prototype.$_cloneObject = cloneObject } } <file_sep>/test/unit/specs/IconSupports.spec.js import Vue from 'vue' import IconSupports from '../../../src/components/IconSupports' describe('IconSupports.vue', () => { it('测试开始', () => { const Constructor = Vue.extend(IconSupports) const vm = new Constructor().$mount() expect(vm.$el.querySelector('.supports-icon').textContent) .toEqual('测试组件') }) }) <file_sep>/src/common/js/store.js /** * 存储localStorage * id, key, val @example 1,favorite,true ,3,favorite,true , * @example => {"1":{"favorite":true},"2":{"favorite":true}} * */ export function saveToLocal(id, key, val) { let seller = window.localStorage._info_ if (!seller) { seller = {} seller[id] = {} } else { seller = JSON.parse(seller) if (!seller[id]) { seller[id] = {} } } seller[id][key] = val window.localStorage._info_ = JSON.stringify(seller) } /** * 获取localStroage * @example loadFromLocal(1,'favorite', false) => true * */ export function loadFromLocal(id, key, def) { let seller = window.localStorage._info_ if (!seller) { return def } seller = JSON.parse(seller)[id] if (!seller) { return def } else { return seller[key] || def } } <file_sep>/src/components/MessageSure/index.js import MessageSure from './MessageSure.vue' const MSG = { animateTime: 500, // 弹窗出现,隐藏的动画时间 defaultTitle: '操作提示:', // 默认提示 isRegister: false, // 是否正在使用模板 install(Vue, options) { if (typeof window !== 'undefined' && window.Vue) { Vue = window.Vue } Vue.component('messagesure', MessageSure) // 全局注册模板 function BackMsg(text, callBack) { if (MSG.isRegister) { // 操作未确认或者取消前,不会继续调用模板 return } MSG.isRegister = !MSG.isRegister let words, titlemsg // 弹窗信息,弹出头部 if (typeof text === 'string') { words = text titlemsg = MSG.defaultTitle // string,使用默认titlText } else if (text instanceof Object) { // 参数是个对象 words = text.text || '' // 参数是个对象的情况下,不存在titleText属性时,使用默认 // 存在titleText 属性时,(空的话,表示子组件,title隐藏) titlemsg = (typeof text.titleText) === 'undefined' ? MSG.defaultTitle : (text.titleText || '') } let VueMsg = Vue.extend({ render(h) { return h('messagesure', { props: { text: words, titleText: titlemsg, show: this.show }, on: { msgcancel: function() { vm.show = false let t1 = setTimeout(() => { clearTimeout(t1) document.body.removeChild(el) vm = null VueOneMsg.$destroy() MSG.isRegister = !MSG.isRegister }, MSG.animateTime) }, msgsure: function() { // 动画效果过后,清除元素,调用回调 vm.show = false let t2 = setTimeout(() => { clearTimeout(t2) document.body.removeChild(el) vm = null VueOneMsg.$destroy() MSG.isRegister = !MSG.isRegister callBack && (typeof callBack === 'function') && callBack() }, MSG.animateTime) } } }) }, data() { return { show: false } } }) let VueOneMsg = new VueMsg() let vm = VueOneMsg.$mount() let el = vm.$el document.body.append(el) vm.show = true // 显示之后操作,根据组件方法,取消,确认 } Vue.prototype.$_messagesure = BackMsg } } export default MSG <file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' // 加载路由 vue.$route vue.$router import store from './store' // 加载vuex $store import PicPreview from 'vue-picture-preview-extend' // 加载preview 图片查看器 import utils from './common/js/utils.js' // 加载自定义公用类js库 import vMessage from './components/Message/index.js' // 加载自定义弹出信息,以插件形式安装。此方法单独以组件方法形式,是因为多了模板样式 import vMessageSure from './components/MessageSure/index.js' // 加载自定义弹出信息2 // import axios from 'axios' // import VueAxios from 'vue-axios' import myaxios from './common/axios/api' // 自定义封装的axios api层。 import './mock' // 加载模拟数据mock import '../static/css/reset.css' // 加载rest.css 和 icon.css import './common/css/icon.css' import FastClick from 'fastclick' // 解决移动端300毫秒点击延迟 FastClick.attach(document.body) Vue.use(PicPreview) Vue.use(utils) Vue.use(vMessage) // 使用案例header,info.vue Vue.use(vMessageSure) // 使用案例info.vue Vue.config.productionTip = false Vue.use(myaxios) // 全局使用this.$_axios.getWork().then() // Vue.use(VueAxios, axios) // Vue.prototype.$axios = axios // 挂载到原型上 /* eslint-disable no-new */ new Vue({ el: '#app', router: router, store: store, data: { eventHub: new Vue() }, components: { App }, template: '<App/>', created() { this.$router.push({path: '/projects'}) } })
77d13ce091408c8e92ae3d5a12eb024ee4cdb694
[ "JavaScript" ]
5
JavaScript
lk452584833/resume
467d225030e81cfb32050d270b22db0296402891
31635026b502aaa05ff0f1053ed3410a02f5d827
refs/heads/master
<file_sep>package oo.max.noteslistexample.list; import android.os.AsyncTask; import java.util.List; import oo.max.noteslistexample.apiclient.NotesApiClient; import oo.max.noteslistexample.apiclient.RetrofitApiClientFactory; import oo.max.noteslistexample.model.NoteListItem; import oo.max.noteslistexample.model.NotesListResponse; import retrofit2.Response; public class GetNotesListAsyncTask extends AsyncTask<Void, Void, List<NoteListItem>> { private final NotesApiClient notesApiClient; private final OnNotesDownloadListener onNotesDownloadListener; public GetNotesListAsyncTask(OnNotesDownloadListener onNotesDownloadListener) { this.onNotesDownloadListener = onNotesDownloadListener; notesApiClient = new RetrofitApiClientFactory().create(); } @Override protected List<NoteListItem> doInBackground(Void... voids) { try { Response<NotesListResponse> response = notesApiClient.getNotes().execute(); if(response.isSuccessful()) { return response.body().getData(); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(List<NoteListItem> noteListItems) { onNotesDownloadListener.notesDownloaded(noteListItems); } public interface OnNotesDownloadListener { void notesDownloaded(List<NoteListItem> noteListItems); } } <file_sep>package oo.max.noteslistexample.apiclient; import android.widget.TextView; import oo.max.noteslistexample.model.NotesListResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface NotesApiClient { @GET("/plugin/notes.list") Call<NotesListResponse> getNotes(); @GET("/plugin/notes.list") Call<NoteDetailRespons> getNoteDatails(@Query("id")String id); TextView=(TextView) final class NoteDetailRespons { } }<file_sep>package oo.max.noteslistexample.list; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import oo.max.noteslistexample.R; import oo.max.noteslistexample.model.NoteListItem; public class NotesListAdapter extends RecyclerView.Adapter<NotesListAdapter.NotesItemViewHolder> { private final Context context; private final List<NoteListItem> noteListItems; private final LayoutInflater layoutInflater; private final OnNoteClikedListner onNoteClikedListner; public NotesListAdapter(Context context, List<NoteListItem> noteListItems, OnNoteClikedListner onNoteClikedListner) { this.context = context; this.noteListItems = noteListItems; layoutInflater = LayoutInflater.from(context); this.onNoteClikedListner = onNoteClikedListner; } @Override public NotesItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = layoutInflater.inflate(R.layout.notes_list_item, parent, false); return new NotesItemViewHolder(view); } @Override public void onBindViewHolder(NotesItemViewHolder holder, int position) { NoteListItem noteListItem = noteListItems.get(position); holder.noteNameText.setText(noteListItem.getName()); holder.noteListItem = noteListItem; } @Override public int getItemCount() { return noteListItems.size(); } public static class NotesItemViewHolder extends RecyclerView.ViewHolder { TextView noteNameText; NoteListItem noteListItem; public NotesItemViewHolder(View itemView, final OnNoteClikedListner onNoteClikedListner) { super(itemView); noteNameText = (TextView) itemView.findViewById(R.id.note_name); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onNoteClikedListner.noteCliked(noteListItem); } }); } public NotesItemViewHolder(View view) { super(view); } } public interface OnNoteClikedListner { void noteCliked(NoteListItem noteListItem); } }
23b5af440d9553f564b08831acdd14a5414e0578
[ "Java" ]
3
Java
smtoudi/NotesListExample2017
b56dc825abb2c2bc94ab6a4016c33a6dbf15bbc5
22bcf13f76c029ab1f0874bafbf8c2786da652df
refs/heads/master
<file_sep># FirebaseExpenseApp ## Part A: ExpenseApp screen The main activity should start by displaying the ExpenseApp screen, with the following requirements: 1. When the app first starts, there should be no expenses added in the list. So it should display the ExpenseApp screen with a message, “There is no expense to show, Please add your expenses from the menu.”. 2. The list of expenses should be stored in Firebase realtime database. 3. The ExpenseApp screen should use a ListView/RecyclerView to display the list of expenses. a) Long press on an item should delete the expense from the list. It should update Firebase, and refresh the ListView to indicate this change. A Toast should be displayed having the message, “Expense Deleted”. b) Clicking on an expense item should display the ShowExpense screen, you should push the ExpenseApp screen on the screen stack. 4. Clicking on the add (+) icon should start the AddExpense screen. ## Part B: AddExpense screen This screen should enable user to add a new expense. You should complete the following tasks: 1. The user should be able to enter the expense name, category and amount. The app should take the current date as the expense date. This information should be stored in an Expense Object. 2. The categories should be in a selection pane . The categories should include are: Groceries, Invoice, Transportation, Shopping, Rent, Trips, Utilities and Other. 3. Clicking on “Add Expense” button should validate the user’s input and ensure that all the fields are provided. If any field is missing, display a Toast to indicate the missing field. If all the fields are provided correctly, save the fields as an Expense object, and add the new expense to Firebase. Then display the main activity with the added expense. ## Part C: ShowExpenses screen Implement the following requirements: 1. When the user clicks on an expense item in the ExpenseApp screen, the ShowExpenses screen should be started to show the details of selected expense item. 2. If the user clicks Edit Expense button, it should start EditExpense screen with preloaded values. 3. Upon clicking Close button, the screen should be closed and should navigate back to the ExpenseApp screen. ## Part D: EditExpense screen Implement the following requirements: 1. It is identical to the Add Expense screen with preloaded values for the particular expense. 2. If the user makes changes to the values, and clicks on Save button, it should update the corresponding values to Firebase, and get back to the main screen with updated values. <file_sep>package com.example.inclass11; import java.util.Date; import java.util.HashMap; public class Expense { String title; String cost; String category; String date; HashMap<String,Object> hmap; String documentId; public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Expense() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCost() { return cost; } public void setCost(String cost) { this.cost = cost; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Override public String toString() { return "Expense{" + "title='" + title + '\'' + ", cost=" + cost + ", category='" + category + '\'' + ", date=" + date + '}'; } public Expense(String title, String cost, String category, String date) { this.title = title; this.cost = cost; this.category = category; this.date = date; } HashMap<String,Object> toHashMap(){ hmap=new HashMap<>(); hmap.put("title",title); hmap.put("cost",cost); hmap.put("category",category); hmap.put("date",date); return hmap; } } <file_sep>package com.example.inclass11; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.ParseException; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.FirebaseFirestore; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class EditExpense extends AppCompatActivity { EditText et_expense,et_amount; Spinner spinner; Button btn_add,btn_cancel; String category; private FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_expense); setTitle("Edit Expense"); et_expense=findViewById(R.id.et_eenmae); et_amount=findViewById(R.id.et_eamount); spinner=findViewById(R.id.editspinner); btn_add=findViewById(R.id.btn_save); btn_cancel=findViewById(R.id.btn_ecancel); db = FirebaseFirestore.getInstance(); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(EditExpense.this, R.array.categories_array, android.R.layout.simple_spinner_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { category=parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); if (getIntent()!=null){ Bundle extras=getIntent().getExtras(); et_expense.setText(extras.getString("name")); et_amount.setText(String.valueOf(extras.getString("amount"))); int position=adapter.getPosition(extras.getString("category")); spinner.setSelection(position); } btn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (et_expense.getText().toString().equals("")) et_expense.setError("It can't be empty"); else if (et_amount.getText().toString().equals("")) et_amount.setError("It can't be empty"); else { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); Date dateobj = new Date(); db.collection("expenses") .document(getIntent().getExtras().getString("DocumentID")) .update("cost", et_amount.getText().toString(), "title", et_expense.getText().toString(), "category", category, "date", df.format(dateobj)) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d("Success", "Update Success"); } }); Intent i1 = new Intent(EditExpense.this, MainActivity.class); startActivity(i1); } } }); btn_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i2 = new Intent(EditExpense.this, MainActivity.class); startActivity(i2); } }); } } <file_sep>/* Assignment: Inclass11 Team members: <NAME>:801165622 <NAME>:801164383 */ package com.example.inclass11; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements ExpenseAdapter.InteractMainActivity { private FirebaseFirestore db; ImageView iv_add; TextView tv_current; RecyclerView recyclerView; ArrayList<Expense> expenses=new ArrayList<>(); RecyclerView.LayoutManager rv_layoutManager; RecyclerView.Adapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("Expense App"); db = FirebaseFirestore.getInstance(); iv_add=findViewById(R.id.imageView); tv_current=findViewById(R.id.tv_expenses); recyclerView=findViewById(R.id.expenselist); recyclerView.setVisibility(View.VISIBLE); recyclerView.setHasFixedSize(true); rv_layoutManager=new LinearLayoutManager(this); recyclerView.setLayoutManager(rv_layoutManager); iv_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1=new Intent(MainActivity.this,ExpensesActivity.class); startActivity(i1); } }); // Expense expense=new Expense("Walmart",67.00,"groceries",new Date()); // HashMap<String,Object> toSave=expense.toHashMap(); // CollectionReference cities = db.collection("expenses"); // db.collection("expenses") // .add(toSave) // .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { // @Override // public void onSuccess(DocumentReference documentReference) { // Log.d("demo","OnSuccess:Succesful"); // } // }) // .addOnFailureListener(new OnFailureListener() { // @Override // public void onFailure(@NonNull Exception e) { // Log.d("demo","onFailure"); // } // }); db.collection("expenses") .get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { for(DocumentSnapshot documentSnapshot:queryDocumentSnapshots){ Expense expense=documentSnapshot.toObject(Expense.class); expense.setDocumentId(documentSnapshot.getId()); Log.d("expense:",expense.getDocumentId()); expenses.add(expense); } if(expenses.size()!=0) tv_current.setVisibility(View.INVISIBLE); adapter=new ExpenseAdapter(expenses,MainActivity.this); recyclerView.setAdapter(adapter); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d("test","Failure"); } }); // db.collection("expense").document("zzdadSXZEu26Tdcu0Faf") // .delete() // .addOnSuccessListener(new OnSuccessListener<Void>() { // @Override // public void onSuccess(Void aVoid) { // Log.d("delete:","Succesful"); // } // }) // .addOnFailureListener(new OnFailureListener() { // @Override // public void onFailure(@NonNull Exception e) { // Log.d("delete:","Unsuccesful"); // } // }); } @Override public void deleteitem(final int position, final String documentID) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Delete an item?") .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { db.collection("expenses").document(documentID) .delete() .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d("test", "Delete succeeded!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e("test", "Delete unsuccessful: "+e.getMessage()); } }); expenses.remove(position); if(expenses.size()==0) tv_current.setVisibility(View.VISIBLE); adapter.notifyDataSetChanged(); } } ).show(); } } <file_sep>package com.example.inclass11; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ShowExpenseActivity extends AppCompatActivity { TextView tv_name,tv_category,tv_amount,tv_date; Button btn_edit,btn_close; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_expense); setTitle("Show Expense"); tv_name=findViewById(R.id.tv_dname); tv_amount=findViewById(R.id.tv_damount); tv_category=findViewById(R.id.tv_dcategory); tv_date=findViewById(R.id.tv_ddate); btn_edit=findViewById(R.id.btn_editexpense); btn_close=findViewById(R.id.btn_close); final Bundle extras=getIntent().getExtras(); tv_name.setText(extras.getString("name")); tv_category.setText(extras.getString("category")); String price=extras.getString("amount"); tv_amount.setText(String.valueOf(price)); tv_date.setText(extras.getString("date")); btn_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); btn_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1=new Intent(ShowExpenseActivity.this,EditExpense.class); i1.putExtras(extras); startActivity(i1); } }); } } <file_sep>package com.example.inclass11; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class ExpenseAdapter extends RecyclerView.Adapter<ExpenseAdapter.ViewHolder> { ArrayList<Expense> expenseArrayList=new ArrayList<>(); Context ctx; public static InteractMainActivity interact; public ExpenseAdapter(ArrayList<Expense> expenseArrayList, Context ctx) { this.expenseArrayList = expenseArrayList; this.ctx = ctx; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LinearLayout linearLayout=(LinearLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false); ViewHolder viewHolder=new ViewHolder(linearLayout); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { interact=(InteractMainActivity)ctx; holder.tv_name.setText(expenseArrayList.get(position).getTitle()); holder.tv_price.setText("$"+String.valueOf(expenseArrayList.get(position).getCost())); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle extras=new Bundle(); extras.putString("name",expenseArrayList.get(position).getTitle()); extras.putString("category",expenseArrayList.get(position).getCategory()); extras.putString("amount",expenseArrayList.get(position).getCost()); extras.putString("date",expenseArrayList.get(position).getDate().toString()); extras.putString("DocumentID",expenseArrayList.get(position).getDocumentId().toString()); Intent i1=new Intent(ctx,ShowExpenseActivity.class); i1.putExtras(extras); ctx.startActivity(i1); } }); holder.cardView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { interact.deleteitem(position,expenseArrayList.get(position).getDocumentId().toString()); return false; } }); } @Override public int getItemCount() { return expenseArrayList.size(); } public interface InteractMainActivity{ void deleteitem(int position,String document); } public class ViewHolder extends RecyclerView.ViewHolder { TextView tv_name,tv_price; CardView cardView; public ViewHolder(@NonNull View itemView) { super(itemView); tv_name=itemView.findViewById(R.id.tv_expensename); tv_price=itemView.findViewById(R.id.tv_amountmain); cardView=itemView.findViewById(R.id.cardView); } } }
967ef0a539cfd09d82de135b40fc67983c2d3e81
[ "Markdown", "Java" ]
6
Markdown
akhilmadhamshetty21/FirebaseExpenseApp
e88ab8dd0e1194cb2c2119271c70863118fc5a88
42e009814f420855d0062b563cf32bf9df6379bc
refs/heads/master
<file_sep><?php $name = urldecode($_POST['name']); $datetime=urldecode($_POST['datetime']); $imei=urldecode($_POST['imei']); $activityStatus=urldecode($_POST['activityStatus']); $InternetSpeed=urldecode($_POST['InternetSpeed']); $StreamStatus=urldecode($_POST['StreamStatus']); $con=mysqli_connect("localhost","root","root","bjp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"INSERT INTO userinfo (name,datetime,imei,activityStatus) VALUES ('$name','$datetime',$imei,$activityStatus)"); print "$name"; //echo "hello"+$datetime; $con1=mysqli_connect("localhost","root","root","bjp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query="SELECT * FROM recentuserinfo WHERE imei like '%$imei%'"; $result=mysqli_query($con1,$query); //echo "result".$result->num_rows; if($result->num_rows==0) { //echo "If"; $res=mysqli_query($con1,"INSERT INTO recentuserinfo VALUES ($imei,'$datetime',$activityStatus,'$InternetSpeed','$StreamStatus')"); mysqli_close($con1); } else { //echo "else"; $res=mysqli_query($con1,"UPDATE recentuserinfo SET datetime='".$datetime."',activestatus='".$activityStatus."',InternetSpeed='".$InternetSpeed."',StreamStatus='".$StreamStatus."' WHERE imei=$imei"); mysqli_close($con1); } ?> <file_sep><meta http-equiv="refresh" content="5" > <?php echo "<body style='background:#211213;'>"; function DisplayLatitude($strlatitude) { $latitude = (float)$strlatitude; if ($latitude > 0) { return $latitude . " N"; } else if ($latitude < -999.0) { return "Unknown location"; } else if ($latitude < 0) { $latitude = -1*$latitude; return $latitude . " S"; } else { return $latitude; } } function DisplayLongitude($strlongitude) { $longitude = (float)$strlongitude; if ($longitude > 0) { return $longitude . " E"; } else if ($longitude < -999.0) { return ""; } else if ($longitude < 0) { $longitude = -1*$longitude; return $longitude . " W"; } else { return $longitude; } } ?> <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ }); function sendPushNotification(id){ var data = $('form#'+id).serialize(); $('form#'+id).unbind('submit'); $.ajax({ url: "send_message.php", type: 'GET', data: data, beforeSend: function() { }, success: function(data, textStatus, xhr) { $('.txt_message').val(""); }, error: function(xhr, textStatus, errorThrown) { } }); return false; } </script> <style type="text/css"> .container{ width: 1100px; margin: 0 auto; padding: 0; } h1{ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 18px; color: #777; } h2{ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; color: #777; } table.users { float: left; font-size: 12px; font-style: normal; font-weigth: bold; list-style: none; border: 1px solid #dedede; padding: 10px; margin: 0 5px 5px 0; border-radius: 3px; -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.35); -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.35); box-shadow: 0 1px 1px rgba(0, 0, 0, 0.35); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #555; } table.users td { float: left; width: 200px; list-style: none; padding: 2px; margin: 0 2px 2px 0; border-radius: 2px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #555; } table.users labelHeading { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: bold; color: #393939; display: block; float: left; } table.users label { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: normal; color: #393939; display: block; float: left; } </style> </head> <body > <?php include_once 'db_server_functions.php'; $con=mysqli_connect("localhost","root","root","bjp"); $db = new DB_Functions(); $users = $db->getAllLoggedInUserInfo(); $userCnt = $db->getNumberOfUsersWithAccounts(); $active=$db->getAllAppActiveInfo() ; $no_of_ActiveUsers = mysql_num_rows($active); if ($users != false) $no_of_users = mysql_num_rows($users); else $no_of_users = 0; ?> <div class="container"> <div style="float: center; background-color: #DBDBDB;"> <table style="width:100%;height:10%;"> <tr bgcolor="#2E8B57"> <td style="padding-left: 5px; padding-bottom:3px; color:#FF6347; font-size:3em; font-weight:bold"><center>BJP Player</center> </td> </tr> </table> </div> <div style="float: center; background-color: #DBDBDB;"> <table width="40%"> <tr> <td> <h2>Number of Devices currently active </h2> </td> <td><h2><?php echo $no_of_ActiveUsers; ?></h2> </td> </tr> <tr> <td> <h2>Last Updated at </h2> </td> <td><h2><?php $date = date('Y-m-d H:i:s'); echo $date; ?></h2> </td> </tr> <tr> <td><h2>Currently Running</h2> </td> <td><h2><img src="green.png" width="25" height="25"></h2> </td> </tr> <tr> <td><h2>Currently Not Running</h2> </td> <td><h2><img src="yellow.png" width="25" height="25"></h2> </td> </tr> <tr> <td><h2>App Uninstalled</h2> </td> <td><h2><img src="red.png" width="25" height="25"></h2> </td> </tr> </table> </div> <!-- <h2>Number of Devices currently active : <?php echo $no_of_ActiveUsers; ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h2> <h2>Last Updated at : <?php $date = date('Y-m-d H:i:s'); echo $date; ?> <h2>Currently Running<img src="green.png" width="25" height="25"></h2> <h2>Currently Not Running<img src="yellow.png" width="25" height="25"></h2> <h2>App Uninstalled<img src="red.png" width="25" height="25"></h2> --> <?php if ($no_of_users > 0) { ?> <br><br> <div class="table"> <TABLE border=20 bgcolor=#d1be94 width="100%"> <TR BGCOLOR="#a1be94"> <TH>Device ID</TH><TH>Active Status</TH><TH>Location</TH><TH>NetSpeed</TH> <TH>Date Time </TH><TH>Reset Button</TH><TH>Add Details</TH><TH>StreamStatus</TH></TR> <tr> <?php session_start(); $cnt = 0; while ($row = mysql_fetch_array($users)) { $status=$row["activestatus"]; $InternetSpeed=$row["InternetSpeed"]; $datetimetable=$row["datetime"]; $imei=$row["imei"]; $StreamStatus=$row["StreamStatus"]; $dt = new DateTime(); $datetimesys= $dt->format('Y-m-d h:i:s a'); //calculating time diff for web status change $time1 = new DateTime($datetimesys); $time2 = new DateTime($datetimetable); $interval = $time1->diff($time2); $seconds=$interval->format('%s'); $minutes=$interval->format('%i'); $hours=$interval->format('%h'); $years=$interval->format('%Y'); $months=$interval->format('%m'); $days=$interval->format('%d'); //echo "years\t:".$years."<br>"; //echo "months\t:".$months."<br>"; //echo "days\t:".$days."<br>"; //echo "hours\t:".$hours."<br>"; //echo "minutes\t:".$minutes."<br>" ; //echo "second\t:".$seconds; $pKey = $row["imei"]; $cnt++; ?> <tr align="center"> <td><label><?php echo $row["imei"]; ?></label></td> <?php if($status==1||$status=="true"){?> <?php if($minutes>=2||$hours>=1){ $con1=mysqli_connect("localhost","root","root","bjp"); $res=mysqli_query($con1,"UPDATE recentuserinfo SET InternetSpeed='0',activestatus='deleted' WHERE imei='$imei'"); $s = "enered in if"; }else{ $s = "in else"; }?> <td ><label><?php if($s == "enered in if"){echo "<img src='red.png' style='width:30px;hieght:30px;' >";} else{echo "<img src='green.png' style='width:30px;hieght:30px;' >";}?></label></td> <?php } elseif($minutes>=2){ $con1=mysqli_connect("localhost","root","root","bjp"); $res=mysqli_query($con1,"UPDATE recentuserinfo SET InternetSpeed='0',StreamStatus='0',activestatus='deleted' WHERE imei='$imei'"); ?> <td ><label><?php echo "<img src='red.png' style='width:30px;hieght:30px;' >" ;?></label></td> <?php } elseif($status=="yellow") { ?> <td ><label><?php echo "<img src='yellow.png' style='width:30px;hieght:30px;' >" ; ?></label></td> <?php } ?> <?php $xx=$db->getAllEntriesFromNetTable($row["imei"]); if($row1 = mysql_fetch_array($xx)){ $town=$row1["town"]; } //echo $town; if($town == "") { ?> <td ><label>add Location</label></td> <?php } else{ ?> <td ><label><?php echo $town ; $town = "";?></label></td> <?php } ?> <td ><label><?php echo $InternetSpeed ; ?></label></td> <td><label><?php echo $row["datetime"] ?></label></td> <td><label><a href="sms.php?mobileNo=<?php echo $mobilenumber; ?>&imei=<?php echo $imei; ?> &town=<?php echo $town; ?>"> <button>Reset</button> </a></label></td> <td><label><a href="entry.php?imeiNo=<?php echo $row['imei']; ?>"> <button>addContact</button> </a></label></td> <td><label><?php echo $row["StreamStatus"] ?></label></td> </tr> <?php }//first while ending ?> <tr> </tr> </table> <?php } else { ?> <li> IBPlayer - No users currently active. (Total number of user accounts : <?php echo $userCnt; ?>) </li> <?php } ?> </div> </body> </html> <file_sep> <?php $imeiNo = $_GET['imeino']; //echo "asdfdsf".$imeiNo; ?> <!DOCTYPE html> <html> <head> <script type="text/javascript"> function validateMyForm() { // Create validation tracking variable var valid = true; var validationMessage; var name1 = document.getElementById('name').value; var pwd1=document.getElementById('pwd').value; var imei1=document.getElementById('imei').value; if((name1.length==0)&&(pwd1.length==0)){ // Validate all fields valid = false; alert("Please Enter all Details"); return false; } else if (document.getElementById('name').value.length == 0) { validationMessage = validationMessage + ' Name is missing\r\n'; valid = false; alert("Username is missing"); return false; } // Validate password else if (document.getElementById('pwd').value.length == 0) { validationMessage = validationMessage + 'Password is missing\r\n'; valid = false; alert("Password is missing"); return false; } else { window.location.href = 'http://172.16.58.3/bjp/validate.php?name='+name1+'&pwd='+pwd1+'&imei='+imei1; } }//validateMyForm() </script> </head> <body style='background:#d1be94;'> <div style="float: center; background-color: #DBDBDB;"> <table style="width:100%;height:10%;"> <tr bgcolor="#2E8B57"> <td style="padding-left: 5px; padding-bottom:3px; color:#FF6347; font-size:3em; font-weight:bold"><center>Welcome To Login</center> </td> </tr> </table> </div> <br /> <form action="http://183.82.9.60/bjp/validate.php" method="post"> <table align="center" style="width:10%;height:10%;"> <tr> <td>Name</td><td> <input type="text" name="user" id="name" value="" placeholder="please enter Username" required></td> </tr> <tr> <td>Password</td><td> <input type="<PASSWORD>" name="pwd" id="pwd" value="" placeholder="please enter Password" required></td> </tr> </table> <br> <table align="center"> <tr > <input type="hidden" id="imei" name= "imei" value="<?php echo $imeiNo; ?>"> <td ><input type="submit" value="Login"></td> </tr> </table> <br><br> <table align="center"> <tr> <td><?php if($_GET['login_fail'] == "faild") { echo "Login Failed Please try again! "; } ?></td> </tr> </table> </form> </div> </body> </html> <file_sep> <?php session_start(); $imeiNo = $_SESSION['imeiNo']; //echo "asdfdsf".$imeiNo; ?> <!DOCTYPE html> <html> <head> <script type="text/javascript"> function validateMyForm() { // Create validation tracking variables var valid = true; var validationMessage; var name1 = document.getElementById('name').value; var city1=document.getElementById('city').value; var mobilenum=document.getElementById('mnumber').value; var countryname=document.getElementById('country').value; var imei1=document.getElementById('imei').value; if((name1.length==0)&&(mobilenum.length==0)&&(city1.length==0)){ // Validate all fields valid = false; alert("Please Enter all Details"); return false; } else if (document.getElementById('name').value.length == 0) { validationMessage = validationMessage + ' Name is missing\r\n'; valid = false; alert("Name is missing"); return false; } // Validate mobile number else if (document.getElementById('mnumber').value.length == 0) { validationMessage = validationMessage + 'Mobile Number is missing\r\n'; valid = false; alert("Mobile Number is missing"); return false; } // Validate city name else if (document.getElementById('city').value.length == 0) { validationMessage = validationMessage + 'City name is missing\r\n'; valid = false; alert("City name is missing"); return false; } else { window.location.href = 'http://172.16.31.10/bjp/addcontact.php?name='+name1+'&mnum='+mobilenum +'&cityname='+city1+'&cname='+countryname+'&imei='+imei1; } }//validateMyForm() </script> </head> <body style='background:#d1be94;'> <br /> <div style="float: center; background-color: #DBDBDB;"> <table style="width:100%;height:10%;"> <tr bgcolor="#2E8B57"> <td style="padding-left: 5px; padding-bottom:3px; color:#FF6347; font-size:3em; font-weight:bold"><center>Add Contact Details</center> </td> </tr> </table> </div> <form onsubmit="return false;"> <table align="center" style="width:10%;height:10%;"> <tr> <td>Name</td><td> <input type="text" name="user" id="name" value="" placeholder="please enter Name" ></td> </tr> <tr> <td>MobileNumber</td><td> <input type="text" name="mnumber" id="mnumber" value="" placeholder="please enter mobile number" ></td> </tr> <tr> <td>City</td><td> <input type="text" name="city" id="city" value="" placeholder="please enter City" ></td> </tr> <tr><label for="name"><td>Country</td></label><td><select name="country" id="country" > <option value="India">India</option> <option value="France">France</option> <option value="Italy">Italy</option> </tr> </td></select> </table> <br> <table align="center"> <tr > <input type="hidden" id="imei" name= "imei" value="<?php echo $imeiNo; ?>"> <td ><input type="submit" value="Save" onClick="validateMyForm();"></td> </tr> </table> </form> </div> </body> </html> <file_sep><?php $imeiNo = $_GET['imeiNo']; //echo $imeiNo; ?> <!DOCTYPE html> <html> </head> <body style='background:#d1be94;'> <div style="float: center; background-color: #DBDBDB;"> <table style="width:100%;height:10%;"> <tr bgcolor="#2E8B57"> <td style="padding-left: 5px; padding-bottom:3px; color:#FF6347; font-size:3em; font-weight:bold"><center>WelCome To BJP Player</center> </td> </tr> </table> </div> <br><br><br><br> <table align="center"> <tr > <input type="hidden" id="imei" name= "imei" value="<?php echo $imeiNo; ?>"> <td><a href="login.php?imeino=<?php echo $imeiNo ?>"> <button>Login</button> </tr> </table> <br> <table align="center"> <tr> <td><a href="createuser.php?imeiNo=<?php echo $row['imei']; ?>"> <button>Create User</button> </tr> </table> </body> </head> </html> <file_sep><?php $x='2010-07-29 12:43:54'; $y='2010-07-22 01:23:42'; $time1 = new DateTime($x); $time2 = new DateTime($y); $interval = $time1->diff($time2); $seconds=$interval->format('%s'); $minuts=$interval->format('%i'); $hours=$interval->format('%h'); $years=$interval->format('%Y'); $months=$interval->format('%m'); $days=$interval->format('%d'); echo "years\t:".$years."<br>"; echo "months\t:".$months."<br>"; echo "days\t:".$days."<br>"; echo "hours\t:".$hours."<br>"; echo "minutes\t:".$minuts."<br>" ; echo "second\t:".$seconds; ?> <file_sep><?php $name = $_POST['user']; $mobilenumber = $_GET['mobileNo']; $town = $_POST['town']; $country = $_POST['country']; $imei = $_GET['imei']; $deviceName = $imei; //Multiple mobiles numbers seperated by comma //echo $deviceName."<br>"; $mobileNumber = $mobilenumber; //echo $mobileNumber; $mobilemsg="IB_start"; if(($deviceName == "") && ($mobilenumber == "") ){ echo "Please Add your contact Details First"; } else { echo "DeviceName ".$deviceName."<br>"; echo "Message ".$mobilemsg."<br>"; echo "MobileNumber ".$mobileNumber."<br>"; } //Your authentication key $authKey = "62264A7RDpradwshV52d3be3d"; //Sender ID,While using route4 sender id should be 6 characters long. $senderId = "octo"; //Your message to send, Add URL endcoding here. $message = urlencode($mobilemsg); //Define route $route = "1"; //Prepare you post parameters $postData = array( 'authkey' => $authKey, 'mobiles' => $mobileNumber, 'message' => $message, 'sender' => $senderId, 'route' => $route ); //API URL $url="http://india.msg91.com/api/sendhttp.php"; // init the resource $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData //,CURLOPT_FOLLOWLOCATION => true )); //get response $output = curl_exec($ch); curl_close($ch); echo $output."Message has been sent to Device";?> sleep(1000); <script> location.replace("http://www.bookingslot.com/ResetDevice.php"); </script> <file_sep><?php $username=$_GET['name']; $town = $_GET['cityname']; $email = $_GET['email']; $password=$_GET['pwd']; $imei = $_GET['imei']; //echo $name; //echo $imei."<br>I am in SMS"; $con1=mysqli_connect("localhost","root","root","bjp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query="SELECT * FROM createuser WHERE username like '%$username%'"; $result=mysqli_query($con1,$query); if($result->num_rows==0) { //echo "in if"; $res=mysqli_query($con1,"INSERT INTO createuser (username,email,city,password,imei) VALUES ('$username','$email','$town','$password','$imei')"); echo "Details Saved"; mysqli_close($con); } else { echo "User Already Exist!"; } ?> <file_sep><?php session_start(); $name=$_POST['user']; $pwd = $_POST['pwd']; $im=$_POST['imei']; $_SESSION['imeiNo'] = $im; //echo "Details Saved<br>"; //echo $_SESSION['imeiNo']."<br>"; //echo $pwd."<br>"; $con1=mysqli_connect("localhost","root","root","bjp"); include_once 'db_server_functions.php'; $db = new DB_Functions(); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query="SELECT password FROM createuser WHERE username like '%$name%'"; $result=mysqli_query($con1,$query); $xx=$db->getAllEntriesFromCreateTable($name); while ($row1 = mysql_fetch_array($xx)) { $password=$<PASSWORD>["<PASSWORD>"]; //echo $password; } if($password==$pwd) { echo "Login Success"; ?> <script> location.replace("http://1172.16.31.10/bjp/view_users.php"); </script> <?php } else { //echo "Login Failed"; ?> <script> location.replace("http://172.16.31.10/bjp/login.php?login_fail=faild"); </script> <?php } ?> <file_sep><?php class DB_Functions { private $passwordSeed = "<PASSWORD>"; private $db; //put your code here // constructor function __construct() { include_once './db_connect.php'; // connecting to database $this->db = new DB_Connect(); $this->db->connect(); } // destructor function __destruct() { } public function isAuthorized($email) { $result = mysql_query("SELECT Authorized FROM Users where email='$email'"); $returned = mysql_fetch_array($result); if ($returned[0] == "1") { return true; } else { return false; } } private function decryptPassword($email,$password) { $result = mysql_query("SELECT AES_DECRYPT(encrypted_password,CONCAT('$email','$this->passwordSeed')) FROM Users WHERE email='$email'"); $returned = mysql_fetch_array($result); return $returned[0]; } public function validateUser($username,$password) { $result = mysql_query("SELECT Username, Email FROM Users where username='$username'"); $returned = mysql_fetch_array($result); if ($username == $returned[0]) { $email = $returned[1]; $decryptedPassword = $this->decryptPassword($email,$password); if ($decryptedPassword == $password) { return json_encode(array('Result' => 'AOK', 'Reason' => '')); } else { return json_encode(array('Result' => 'NOK', 'Reason' => 'Bad user credentials')); } } else { return json_encode(array('Result' => 'NOK', 'Reason' => 'User does not exists')); } } public function BooleanResultValidateUser($username,$password) { $result = mysql_query("SELECT Email FROM Users where username='$username'"); if ($result) { $returned = mysql_fetch_array($result); $email = $returned[0]; $decryptedPassword = $this->decryptPassword($email,$password); if ($decryptedPassword == $password) { return true; } else { return false; } } } public function updatePosition($username, $password, $dateTime, $latitude, $longitude, $heading, $speed) { if ($this->validateUser($username,$password)) { if ($speed == 0.0) { $heading = -1.0; } $result = mysql_query("UPDATE Users SET lastUpdatedAt='$dateTime', latitude=$latitude, longitude=$longitude, speed=$speed, heading=$heading WHERE username='$username'"); if ($result) { return json_encode(array('Result' => 'OK', 'Reason' => '')); } else { return json_encode(array('Result' => 'NOK', 'Reason' => 'Unknown Reason')); } } else { return json_encode(array('Result' => 'NOK', 'Reason' => 'Bad credentials')); } } public function getRegId($email, $password) { $validUser = $this->validateUser($email,$password); if ($validUser == "NOK") { return "NOK"; } $result = mysql_query("SELECT gcm_regid FROM Users where email='$email'"); $returned = mysql_fetch_array($result); return $returned[0]; } public function AddRequest($eventName ,$eventDescription, $eventExpiry, $eventAddress,$latitude, $longitude, $notificationDistance, $recordDistance) { $sql = "INSERT INTO Request(RequestDateTime,EventName,EventDescription,EventExpiry,Address,Latitude,Longitude,NotificationDistance,RecordDistance) VALUES (NOW(),'$eventName','$eventDescription','$eventExpiry','$eventAddress',$latitude,$longitude,$notificationDistance,$recordDistance)"; //error_log($sql,0); $result = mysql_query($sql); error_log($result,0); return $result; } public function getAllContactsForUser($username) { $response_array = Array(); $result = mysql_query("SELECT FriendUsername FROM FriendList WHERE Username='$username' ORDER BY FriendUsername"); while($row = mysql_fetch_array($result)){ $result2 = mysql_query("SELECT Fullname, Email FROM Users WHERE Username='$row[0]'"); $row2 = mysql_fetch_array($result2); $row_array['Username'] = $row[0]; $row_array['Fullname'] = $row2[0]; $row_array['Email'] = $row2[1]; array_push($response_array,$row_array); } echo json_encode($response_array); } public function getAllGroupsForUser($username) { $response_array = Array(); $result = mysql_query("SELECT Groupname, GroupDescription FROM GroupNames WHERE Username='$username' ORDER BY Groupname"); while($row = mysql_fetch_array($result)){ $groupname = $row[0]; $groupdesc = $row[1]; $result = mysql_query("SELECT FriendList.FriendUsername FROM FriendList,GroupNames WHERE GroupNames.Groupname='$groupname' ORDER BY FriendList.FriendUsername"); while($row = mysql_fetch_array($result)){ $username = $row[0]; $result2 = mysql_query("SELECT Fullname, Email FROM Users WHERE Username='$row[0]'"); $row2 = mysql_fetch_array($result2); $row_array['Groupname'] = $groupname; $row_array['Groupdesc'] = $groupdesc; $row_array['FriendUsername'] = $username; $row_array['FriendFullname'] = $row2[0]; array_push($response_array,$row_array); } } echo json_encode($response_array); } public function getAllAppActiveInfo() { //$result = mysql_query("select name, datetime, imei,activityStatus FROM userinfo Where activityStatus='1'"); old $result = mysql_query("select * FROM recentuserinfo WHERE activestatus='true'"); return $result; } public function getAllEntriesFromNetTable($x) { $result = mysql_query("select town from userdetails where imei='$x' "); return $result; } public function getAllEntriesFromCreateTable($x) { $result = mysql_query("select password from createuser where username like'%$x%' "); return $result; } public function getAllLoggedInUserInfo() { //$result = mysql_query("select name, datetime, imei,activityStatus FROM userinfo Where activityStatus='1'"); old $result = mysql_query("select * FROM recentuserinfo"); return $result; } public function getNumberOfUsersWithAccounts() { $result = mysql_query("select count(*) from recentuserinfo"); $row = mysql_fetch_array($result); return $row[0]; } } ?>
1042d17cc3e3b942a8fe87749ec4c1e1b7b3638e
[ "PHP" ]
10
PHP
sumanpulaib/BJPPlayer
62f74d43e965dbe672ab0ac32e4dbfbe938ff480
115c1904bc122a332bd67658c32e42e279ba5c1b
refs/heads/master
<file_sep>import React, {useState} from 'react'; import ExpenseForm from './ExpenseForm'; import './NewExpense.css' const NewExpense = (props) => { const [isModifying, setIsModifying] = useState(false); const saveExpenseDataHandler = (enteredExpenseData) => { const expenseData = { ...enteredExpenseData, id: Math.random().toString() }; props.addExpense(expenseData); setIsModifying(false); }; const startEditingHandler = () => { setIsModifying(true); }; const cancelEditingHandler = () => { setIsModifying(false); }; return ( <div className='new-Expense'> {!isModifying && <button onClick={startEditingHandler}>Lisää uusi kulu</button>} {isModifying && ( <ExpenseForm onSaveExpenseData={saveExpenseDataHandler} isCanceling={cancelEditingHandler}/> )} </div> ); }; export default NewExpense;<file_sep>import React, { useState } from 'react'; import NewExpense from './components/NewExpense/NewExpense'; import Expenses from './components/Expenses/Expenses'; const KuluListaa = [ { id: 'a1', title: 'Kirjat', amount: 45, date: new Date(2021, 4, 15), }, { id: 'a2', title: 'Moottoripyörävaatteet', amount: 70, date: new Date(2020, 5, 16), }, { id: 'a3', title: 'Ruuat', amount: 35, date: new Date(2020, 6, 17), }, { id: 'a4', title: 'Moottoripyörän tarvikkeet', amount: 100, date: new Date(2019, 7, 18), }, { id: 'a5', title: 'Moottoripyörän tarvikkeet', amount: 17, date: new Date(2019, 8, 18), }, { id: 'a6', title: 'Moottoripyörän tarvikkeet', amount: 90, date: new Date(2019, 9, 18), }, ]; const App = () => { const [expenses, setExpenses] = useState(KuluListaa); const addExpenseHandler = (expense) => { setExpenses(prevExpenses => { return [expense, ...prevExpenses]; }); }; return ( <div> <NewExpense addExpense={addExpenseHandler}/> <Expenses items={expenses} /> </div> ); }; export default App; <file_sep>import FullCalendar from '@fullcalendar/react'; import dayGridPlugin from '@fullcalendar/daygrid'; import timeGridPlugin from '@fullcalendar/timegrid'; import interactionPlugin from '@fullcalendar/interaction'; function Calendar() { return( <div> <FullCalendar headerToolbar = {{ start: 'title', center: 'dayGridMonth, timeGridWeek, timeGridDay', end: 'today prev,next' }} plugins={[dayGridPlugin, timeGridPlugin,interactionPlugin]} initialView="dayGridMonth" /> </div> ) } export default Calendar;
dfe16f642585fee6e1b21faec604c203b6add779
[ "JavaScript" ]
3
JavaScript
JouniGitti/Kulut
3d3f4c0ff5708ae69d67edd7aee078946174d91c
14a4d5b71546df9f8aa282faa78af7ba4a8dcb94
refs/heads/master
<repo_name>liangl/Demo<file_sep>/Keyyum/Keyyum/Keyyum.DAL/UserRepository.cs using Keyyum.IDAL; using Keyyum.Models; using System.Linq; namespace Keyyum.DAL { class UserRepository:BaseRepository<User>,InterfaceUserRepository { } } <file_sep>/Keyyum/Keyyum/Keyyum.BLL/UserService.cs using Keyyum.DAL; using Keyyum.IBLL; using Keyyum.Models; using System.Linq; namespace Keyyum.BLL { public class UserService:BaseService<User>,InterfaceUserService { public UserService() : base(RepositoryFactory.UserRepository) { } public bool Exist(string userName) { return CurrentRepository.Exist(u => u.UserName == userName); } public User Find(System.Guid userID) { return CurrentRepository.Find(u => u.UserID ==userID ); } public User Find(string userName) { return CurrentRepository.Find(u => u.UserName == userName); } public IQueryable<User> FindPageList(int pageIndex, int pageSize, out int totalRecord, int order) { bool _isAsc = true; string _orderName = string.Empty; switch (order) { case 0: _isAsc = true; _orderName = "UserID"; break; case 1: _isAsc = false; _orderName = "UserID"; break; case 2: _isAsc = true; _orderName = "RegistrationTime"; break; case 3: _isAsc = false; _orderName = "RegistrationTime"; break; case 4: _isAsc = true ; _orderName = "LoginTime"; break; case 5: _isAsc = false ; _orderName = "LoginTime"; break; default : _isAsc = false ; _orderName = "UserID"; break; } return CurrentRepository.FindPageList(pageIndex, pageSize, out totalRecord, u => true, _orderName, _isAsc); } } } <file_sep>/Keyyum/Keyyum/Keyyum.IDAL/InterfaceBaseRepository.cs using System; using System.Linq; using System.Linq.Expressions; namespace Keyyum.IDAL { /// <summary> /// 接口基类 /// <remarks > /// 创建:2014.03.17<br/> /// 修改: /// </remarks> /// </summary> /// <typeparam name="T">类型</typeparam> public interface InterfaceBaseRepository<T> { /// <summary> /// 添加 /// </summary> /// <param name="entity">数据实体</param> /// <returns>添加后的数据实体</returns> T Add(T entity); /// <summary> /// 查询记录数 /// </summary> /// <param name="predicate">条件表达式</param> /// <returns>记录数</returns> int Count(Expression<Func<T, bool>> predicate); /// <summary> /// 更新 /// </summary> /// <param name="entity">数据实体</param> /// <returns>是否成功</returns> bool Update(T entity); bool Delete(T entity); bool Exist(Expression<Func<T,bool>> anyLambda); T Find(Expression<Func<T, bool>> whereLambda); IQueryable<T> FindList(Expression<Func<T, bool>> whereLamdba,string orderName, bool isAsc); IQueryable<T> FindPageList(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba,string orderName, bool isAsc); } } <file_sep>/Keyyum/Keyyum/Keyyum.BLL/BaseService.cs using Keyyum.IBLL; using Keyyum.IDAL; namespace Keyyum.BLL { public abstract class BaseService<T>:InterfaceBaseService<T> where T:class { // private IDAL.InterfaceUserRepository interfaceUserRepository; protected InterfaceBaseRepository<T> CurrentRepository { get; set; } public BaseService(InterfaceBaseRepository<T> currentRepository) { CurrentRepository = currentRepository; } //public BaseService(IDAL.InterfaceUserRepository interfaceUserRepository) //{ // // TODO: Complete member initialization // this.interfaceUserRepository = interfaceUserRepository; //} public T Add(T entity) { return CurrentRepository.Add(entity); } public bool Update(T entity) { return CurrentRepository.Update(entity); } public bool Delete(T entity) { return CurrentRepository.Delete(entity); } } } <file_sep>/Keyyum/Keyyum/Keyyum.Models/User.cs using System; using System.ComponentModel.DataAnnotations; namespace Keyyum.Models { /// <summary> /// 用户模型 /// <remarks > /// 创建:2014年3月17日 /// 修改: /// </remarks> /// </summary> public class User { [Key] public Guid UserID { get; set; } /// <summary> /// 用户名 /// </summary> [Required(ErrorMessage = "必填")] [StringLength(20, MinimumLength = 4, ErrorMessage = "{1}到{0}个字符")] [Display(Name = "用户名")] public string UserName { get; set; } /// <summary> /// 用户组ID /// </summary> //[Required(ErrorMessage = "必填")] //[Display(Name = "用户组ID")] // public Guid GroupID { get; set; } /// <summary> /// 显示名称 /// </summary> [Required(ErrorMessage = "必填")] [StringLength(20, MinimumLength = 2, ErrorMessage = "{1}到{0}个字符")] [Display(Name = "显示名")] public string DisplayName { get; set; } /// <summary> /// 密码 /// </summary> [Required(ErrorMessage = "必填")] [Display(Name = "密码")] [StringLength(20, MinimumLength = 6, ErrorMessage = "密码必须为{1}到{0}个字符")] [DataType(DataType.Password)] public string Password { get; set; } /// <summary> /// 邮箱 /// </summary> /// [Required(ErrorMessage = "必填")] [Display(Name = "邮箱")] [DataType(DataType.EmailAddress)] public string Email { get; set; } /// <summary> /// 用户状态<br/> /// 0正常,1锁定,2未通过邮件验证,3未通过管理员 /// </summary> public int Status { get; set; } /// <summary> /// 注册时间 /// </summary> public DateTime RegistrationTime { get; set; } /// <summary> /// 上次登陆时间 /// </summary> public DateTime LoginTime { get; set; } /// <summary> /// 上次登陆IP地址 /// </summary> /// [Display(Name="上次登陆的IP地址")] public string LoginIP { get; set; } public virtual Role Group { get; set; } } } <file_sep>/Keyyum/Keyyum/Keyyum.DAL/RepositoryFactory.cs using Keyyum.IDAL; namespace Keyyum.DAL { public static class RepositoryFactory { public static InterfaceUserRepository UserRepository { get { return new UserRepository(); } } } } <file_sep>/Keyyum/Keyyum/Keyyum.IBLL/InterfaceBaseService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Keyyum.IBLL { public interface InterfaceBaseService<T> where T:class { T Add(T entity); bool Update(T entity); bool Delete(T entity); } } <file_sep>/Keyyum/Keyyum/Keyyum.IDAL/InterfaceUserRepository.cs using Keyyum.Models; namespace Keyyum.IDAL { /// <summary> /// 用户接口 /// <remarks >创建:2014.03.17</remarks> /// </summary> public interface InterfaceUserRepository:InterfaceBaseRepository<User> { } } <file_sep>/Keyyum/Keyyum/Keyyum.DAL/ContextFactory.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace Keyyum.DAL { public class ContextFactory { public static KeyyumDbContext GetCurrentContext() { KeyyumDbContext _nContext = CallContext.GetData("KeyyumContext") as KeyyumDbContext; if (_nContext == null) { _nContext = new KeyyumDbContext(); CallContext.SetData("KeyyumContext", _nContext); } return _nContext; } } } <file_sep>/Keyyum/Keyyum/Keyyum.DAL/KeyyumDbContext.cs using Keyyum.Models; using System.Data.Entity; namespace Keyyum.DAL { public class KeyyumDbContext:DbContext { public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<UserConfig> UserConfig { get; set; } public DbSet<UserRoleRelation> UserRoleRelations { get; set; } public KeyyumDbContext() : base("DefaultConnection") { Database.CreateIfNotExists(); } } }
b78837ce8a623fa477b4c74d9fec9b1b4f5dca53
[ "C#" ]
10
C#
liangl/Demo
dd39cfcb20b4b97bcc89d1fb73a3812e290aef85
2a1537cda2e22db9fc3d8a8f35833603b296c3c9
refs/heads/master
<repo_name>ibbocus/Terraform_AWS<file_sep>/playbooks/install_ansible.sh #!/bin/bash sudo apt update -y sudo apt install software-properties-common -y sudo apt-add-repository --yes --update ppa:ansible/ansible sudo apt install ansible sudo apt install python -y sudo apt install python-pip -y sudo pip install --upgrade pip -y sudo pip install boto cd /etc/ansible echo "[web] 192.168.3.11 ansible_connection=ssh ansible_ssh_user=vagrant ansible_ssh_pass=<PASSWORD>" >> hosts echo "[db] 172.16.17.32 ansible_connection=ssh ansible_ssh_user=vagrant ansible_ssh_pass=<PASSWORD>" >> hosts echo "[aws] 192.168.33.12 ansible_connection=ssh ansible_ssh_user=vagrant ansible_ssh_pass=<PASSWORD>" >> hosts <file_sep>/terraform/install_terraform.sh #!/bin/bash sudo wget -q -O - https://tjend.github.io/repo_terraform/repo_terraform.key | sudo apt-key add - sudo echo 'deb [arch=amd64] https://tjend.github.io/repo_terraform stable main' >> /etc/apt/sources.list.d/terraform.list sudo apt-get update sudo apt-get install terraform cd terraform/ terraform init <file_sep>/run_vagrant.sh #!/bin/bash vagrant up <file_sep>/terraform/run_terraform.sh #!/bin/bash cd terraform terraform plan terraform apply -auto-approve echo "export App_ip=$(terraform output app_ip)" >> ./.bashrc echo "export DB_ip=$(terraform output db_ip)" >> ./.bashrc echo "export Bastion_ip=$(terraform output bastion_ip)" >>./.bashrc source ~/.bashrc <file_sep>/Vagrantfile # Install required plugins required_plugins = ["vagrant-hostsupdater", "vagrant-berkshelf"] required_plugins.each do |plugin| unless Vagrant.has_plugin?(plugin) # User vagrant plugin manager to install plugin, which will automatically refresh plugin list afterwards puts "Installing vagrant plugin #{plugin}" Vagrant::Plugin::Manager.instance.install_plugin plugin puts "Installed vagrant plugin #{plugin}" end end def set_env vars command = <<~HEREDOC echo "Setting Environment Variables" source ~/.bashrc HEREDOC vars.each do |key, value| command += <<~HEREDOC if [ -z "$#{key}" ]; then echo "export #{key}=#{value}" >> ~/.bashrc fi HEREDOC end return command end Vagrant.configure("2") do |config| config.vm.define "aws" do |aws| aws.vm.box = "ubuntu/xenial64" aws.vm.network "private_network", ip: "192.168.33.12" aws.hostsupdater.aliases = ["development.local"] aws.vm.synced_folder "app/", "/home/vagrant/app" aws.vm.synced_folder "playbooks/", "/home/vagrant/playbooks" aws.vm.synced_folder "terraform/", "/home/vagrant/terraform" aws.vm.synced_folder "key/", "/home/vagrant/key/" aws.vm.provision "shell", path: "terraform/run_terraform.sh", privileged: false aws.vm.provision "shell", inline: set_env({ AWS_ACCESS_KEY: $AWS_ACCESS_KEY_ID }), privileged: false aws.vm.provision "shell", inline: set_env({ AWS_SECRET_KEY: $AWS_SECRET_KEY }), privileged: false end end
c0620d54425eaf27c5e5707ece0d919b1735f7ba
[ "Ruby", "Shell" ]
5
Shell
ibbocus/Terraform_AWS
c5253e62d37cbeb9ee2d309db7d3763111a1dcd6
1bf3179e6e8ad055c151cb27ed1764b6991ab80e
refs/heads/master
<file_sep><?php /** * 接收另一个域名传递过来的文件和图片 */ define('ROOT_PATH', str_replace('uploadFile.php', '', str_replace('\\', '/', __FILE__))); $access_key = ""; $cus_remote_file_key = isset($_POST['access_key']) ? $_POST['access_key'] : ""; if($access_key != $cus_remote_file_key){ exit("FAILED"); } //允许的文件类型 $allow_file_types = '|GIF|JPG|JPEG|PNG|BMP|DOC|DOCX|XLS|XLSX|PPT|PPTX|MID|WAV|ZIP|RAR|PDF|TXT|'; //允许的操作来源 $promote_type_list = array('ueditor', 'gallery'); $promote_type = isset($_POST['promote_type']) ? trim($_POST['promote_type']) : ''; if(!in_array($promote_type, $promote_type_list)){ exit("FAILED"); } $file_dir = isset($_POST['dir']) ? trim($_POST['dir']) : ''; if(!$file_dir){ exit("FAILED"); }else{ if($promote_type == 'ueditor'){ $file_dir = str_replace('../../../', '/', $file_dir); }elseif ($promote_type == 'gallery') { $file_dir = str_replace('../', '/', $file_dir); } } $file = isset($_FILES['file']) ? $_FILES['file'] : ''; if(!$file){ exit("FAILED"); } logResult(var_export($_POST, true)); if ( (isset($file['error']) && $file['error'] == 0) || (!isset($file['error']) && isset($file['tmp_name']) && $file['tmp_name'] != 'none') ){ $tmpname = $file['tmp_name']; if(is_uploaded_file($tmpname)) { // 检查文件格式 if (!check_file_type($tmpname, $file['name'], $allow_file_types)){ exit("FAILED"); } if($file['size'] > 4096000){ exit("FAILED"); #文件过大 } //检查目录是否存在,不存在则创建 if(!file_exists('.'.$file_dir)){ mkdir('.'.$file_dir, 0777, true); //允许创建多级目录 } //移动文件 $target_file = '.'.$file_dir.'/'.$file['name']; if(!move_uploaded_file($file['tmp_name'], $target_file)){ exit("FAILED"); }else{ exit("SUCCESS"); } }else{ exit("FAILED"); } } //未知错误 exit("FAILED"); /** * 检查文件类型 * * @access public * @param string filename 文件名 * @param string realname 真实文件名 * @param string limit_ext_types 允许的文件类型 * @return string */ function check_file_type($filename, $realname = '', $limit_ext_types = '') { if ($realname) { $extname = strtolower(substr($realname, strrpos($realname, '.') + 1)); } else { $extname = strtolower(substr($filename, strrpos($filename, '.') + 1)); } if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false) { return ''; } $str = $format = ''; $file = @fopen($filename, 'rb'); if ($file) { $str = @fread($file, 0x400); // 读取前 1024 个字节 @fclose($file); } else { if (stristr($filename, ROOT_PATH) === false) { if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' || $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' || $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' || $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' || $extname == 'xlsx' || $extname == 'docx') { $format = $extname; } } else { return ''; } } if ($format == '' && strlen($str) >= 2 ) { if (substr($str, 0, 4) == 'MThd' && $extname != 'txt') { $format = 'mid'; } elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav') { $format = 'wav'; } elseif (substr($str ,0, 3) == "\xFF\xD8\xFF") { $format = 'jpg'; } elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt') { $format = 'gif'; } elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") { $format = 'png'; } elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt') { $format = 'bmp'; } elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt') { $format = 'swf'; } elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0") { // D0CF11E == DOCFILE == Microsoft Office Document if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc') { $format = 'doc'; } elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls') { $format = 'xls'; } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt') { $format = 'ppt'; } } elseif (substr($str ,0, 4) == "PK\x03\x04") { if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx') { $format = 'docx'; } elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx') { $format = 'xlsx'; } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx') { $format = 'pptx'; }else { $format = 'zip'; } } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt') { $format = 'rar'; } elseif (substr($str ,0, 4) == "\x25PDF") { $format = 'pdf'; } elseif (substr($str ,0, 3) == "\x30\x82\x0A") { $format = 'cert'; } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt') { $format = 'chm'; } elseif (substr($str ,0, 4) == "\x2ERMF") { $format = 'rm'; } elseif ($extname == 'sql') { $format = 'sql'; } elseif ($extname == 'txt') { $format = 'txt'; } } if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false) { $format = ''; } return $format; } function logResult($word='') { $fp = fopen('./logs/'.date("Ymd").".txt","a"); flock($fp, LOCK_EX) ; fwrite($fp,"执行日期:".strftime("%Y-%m-%d %H:%M:%S",time())."\n".$word."\n"); flock($fp, LOCK_UN); fclose($fp); } ?> <file_sep><?php /** * 将图片或文件上传到图片服务器 */ class CustomRemoteFile { //配置 var $cus_remote_file_target = "http://images.site.com/uploadFile.php"; //服务器地址 var $cus_remote_file_key = ""; //access_key /** * 上传百度编辑器图片 */ function cus_remote_editor_file($cus_remote_file_path){ $cus_remote_file_re = $this->curl_post_contents($this->cus_remote_file_target, array('file'=>'@'.realpath($cus_remote_file_path), 'dir'=>dirname($cus_remote_file_path), 'access_key'=>$this->cus_remote_file_key, 'promote_type'=>'ueditor')); if($cus_remote_file_re == "SUCCESS"){ return str_replace('../../../', '/', $cus_remote_file_path); }else{ return "http://".$_SERVER['HTTP_HOST']."/includes/ueditor/php/".$cus_remote_file_path; } } /** * 上传商品编辑中的相册 */ function cus_remote_gallery_file($cus_remote_file_path){ $data = array( 'file' => '@'.realpath($cus_remote_file_path), 'dir' => dirname($cus_remote_file_path), 'access_key'=>$this->cus_remote_file_key, 'promote_type'=>'gallery', ); return $this->curl_post_contents($this->cus_remote_file_target, $data); } /** * curl 发送post数据和文件 */ function curl_post_contents($url, $postdata) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); $r = curl_exec($ch); curl_close($ch); return $r; } } ?> <file_sep># 分离ECShop的图片资源到其他服务器 因项目需要,决定将ECShop的图片资源分离到另一台图片服务器上,并对它单独做加速。 > 查了一下关于图片分布式存储的资料,基本方法可以归结为以下几类: 1. 通过FTP传输 2. 通过分布式文件管理系统进行同步 3. 因使用的ECShop后台编辑器改为了百度编辑器,而百度编辑器有一个版本是用七牛云存储的,可以考虑将图片存储到七牛上 4. 使用ajax模拟表单提交,将图片上传到目标服务器上 5. 使用php的curl函数模拟表单提交 因为本身项目不大,所以放弃了方法2,方法1还要部署FTP,觉得麻烦也放弃了,公司的项目数据文件还是放在自己的服务器上比较好,基于此,方法3也放弃。 最终思考之后决定:绝大多数地方用php的curl方法,局部使用ajax加强体验。 关于ueditor,吐槽一下,在这个项目上使用的是1.3.6版本的,现在官网上的文档都是1.4.0+的,1.4+有比较大的改动,官方文档上也写了如何设置远程地址,但对于只在项目开始时配置一下其他时候不管的我来说,想知道怎么设置很费劲,而且官网上也没有关于版本升级的方案,总之,文档模模糊糊的,不够清晰,果断放弃升级、配置。 ### 图片服务器修改 > 不管使用方法4还是5,都需要图片服务器有php环境,用以接收文件 1. 添加 uploadFile.php 文件到图片服务器根目录,并在根目录下创建 logs 文件夹,作为日志目录 2. 编辑 uploadFile.php 文件,设置第7行的 `access_key` ,用来进行简单的验证 3. 分别复制 bdimages(ueditor文件上传目录)、data、images、themes(主题目录,可不传)目录到图片服务器根目录下 ### 主服务器修改 1. 添加 RemoteFileUp.class.php 文件到主服务器 includes 目录下,并将其中的 $cus_remote_file_target 替换为目标图片服务器地址,设置 $cus_remote_file_key 为上面设置的 access_key 值 2. 【ueditor修改】修改ueditor.config.js 文件中的 imagePath为空,使上传的图片在编辑器里不会加上当前主服务器网址 `,imagePath: ""` 3. 【ueditor修改】修改php目录下的imageUp.php文件,在第67行左右[$info = $up->getFileInfo();] 后添加如下代码: ```php ... $info = $up->getFileInfo(); //上传图片到远程服务器 include_once dirname(__FILE__) . '/../../remoteFileUp.php'; $CusRemoteFile = new CustomRemoteFile(); $info['url'] = $CusRemoteFile->cus_remote_editor_file($info['url']); ... ``` 4. 【数据库修改】为后台能统一设置图片服务器地址,在`ecs_shop_config`表 中添加一条记录: ![ecs_shop_config](https://dn-shimo-image.qbox.me/kCLL9RAPweQB0xkL.png!thumbnail "ecs_shop_config") 此时要获取图片服务器地址,只需要使用 `$GLOBALS['_CFG']['site_url']` 即可 5. 【语言文件修改】打开 /languages/zh_cn/admin/shop_config.php 在末尾或者适当位置添加一行代码 ```php $_LANG['cfg_name']['site_url'] = "网店图片资源地址"; ``` 重新打开后台系统设置页面,即可看到刚刚设置的这个site_url了。 6. 【后台修改】网店最主要的是产品图片资源较多,此处就以后台添加产品为例说明。编辑后台目录(默认admin)下的goods.php 文件,1211行左右[/* 处理相册图片 */] 之后添加代码: ```php if($GLOBALS['_CFG']['site_url']!="" && $GLOBALS['_CFG']['site_url']!='http://'.$_SERVER['HTTP_HOST'].'/'){ //上传图片到远程服务器 include_once dirname(__FILE__) . '/../includes/remoteFileUp.php'; $CusRemoteFile = new CustomRemoteFile(); if($goods_img){ $CusRemoteFile->cus_remote_gallery_file('../'.$goods_img); //上传商品图 } if($original_img){ $CusRemoteFile->cus_remote_gallery_file('../'.$original_img); //上传商品原图 } if($goods_thumb){ $CusRemoteFile->cus_remote_gallery_file('../'.$goods_thumb); //上传商品缩略图 } if($img){ $CusRemoteFile->cus_remote_gallery_file('../'.$img); //上传商品相册图 } if($gallery_img){ $CusRemoteFile->cus_remote_gallery_file('../'.$gallery_img); //上传商品相册图 } if($gallery_thumb){ $CusRemoteFile->cus_remote_gallery_file('../'.$gallery_thumb); //上传商品相册缩略图 } } ``` 7.【前台模板修改】首先在includes/lib_main.php 文件中找到function assign_template(第1701行左右)添加一行代码,目的是赋值给smarty一个公共的变量: ```php $smarty->assign('site_url', $GLOBALS['_CFG']['site_url']); ``` 8. 【前台模板修改】在themes目录下修改首页、列表页、详情页等需要修改的模板,在img的src之前加上{$site_url}即可 9. 【前台模板修改】固定的图片资源在模板里相应变量前加$site_url就可以了,接下来要将产品详情等在后台编辑器中编辑的图片也改过来。 在includes/lib_base.php文件末尾加一个公共函数,用来替换编辑器编辑的内容中的图片路径: ```php /** * 替换图片地址为图片服务器地址,如有需要,可以自行添加 * @param string $site_url 图片服务器地址 * @param string $content 原字符串 * @return string */ function replace_remote_image_url($site_url='', $content=''){ if($site_url == '' || $content == ''){ return ''; } //原ueditor编辑器上传的图片带有当前站点网址,如果是新站,第一行可忽略 $content = str_replace("http://".$_SERVER['HTTP_HOST']."/includes/ueditor/php/../../../", '/', $content); $content = str_replace('src="/bdimages/', 'src="'.$site_url.'bdimages/', $content); $content = str_replace('src="/images/', 'src="'.$site_url.'images/', $content); return $content; } ``` 10. 【前台模板修改】编辑goods.php 文件,找到: `$smarty->assign('goods', $goods);` 在它之前添加一行代码: ```php $goods['goods_desc'] = replace_remote_image_url($GLOBALS['_CFG']['site_url'], $goods['goods_desc']); `` 完成 =====
760c82797bbae4305db1136828631559f7ce195b
[ "Markdown", "PHP" ]
3
PHP
tinydream96/seperate-images-from-ecshop-to-another-server
125e2ab895fd4fa2ec1f66772de5d102b305db43
ff20a36f84c801fd96fa4ac824a093d89977c193
refs/heads/master
<file_sep>import sys import requests as r import urllib.parse as purl import json f = open('../scopus.key') keys = [ln.strip() for ln in f if len(ln) > 5] key = keys[0] f.close() f = open(sys.argv[1]) journalFields = [('dc:title','title'), ('dc:publisher','publisher')] def formatJournal(jrnl): res = {} if ('serial-metadata-response' not in jrnl or 'entry' not in jrnl['serial-metadata-response'] or len(jrnl['serial-metadata-response']['entry']) == 0): return res jrnl = jrnl['serial-metadata-response']['entry'][0] for jsId, oId in journalFields: res[oId] = jrnl[jsId] if 'subject-area' in jrnl and len(jrnl['subject-area']) > 0: res['subject'] = jrnl['subject-area'][0]['@abbrev'] res['subjects'] = "; ".join([sb['$'] for sb in jrnl['subject-area']]) if 'SNIPList' in jrnl and 'SNIP' in jrnl['SNIPList']: res['SNIP'] = jrnl['SNIPList']["SNIP"][0]["$"] res['SNIPyear'] = jrnl['SNIPList']["SNIP"][0]["@year"] if 'SJRList' in jrnl and 'SJR' in jrnl['SJRList']: res['SJR'] = jrnl['SJRList']["SJR"][0]["$"] res['SJRyear'] = jrnl['SJRList']["SJR"][0]["@year"] if 'IPPList' in jrnl and 'IPP' in jrnl['IPPList']: res['IPP'] = jrnl['IPPList']["IPP"][0]["$"] res['IPPyear'] = jrnl['IPPList']["IPP"][0]["@year"] return res outp = [] baseUrl = "http://api.elsevier.com/content/serial/title/issn/" for i,ln in enumerate(f): ln = ln.strip().replace("\"","") url = purl.urlencode({'apiKey':key, 'httpAccept':'application/json'}) resUrl = "{}{}?{}".format(baseUrl,ln,url) m = r.get(resUrl) itm = formatJournal(m.json()) itm['issn'] = ln outp.append(itm) f = open('journalData.json','w') json.dump(outp,f) f.close() <file_sep>#!/usr/bin/env python3 from ScopusScrapus import * from ScopusScrapus.utils import formatScopusEntry import json f = open('../scopus.key') keys = [ln.strip() for ln in f if len(ln) > 5] f.close() params = {'query':'TITLE-ABS-KEY(arctic)'} ppList = [] qExceeded = False for year in range(2016,1945,-1): params['date'] = year ssq = StartScopusSearch(keys,params,delay=10) for pp in ssq: try: ppList.append(formatScopusEntry(pp)) except Exception as e: if 'QuotaExceeded' not in str(e): raise qExceeded = True print("Quota Exceeded. Made it to",year) break if qExceeded: break outf = open("firstPapers_1.json",'w') json.dump(ppList,outf) outf.close() <file_sep>## Dataset of Arctic-related papers The dataset contains two main graphs: * A bipartite graph of authors and papers * A **tripartite** graph of authors, papers, and institutions. This is the main graph. To operate over 'pairs' of nodesets, it is only necessary to remove nodes of category 'paper', 'inst' or 'author'. The code to ceate the datasets is in `scratch/`. Their functions are the following: * `scratch/scrapePapers.py` - It scrapes all papers containing the word 'arctic' in their title, keywords or abstract, every year back to 1945. * `scratch/scrapeIssn.py` - Takes in a list of ISSNs (for instance in `data/issn.txt`) and downloads data about their publication * `scratch/makeAuthorPaperGraph.py` - It takes in data from the two previous scripts (check first few lines), and outputs a bipartite graph of authors and papers * `scratch/makeTripartite.py` - It takes in data from the two previous scripts (check first few lines), and outputs a tripartite graph that includes papers, authors, and institutions. ### Notes on what the data files are * `data/acia.csv` is a list of author ids that we want to mark in the graph. * `data/paperData.json` is the list of paper information as scraped from the SCOPUS database. * `data/scopusRefined.json` is a refined version of `data/paperData.json`. The paper data is spread into several dictionaries, due to how openrefine works. ### Graph conventions Some data from Scopus was 'corrupted', so there will be a few papers without publication, author or affiliation information. Node ids capture what entity the node represents by their first letter: an author("a"), paper("p") or institution("i"). For instance, node "a7563051" would represent an author, node "i7563957" would represent an institution, and node "p67865" would represent a paper. Also, in `tripartite.graphml`, the nodes contain a `category` field which has a value of `'author'`,`'paper'`, or `'inst'`, for each entity. ## Stats for tripartite graph and derivative graphs 50189 papers. 78901 authors. 13150 institutions. The author-publication graph has 129090 nodes, 7916 connected components. Their sizes: [95637, 295, 102, 101, 96, 77, 64, 55, 47, 46], etc. 50639 authors have ONE publication. 11646 authors have TWO publications. 5196 authors have THREE publications. 11420 authors have MORE THAN THREE publications. 8491 papers have ONE author. 10458 papers have TWO authors. 9397 papers have THREE authors. 21843 papers have MORE THAN THREE authors. The author-institution graph has 92051 nodes, 7493 connected components. Their sizes: [73729, 67, 53, 47, 45, 38, 36, 35, 35, 29], etc. 58527 authors have ONE institutions. 12546 authors have TWO instututions. 3370 authors have THREE institutions. 4458 authors have MORE THAN THREE institutions. 6850 institutions have ONE author. 1942 institutions have TWO authors. 1022 institutions have THREE authors. 3336 institutions have MORE THAN THREE authors. <file_sep>import networkx as nx import json f = open('scratch/firstPapers.json') papers = json.load(f) f.close() f = open('scratch/journalData.json') journals = json.load(f) f.close() journalDic = {j['issn']:j for j in journals} G = nx.Graph() seenAuths = set() for i,pp in enumerate(papers): addPp = {} for k,e in pp.items(): if e is None: continue addPp[k] = e pp = addPp if 'pubissn' in pp and pp['pubissn'] in journalDic: for k,e in journalDic[pp['pubissn']].items(): if e is None: continue pp['pub_'+k] = e else: if 'pubissn' not in pp: continue print("Publication with issn {} unavailable or publication of paper \"{}\" unavailable." .format(str(pp.get('pubissn')),pp['title'])) ppId = 'p{}'.format(i+1) authors = pp.get('authors') if 'authors' in pp: del pp['authors'] affiliations = pp.get('affiliations') if 'affiliations' in pp: del pp['affiliations'] G.add_node(ppId,pp) if authors is None: continue for j, auth in enumerate(authors): athId = 'a{}'.format(auth['id']) newAuth = {} for k,e in auth.items(): if e is None: continue newAuth[k] = e auth = newAuth if 'affiliations' in auth: auth['affiliations'] = ', '.join(auth['affiliations']) if athId not in seenAuths: seenAuths.add(athId) G.add_node(athId,auth) G.add_edge(ppId,athId) nx.write_graphml(G,'author_paper.graphml') <file_sep>import ipdb import networkx as nx import json import csv import itertools from utilities import (PaperGenerator, OpenRefinePaperGenerator, NamesIdDictionary) def load_journals(file_name='data/journalData.json'): with open(file_name) as f: journals = json.load(f) journal_dictionary = {j['issn']:j for j in journals} return journal_dictionary def load_important_authors(file_name='data/acia.csv'): with open(file_name) as f: ids = [a[0] for a in list(csv.reader(f))] return ids acia_auths = set(load_important_authors()) journalDic = load_journals() #papers = PaperGenerator() papers = OpenRefinePaperGenerator() def different_institutions(x, y): return (x['names'] != y['names'] and all([x[k] != y[k] for k in ['country', 'city'] if k in y and k in x and None not in [x[k], y[k]]] or [False])) institution_dictionary = NamesIdDictionary( name_field=lambda x: '{} {}'.format(x.get('names', ''), x.get('country', '')), differentiator=different_institutions) for pp in papers: if 'affiliations' not in pp: continue for j, aff in enumerate(pp['affiliations']): try: institution_dictionary.add(aff) except KeyError: continue G = nx.Graph() def fill_in_publication_data(pp, pub): for k,e in pub.items(): if e is None: continue pp['pub_'+k] = e seenAuths = set() seenAffs = set() def add_node(G, id, node): if id == 'i0': print("Inserting i0!") ipdb.set_trace() G.add_node(id, node) def add_edge(G, id1, id2): if id1[0] == id2[0]: print("Intra-category edge!") ipdb.set_trace() G.add_edge(id1, id2) for i, pp in enumerate(papers): addPp = {} # First we clean the paper info from None fields for k,e in pp.items(): if e is None: continue addPp[k] = e pp = addPp # The we check that the paper has an ISSN (we ignore books), and that the # publication is one that we know. if 'pubissn' in pp and pp['pubissn'] in journalDic: fill_in_publication_data(pp, journalDic[pp['pubissn']]) else: if 'pubissn' not in pp: continue journalDic[pp['pubissn']] = {'issn':pp['pubissn']} fill_in_publication_data(pp, journalDic[pp['pubissn']]) print("Publication with issn {} unavailable or publication of paper \"{}\" unavailable." .format(str(pp.get('pubissn')),pp['title'])) ppId = 'p{}'.format(i+1) # Now we retrieve author information from a paper. authors = pp.get('authors') if 'authors' in pp: del pp['authors'] if authors is None or len(authors) == 0: # If there are no authors in the paper, we ignore it continue # Now we retrieve affiliation information for a paper affiliations = pp.get('affiliations') if 'affiliations' in pp: del pp['affiliations'] if affiliations is None or len(affiliations) == 0: # If there are no affiliations in the paper, we ignore it continue pp['category'] = 'paper' add_node(G, ppId,pp) if affiliations is not None: for j, aff in enumerate(affiliations): if not aff.get('id'): continue aff = institution_dictionary.get(aff['id']) if not aff: continue try: aff_ids = sorted(list( institution_dictionary.get_ids_from_id(aff['id']))) except TypeError: pass if len(aff_ids) > 1: print('Long ids. Good. {} ids'.format(str(len(aff_ids)))) affId = 'i'+aff_ids[0] seenAffs.add(affId) aff['category'] = 'inst' add_node(G, affId, aff) add_edge(G, ppId, affId) # These might not be useful if authors is None: continue for j, auth in enumerate(authors): if 'id' not in auth: continue auth['acia'] = auth['id'] in acia_auths athId = 'a{}'.format(auth['id']) newAuth = {} for k,e in auth.items(): if e is None: continue newAuth[k] = e auth = newAuth #authAffs = [] #if 'affiliations' in auth: # authAffs = auth['affiliations'] # auth['affiliations'] = ', '.join(auth['affiliations']) if athId not in seenAuths: seenAuths.add(athId) auth['category'] = 'author' add_node(G, athId,auth) add_edge(G, ppId,athId) #for aff in authAffs: if 'affiliations' in auth: affId = 'i'+auth['affiliations'] add_edge(G, athId, affId) nx.write_graphml(G,'tripartite.graphml') <file_sep>from collections import defaultdict import json class NamesIdDictionary(object): def __init__(self, differentiator=lambda x, y: False, name_field='names', id_field='id'): """differentiator is a function that returns True if x and y is different. """ # To pair ids to their institutions self._ids_to_items = {} # For when a single institution has different ids self._ids_to_ids_dict = {} # To pair institution names to their ids self._names_to_ids_dict = defaultdict(lambda : set()) self._different = differentiator if isinstance(name_field, str): self._name_fld = lambda x: x.get(name_field) else: # name_field MUST BE A LAMBDA self._name_fld = name_field self._id_fld = id_field def get_ids_from_id(self, id): return self._ids_to_ids_dict.get(id) def get_id_from_name(self, name): return self._names_to_ids_dict.get(name) def get(self, id): return self._ids_to_items.get(id) def add(self, item): id = item.get(self._id_fld) name = self._name_fld(item) if not id: raise KeyError('ID can not be None.') if self._ids_to_items.get(id, None): # We have an item with the same ID # We need to check whether it's the same or not if self._different(item, self._ids_to_items[id]): print('Two items with equal ids are different: {}, {}'.format( str(item), str(self._ids_to_items[id]))) return self._ids_to_items[id] = item if not name: # If we don't know the name, then there's nothing to do return self._names_to_ids_dict[name].add(id) known_ids = self._names_to_ids_dict[name] for _id in known_ids: self._ids_to_ids_dict[_id] = known_ids def clean_up_dict(d): return {k:v for k, v in d.items() if v is not None} def contains_data(arg): if isinstance(arg, dict): values = [v for k, v in arg.items()] elif isinstance(arg, list): values = [v for v in arg] else: values = [arg] return any(values) class PaperGenerator(object): def __init__(self, file_name='data/paperData.json'): self._file_name = file_name def next_paper(self): return next(self._iterator) def __iter__(self): self.papers = json.load(open(self._file_name, 'r')) self._iterator = iter(self.papers) return self def __next__(self): return self.next_paper() def next(self): return self.next_paper() class OpenRefinePaperGenerator(PaperGenerator): def __init__(self, file_name='data/scopusRefined.json'): self._file_name = file_name def __iter__(self): self.json_list = json.load(open(self._file_name, 'r')) self._iterator = iter(self.json_list) self._next_paper_base = next(self._iterator) return self def format_output_paper(self, paper): paper['authors'] = [clean_up_dict(author) for author in paper['authors'] if contains_data(author)] paper['affiliations'] = [clean_up_dict(institution) for institution in paper['affiliations'] if contains_data(institution)] res = clean_up_dict(paper) return res def next_paper(self): paper_base = self._next_paper_base if not paper_base: raise StopIteration if not paper_base.get('pubName'): raise ValueError('The paper list has issues.') if paper_base.get('affiliations') is None: paper_base['affiliations'] = [] if paper_base.get('authors') is None: paper_base['authors'] = [] for e in self._iterator: if e.get('pubName'): self._next_paper_base = e return self.format_output_paper(paper_base) if e.get('authors'): paper_base['authors'] += e['authors'] if e.get('affiliations'): paper_base['affiliations'] += e['affiliations'] self._next_paper_base = None return self.format_output_paper(paper_base) <file_sep>#!/usr/bin/env python import sys import networkx as nx def section(): print('') G = nx.read_graphml(sys.argv[1]) paper_ids = [p for p in G.nodes() if 'p' in p] author_ids = [p for p in G.nodes() if 'a' in p] institution_ids = [p for p in G.nodes() if 'i' in p] print('{} papers. {} authors. {} institutions.'.format(len(paper_ids), len(author_ids), len(institution_ids))) # Removing all institutions [G.remove_node(p) for p in institution_ids] section() connected_components_sizes = sorted( [len(a) for a in nx.connected_components(G)], key=lambda x: -x) print( 'The author-publication graph has {} nodes, {} connected components.' .format(len(G.nodes()), len(connected_components_sizes))) print('Their sizes: {}, etc.'.format(connected_components_sizes[0:10])) from collections import Counter author_publications_distribution = Counter(G.degree(a) for a in author_ids) section() print('{} authors have ONE publication.'.format( author_publications_distribution[1])) print('{} authors have TWO publications.'.format( author_publications_distribution[2])) print('{} authors have THREE publications.'.format( author_publications_distribution[3])) low_count = sum(author_publications_distribution[i] for i in range(1,4)) print('{} authors have MORE THAN THREE publications.'.format( len(author_ids) - low_count)) section() publication_authors_distribution = Counter(G.degree(a) for a in paper_ids) print('{} papers have ONE author.'.format( publication_authors_distribution[1])) print('{} papers have TWO authors.'.format( publication_authors_distribution[2])) print('{} papers have THREE authors.'.format( publication_authors_distribution[3])) low_count = sum(publication_authors_distribution[i] for i in range(1,4)) print('{} papers have MORE THAN THREE authors.'.format( len(paper_ids) - low_count)) G = nx.read_graphml(sys.argv[1]) # Removing all papers [G.remove_node(p) for p in paper_ids] section() connected_components_sizes = sorted( [len(a) for a in nx.connected_components(G)], key=lambda x: -x) print( 'The author-institution graph has {} nodes, {} connected components.' .format(len(G.nodes()), len(connected_components_sizes))) print('Their sizes: {}, etc.'.format(connected_components_sizes[0:10])) author_institutions_distribution = Counter(G.degree(a) for a in author_ids) section() print('{} authors have ONE institutions.'.format( author_institutions_distribution[1])) print('{} authors have TWO instututions.'.format( author_institutions_distribution[2])) print('{} authors have THREE institutions.'.format( author_institutions_distribution[3])) low_count = sum(author_institutions_distribution[i] for i in range(1,4)) print('{} authors have MORE THAN THREE institutions.'.format( len(author_ids) - low_count)) institution_authors_distribution = Counter(G.degree(a) for a in institution_ids) section() print('{} institutions have ONE author.'.format( institution_authors_distribution[1])) print('{} institutions have TWO authors.'.format( institution_authors_distribution[2])) print('{} institutions have THREE authors.'.format( institution_authors_distribution[3])) low_count = sum(institution_authors_distribution[i] for i in range(1,4)) print('{} institutions have MORE THAN THREE authors.'.format( len(institution_ids) - low_count)) <file_sep>""" This script is a sketch of the script that makes the country collaboration graph for future reference. This was used on Jan 31 2017.""" country_edges = defaultdict(lambda : 0) for p in all_papers: if len(p['affiliations']) < 2: continue countries = [a['country'] for a in p['affiliations'] if a.get('country')] if len(countries) < 2: continue print('Countries: {}'.format(countries)) combos = combinations(countries, 2) for combo in combos: combo = sorted(combo) key = tuple(combo) country_edges[key] += 1 G = nx.Graph() for k, v in country_edges.items(): c1 = k[0] c2 = k[1] G.add_node(c1) G.add_node(c2) G.add_edge(c1, c2, weight=v)
40b14fbadc15db2cbd70d87a487f72ab972df128
[ "Markdown", "Python" ]
8
Python
pabloem/arctic-papers
1bbad12bd288706c27b85121a67852bdb0181cd2
8cfeb1e9b7bd930643bd823523819d245cc82d02
refs/heads/master
<file_sep>package com.accenture.tests; import org.testng.Assert; import org.testng.annotations.Test; public class MyTest { @Test public void loginTest() { boolean ER = true; boolean AR = true; Assert.assertEquals(ER, AR); } @Test public void RegTest() { boolean ER = true; boolean AR = false; Assert.assertEquals(ER, AR); } } <file_sep>package com.accenture.test; import org.testng.annotations.Test; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeTest; public class DataDrivenExcel { WebDriver d; @Test public void DataExcel() throws IOException { System.out.println("hre"); d.get("http://demowebshop.tricentis.com/"); FileInputStream fin = new FileInputStream("C:\\Users\\pdc2b-training.pdc2b\\Documents\\TestData.xlsx"); HSSFWorkbook H = new HSSFWorkbook(fin); HSSFSheet s = H.getSheet("Sheet1"); int rowCount= s.getLastRowNum(); for (int i = 1; i<=rowCount; i++) { String Username = s.getRow(i).getCell(0).getStringCellValue(); System.out.println(Username); String Password = s.getRow(i).getCell(1).getStringCellValue(); System.out.println(Password); LoginTest(Username, Password); } try { d.findElement(By.linkText("Log out")).click(); } catch (Exception e) { } } public void LoginTest(String u, String p) { d.findElement(By.linkText("Log in")).click(); d.findElement(By.id("Email")).sendKeys(u); d.findElement(By.id("Password")).sendKeys(p); } @BeforeTest public void BeforeTest() { System.setProperty("webdriver.chrome.driver","C:\\Users\\pdc2b-training.pdc2b\\Desktop\\New folder (2)\\Drivers\\chromedriver_win32\\chromedriver.exe"); d = new ChromeDriver(); } } <file_sep>package com.accenture.test; import org.testng.annotations.Test; import com.gargoylesoftware.htmlunit.javascript.host.Set; import com.gargoylesoftware.htmlunit.javascript.host.URL; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Keys; import org.openqa.selenium.OutputType; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.BeforeTest; @Test public class NewTest { WebDriver d; /*public void demo() { d.get("http://demowebshop.tricentis.com/"); Actions a = new Actions(d); //a.contextClick().build.perform(); d.findElement(By.linkText("Log in")).click(); WebElement email = d.findElement(By.id("Email")); a.moveToElement(email).keyDown(email, Keys.SHIFT).sendKeys("myname").build().perform(); } ******************************************************** public void demoRobot() throws AWTException, InterruptedException { Robot r = new Robot(); //r.keyPress(KeyEvent.VK_WINDOWS); //r.keyRelease(KeyEvent.VK_WINDOWS); setClipboardData("C:\\Users\\pdc2b-training.pdc2b\\Documents\\abcdefgh.txt"); Thread.sleep(1000); r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_V); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_V); } ******************************************************** public void setClipboardData (String s) { StringSelection s1 = new StringSelection(s); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s1, null); } ******************************************************** public class TakeScreenshot { WebDriver d; public void screenshot() throws IOException{ d.get("http://demowebshop.tricentis.com/"); TakeScreenshot t = (TakeScreenShot)d; File f = t.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(f, File("C:\\Screenshots\\myscreenshot.jpg")); } ******************************************************** public class Javascript{ public void js() throws IOException{ d.get("http://demowebshop.tricentis.com/"); d.manage().window().maximize(); JavascriptExecutor j = (JavascriptExecutor) d; } ******************************************************** public class Cookies { WebDriver d; @Test public void demo() throws IOException{ d.get("http://demowebshop.tricentis.com/"); d.manage().deleteAllCookies(); Cookie c = new Cookie("User", "Tricentis"); d.manage().addCookie(c); Set<Cookie> cookiesDetails = d.manage().getCookies(); for (Cookie s:cookiesDetails) { System.out.println(s.getExpiry()); System.out.println(s.getName()); System.out.println(s.getDomain()); } } ******************************************************** public class SeleniumGrid { @Test public void setup() { DesiredCapabilities dc = new DesiredCapabilities(); dc.setBrowserName("chrome"); dc.setPlatform(Platform.WINDOWS); RemoteWebDriver d = new RemoteWebDriver(new URL ("http://10.243.204.8:4343/wd/hub"), dc); } **************************************************************** public class DataDrivenExcel { WebDriver d; @Test public void DataExcel() throws IOException { System.out.println("hre"); d.get("http://demowebshop.tricentis.com/"); FileInputStream fin = new FileInputStream("C:\\Users\\pdc2b-training.pdc2b\\Documents\\TestData.xlsx"); HSSFWorkbook H = new HSSFWorkbook(fin); HSSFSheet s = H.getSheet("Sheet1"); int rowCount= s.getLastRowNum(); for (int i = 1; i<=rowCount; i++) { String Username = s.getRow(i).getCell(0).getStringCellValue(); System.out.println(Username); String Password = s.getRow(i).getCell(1).getStringCellValue(); System.out.println(Password); LoginTest(Username, Password); } try { d.findElement(By.linkText("Log out")).click(); } catch (Exception e) { } } public void LoginTest(String u, String p) { d.findElement(By.linkText("Log in")).click(); d.findElement(By.id("Email")).sendKeys(u); d.findElement(By.id("Password")).sendKeys(p); }*/ @BeforeTest public void BeforeTest() { System.setProperty("webdriver.chrome.driver","C:\\Users\\pdc2b-training.pdc2b\\Desktop\\New folder (2)\\Drivers\\chromedriver_win32\\chromedriver.exe"); d = new ChromeDriver(); } } <file_sep>package com.accenture.test; import org.testng.annotations.Test; import com.gargoylesoftware.htmlunit.javascript.host.URL; import org.openqa.selenium.Platform; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.BeforeTest; public class SeleniumGrid { @Test public void setup() { DesiredCapabilities dc = new DesiredCapabilities(); dc.setBrowserName("chrome"); dc.setPlatform(Platform.WINDOWS); RemoteWebDriver d = new RemoteWebDriver(new URL ("http://10.243.204.8:4343/wd/hub"), dc); } }
372f958edd1d401ceaf4f9d8ff41719114203868
[ "Java" ]
4
Java
varchas44/POM-Framework
3f28d515725e6d395253953d726371171793851e
aed1310f2a53f9e16263815340bdd9c8f86016fc
refs/heads/master
<repo_name>eeue56/slack-today-i-did<file_sep>/run_tests.sh #! /usr/bin/env bash set -e # make sure that there's no syntax errors python3 -c "import main" # run flake8 on everything flake8 main.py slack_today_i_did # run doctest python3 -m doctest slack_today_i_did/*.py python3 -m pytest <file_sep>/slack_today_i_did/our_repo.py """ This file lets you do things with a repo. At the moment, the ElmRepo class can be used in order to get meta info on Elm files in a repo, such as the number of 0.16/0.17 files """ import os import glob from typing import List, Dict from enum import Enum from contextlib import contextmanager class OurRepo(object): def __init__(self, folder: str, token: str, org: str, repo: str): self.folder = folder self.token = token self.org = org self.repo = repo def make_repo_dir(self) -> None: os.makedirs(self.folder, exist_ok=True) def _git_init(self) -> None: url = f'https://{self.token}@github.com/{self.org}/{self.repo}.git' os.system(f'git clone --depth 1 {url}') os.chdir(self.repo) os.system(f'git remote set-url origin {url}') def _git_clone(self, branch_name: str = 'master') -> None: os.system(f'git remote set-branches origin {branch_name}') os.system(f'git fetch --depth 1 origin {branch_name}') os.system(f'git checkout origin/{branch_name}') def get_ready(self, branch_name: str = 'master') -> None: current_dir = os.getcwd() try: self.make_repo_dir() os.chdir(self.folder) self._git_init() except: pass finally: os.chdir(current_dir) os.chdir(self.repo_dir) try: self._git_clone(branch_name) finally: os.chdir(current_dir) @property def repo_dir(self): return f'{self.folder}/{self.repo}' class ElmVersion(Enum): unknown = -1 v_016 = 0 v_017 = 1 class ElmRepo(OurRepo): def __init__(self, *args, **kwargs): OurRepo.__init__(self, *args, **kwargs) self._known_files = {ElmVersion.v_016: [], ElmVersion.v_017: []} self._breakdown_cache = {} self._import_cache = {} self._caching_lookups = False def get_elm_files(self) -> List[str]: return glob.glob(f'{self.repo_dir}/**/*.elm', recursive=True) @property def number_of_017_files(self): elm_017_count = 0 for file in self.get_elm_files(): if self.what_kinda_file(file) == ElmVersion.v_017: elm_017_count += 1 return elm_017_count @property def number_of_016_files(self): elm_016_count = 0 for file in self.get_elm_files(): if self.what_kinda_file(file) == ElmVersion.v_016: elm_016_count += 1 return elm_016_count def get_files_for_017(self, pattern: str) -> List[str]: pattern = pattern.replace('.', '/') all_files = glob.glob( f'{self.repo_dir}/**/{pattern}.elm', recursive=True ) return [ filename for filename in all_files if self.what_kinda_file(filename) == ElmVersion.v_017 ] def get_matching_filenames(self, pattern: str) -> List[str]: pattern = pattern.replace('.', '/') all_files = glob.glob( f'{self.repo_dir}/**/{pattern}.elm', recursive=True ) return all_files @contextmanager def cached_lookups(self) -> None: self.create_cache() yield self.end_cache() def create_cache(self) -> None: """ create a cache so they can be used to make some calcs faster """ self._caching_lookups = True self._breakdown_cache = {} self._import_cache = {} def end_cache(self) -> None: """ removes a lock so caches are no longer used """ self._caching_lookups = False def get_017_porting_breakdown(self, pattern: str) -> Dict[str, Dict[str, int]]: # noqa: E501 all_files = self.get_matching_filenames(pattern) breakdown = { filename: self.how_hard_to_port(filename) for filename in all_files if self.what_kinda_file(filename) == ElmVersion.v_016 } if len(all_files) == 1: imports = self.file_import_list(all_files[0]) for import_ in imports: file_names = self.get_matching_filenames(import_) if not any(name in breakdown for name in file_names): import_breakdown = self.get_017_porting_breakdown(import_) breakdown.update(import_breakdown) return breakdown def file_import_list(self, filename: str) -> List[str]: """ returns the list of modules imported by a file """ if self._caching_lookups: if filename in self._import_cache: return self._import_cache[filename] import_lines = [] in_comment = False with open(filename) as f: for line in f: if in_comment: if line.strip().endswith('-}'): in_comment = False elif line.startswith('import '): just_the_module = 'import '.join(line.split('import ')[1:]) import_lines.append(just_the_module) elif line.strip().startswith('{-'): if line.strip().endswith('-}'): in_comment = False else: in_comment = True elif not (line.startswith('module') or line.startswith(' ')): # we're past the imports break if self._caching_lookups: self._import_cache[filename] = import_lines return import_lines def how_hard_to_port(self, filename: str) -> Dict[str, int]: """ returns a breakdown of how hard a file is to port 0.16 -> 0.17 """ if self._caching_lookups: if filename in self._breakdown_cache: return self._breakdown_cache[filename] breakdown = {} with open(filename) as f: text = f.read() if '\nport' in text or 'Signal' in text: port_count = text.count('\nport') signal_count = text.count('Signal') breakdown['Ports and signals'] = (port_count + signal_count) * 3 if 'import Native' in text: native_modules_count = text.count('import Native') breakdown['Native modules imported'] = (native_modules_count * 2) if ' Html' in text: html_count = text.count(' Html') breakdown['Html stuff'] = html_count if self._caching_lookups: self._breakdown_cache[filename] = breakdown return breakdown def what_kinda_file(self, filename: str) -> ElmVersion: """ if a filename is known to be 0.16 or 0.17, return that const otherwise, go through line by line to try and find some identifiers """ if filename in self._known_files[ElmVersion.v_016]: return ElmVersion.v_016 if filename in self._known_files[ElmVersion.v_017]: return ElmVersion.v_017 with open(filename) as f: for line in f: if line.strip(): if 'exposing' in line: self._known_files[ElmVersion.v_017].append(filename) return ElmVersion.v_017 if 'where' in line: self._known_files[ElmVersion.v_016].append(filename) return ElmVersion.v_016 return ElmVersion.unknown <file_sep>/slack_today_i_did/reports.py import json from typing import Tuple, Dict, Any import time import datetime class Report(object): def __init__( self, channel: str, name: str, time_to_run: Tuple[int, int], people, wait: Tuple[int, int], time_run=None, reports_dir='reports', ): self.name = name self.people_to_bother = people self.channel = channel self.responses = {} self.time_run = time_run self.wait_for = wait self.time_to_run = time_to_run self.reports_dir = reports_dir self.is_ended = False self.last_day_run = None def bother_people(self): if not self.people_to_bother: return [] self.responses = {} self.time_run = datetime.datetime.utcnow() messages = [] messages.append((self.channel, 'Starting my report!')) for person in self.people_to_bother[:]: messages.append((person, 'Sorry to bother you!')) self.add_response(person, '') self.people_to_bother.remove(person) return messages def is_time_to_bother_people(self) -> bool: if self.is_ended: return False current_time = time.time() time_now_string = time.strftime( "%j:%Y %H:%M:", time.gmtime(current_time) ) hour_mins = time_now_string.split(' ')[1].split(':') (hours, minutes) = hour_mins[0], hour_mins[1] time_now = (int(hours), int(minutes)) if time_now < self.time_to_run: return False if self.time_run is not None: day_year = time_now_string.split(' ')[0].split(':') (day_in_year, year) = day_year[0], day_year[1] (time_run_day_in_year, time_run_year) = self.time_run.strftime('%j:%Y').split(':') # noqa: E501 if int(year) == int(time_run_year) and int(day_in_year) == int(time_run_day_in_year): # noqa: E501 return False self.is_ended = False return True def is_time_to_end(self) -> bool: if self.is_ended: return False current_time = time.time() time_now = time.strftime("%H:%M:", time.gmtime(current_time)) time_now = (int(time_now.split(':')[0]), int(time_now.split(':')[1])) end_time = (self.time_to_run[0] + self.wait_for[0], self.time_to_run[1] + self.wait_for[1]) # noqa: E501 if time_now < end_time: return False self.is_ended = True return True def is_for_user(self, user): return user in self.responses or user in self.people_to_bother def add_response(self, user, message): if user not in self.responses: self.responses[user] = message else: if len(self.responses[user]) == 0: self.responses[user] = message else: self.responses[user] += '\n' + message self.save_responses() def save_responses(self): with open(f'{self.reports_dir}/report-{self.name}-{self.channel}-{self.time_run}.json', 'w') as f: # noqa: E501 json.dump(self.responses, f) def save(self): with open(f'{self.reports_dir}/report-config-{self.name}-{self.channel}.json', 'w') as f: # noqa: E501 json.dump(f, self.as_dict()) def as_dict(self): return { 'name': self.name, 'channel': self.channel, 'responses': self.responses, 'people_to_bother': self.people_to_bother, 'time_run': (str(self.time_run) if self.time_run is not None else "") # noqa: E501 } class Sessions(object): def __init__(self): self.sessions = {} def has_running_session(self, person: str) -> bool: if person not in self.sessions: return False return self.sessions[person]['is_running'] def start_session(self, person: str, channel: str) -> None: self.sessions[person] = { 'is_running': True, 'messages': [], 'channel': channel } def end_session(self, person: str) -> None: if not self.has_running_session(person): return self.sessions[person]['is_running'] = False def add_message(self, person: str, message: str) -> None: if not self.has_running_session(person): return self.sessions[person]['messages'].append(message) def get_entry(self, person: str) -> Dict[str, Any]: if person not in self.sessions: return {} return self.sessions[person] def retire_session(self, person: str, filename: str) -> None: session_info = self.sessions.pop(person) with open(filename, 'w') as f: json.dump(session_info, f) def load_from_file(self, filename: str) -> None: """ Load people:session from a file """ try: with open(filename) as f: as_json = json.load(f) except FileNotFoundError: return for (name, session) in as_json['sessions'].items(): self.sessions[name] = session def save_to_file(self, filename: str) -> None: """ save people:sessions to a file """ with open(filename, 'w') as f: json.dump({'sessions': self.sessions}, f) <file_sep>/slack_today_i_did/generic_bot.py """ This file contains the bot itself To add a new function: - add an entry in `known_functions`. The key is the command the bot will know, the value is the command to run - You must add type annotitions for the bot to match args up correctly """ import html from typing import List, Union, NamedTuple from slack_today_i_did.better_slack import BetterSlack from slack_today_i_did.command_history import CommandHistory import slack_today_i_did.self_aware as self_aware import slack_today_i_did.parser as parser import slack_today_i_did.text_tools as text_tools ChannelMessage = NamedTuple('ChannelMessage', [('channel', str), ('text', str)]) ChannelMessages = Union[ChannelMessage, List[ChannelMessage]] class GenericSlackBot(BetterSlack): _user_id = None _last_sender = None def __init__(self, *args, **kwargs): BetterSlack.__init__(self, *args, **kwargs) self.name = 'generic-slack-bot' self.command_history = CommandHistory() def is_direct_message(self, channel): """ Direct messages start with `D` """ return channel.startswith('D') def was_directed_at_me(self, text): return text.startswith(f'<@{self.user_id}>') def parse_direct_message(self, message): self._actually_parse_message(message) async def main_loop(self): await BetterSlack.main_loop( self, parser=self.parse_messages, on_tick=self.on_tick ) def known_tokens(self) -> List[str]: return list(self.known_functions().keys()) def known_functions(self): return {**self.known_user_functions(), **self.known_statements()} def known_user_functions(self): return { 'func-that-return': self.functions_that_return, 'error-help': self.error_help, 'help': self.help, 'possible-funcs': self.possible_funcs, 'list': self.list, 'reload-funcs': self.reload_functions, } def known_statements(self): return { '!!': self.last_command_statement } def on_tick(self): pass @property def user_id(self): if self._user_id is None: data = self.connected_user(self.name) self._user_id = data return self._user_id def parse(self, text, channel): """ Take text, a default channel, """ # we only tokenize those that talk to me if self.was_directed_at_me(text): user_id_string = f'<@{self.user_id}>' if text.startswith(user_id_string): text = text[len(user_id_string):].strip() else: return None tokens = parser.tokenize(text, self.known_tokens()) return parser.parse(tokens, self.known_functions()) def _actually_parse_message(self, message): channel = message['channel'] text = message['text'] stuff = self.parse(text, channel) if stuff is None: return func_call = stuff.func_call evaluate = stuff.evaluate # we always give the channel as the first arg default_args = [parser.Constant(channel, str)] try: evaluation = evaluate(func_call, default_args) # deal with exceptions running the command if len(evaluation.errors) > 0: self.send_channel_message(channel, '\n\n'.join(evaluation.errors)) return if func_call.return_type == ChannelMessages: if isinstance(evaluation.result, ChannelMessage): messages = [evaluation.result] else: messages = evaluation.result for message in messages: self.send_channel_message(message.channel, message.text) if evaluation.action != self.known_statements()['!!']: self.command_history.add_command(channel, evaluation.action, evaluation.args) except Exception as e: self.send_channel_message(channel, f'We got an error {e}!') def parse_message(self, message): # if we don't have any of the useful data, return early if 'type' not in message or 'text' not in message: return None if message['type'] != 'message': return None self._last_sender = message.get('user', None) # if it's a direct message, parse it differently if self.is_direct_message(message['channel']): return self.parse_direct_message(message) return self._actually_parse_message(message) def parse_messages(self, messages): for message in messages: self.parse_message(message) def error_help(self, channel: str, problem: str) -> ChannelMessages: """ present an error help message """ if problem == 'NO_TOKENS': return ChannelMessage(channel, 'I\'m sorry, I couldn\'t find any tokens. Try using `help` or `list`') # noqa: E501 else: return ChannelMessage(channel, f'Some problem: {problem}') def last_command_statement(self, channel: str) -> ChannelMessages: """ run the last command again """ stuff = self.command_history.last_command(channel) if stuff is None: self.send_channel_message(channel, 'No commands have been run yet!') return action = stuff['action'] args = stuff['args'] return action(*args) def list(self, channel: str) -> ChannelMessages: """ list known statements and functions """ message = 'Main functions:\n' message += '\n'.join( f'`{func}`'for func in self.known_user_functions() ) message += '\nStatements:\n' message += '\n'.join( f'`{func}`'for func in self.known_statements() ) return ChannelMessage(channel, message) def possible_funcs(self, channel: str, name: str) -> ChannelMessages: """ give me a name and I'll tell you funcs which are close """ known_functions = self.known_functions() # default the length of the name acceptable_score = len(name) # but for long names, we want to cap it a bit if acceptable_score > 10: acceptable_score = 10 elif acceptable_score > 5: acceptable_score = 4 possibles = possible_functions(known_functions, name, acceptable_score=acceptable_score) if len(possibles) == 0: return ChannelMessage(channel, "I don't know what you mean and have no suggestions") message = f'I don\'t know about `{name}`. But I did find the following functions with similiar names:\n' message += ' | '.join(possibles[:5]) return ChannelMessage(channel, message) # TODO: args should be annotated with `List[parser.FuncArg]` once # https://github.com/python/typing/issues/306 is resolved. @parser.metafunc def help(self, channel: str, args) -> ChannelMessages: """ given a function name, I'll tell you about it """ if not len(args): return self.list(channel) if isinstance(args[0], parser.Constant): func_name = args[0].value else: func_name = args[0].func_name known_functions = self.known_functions() if func_name not in known_functions: return self.possible_funcs(channel, func_name) func = known_functions[func_name] docs = ' '.join(line.strip() for line in func.__doc__.split('\n')) message = f'`{func_name}` has the help message:\n{docs}\n' if not parser.is_metafunc(func): message += 'And the type info:\n```\n' type_info = '\n'.join( f'- {arg_name} : {arg_type}' for (arg_name, arg_type) in func.__annotations__.items() ) message += f'{type_info}\n```' return ChannelMessage(channel, message) def reload_functions(self, channel: str) -> ChannelMessages: """ reload the functions a bot knows """ self_aware.restart_program() return [] def functions_that_return(self, channel: str, text: str) -> ChannelMessages: """ give a type, return functions that return things of that type """ func_names = [] text = text.strip() text = html.unescape(text) for (name, func) in self.known_functions().items(): if str(func.__annotations__.get('return', None)) == text: func_names.append((name, func.__annotations__)) message = f"The following functions return `{text}`:\n" message += '```\n' message += '\n'.join(name for (name, type) in func_names) message += '\n```' return ChannelMessage(channel, message) def possible_functions(known_functions, name, acceptable_score=5): possibles = [ (text_tools.token_based_levenshtein(func_name, name), func_name) for func_name in known_functions ] possibles = [x for x in possibles if x[0] < acceptable_score] possibles = sorted(possibles, key=lambda x: x[0]) possibles = [x[1] for x in possibles] return possibles class BotExtension(GenericSlackBot): def __init__(self, *args, **kwargs): pass <file_sep>/setup.py #!/usr/bin/env python from distutils.core import setup setup( name='slack_today_i_did', version='1.0', description='A slack bot for NoRedInk', author='<NAME>', author_email='<EMAIL>', url='https://www.github.com/NoRedInk/slack-today-i-did', packages=['slack_today_i_did'], ) <file_sep>/requirements.txt json-tricks==3.2.0 mypy-lang==0.4.4 requests==2.11.1 slackclient==1.0.2 typed-ast==0.5.6 websockets==3.2 psutil==4.3.1 prompt-toolkit==1.0.8 <file_sep>/slack_today_i_did/notify.py import json from typing import List import re class Notification(object): """ Allows you to register multiple regex patterns with a person This is designed to let you notify users based on an incoming pattern """ def __init__(self): self.patterns = {} def add_pattern(self, person: str, pattern: str) -> None: """ register a pattern to notify a given person """ if person not in self.patterns: self.patterns[person] = [] self.patterns[person].append(pattern) def forget_pattern(self, person: str, pattern: str) -> None: """ stop notifying a person for a given pattern """ if person not in self.patterns: return if pattern in self.patterns[person]: self.patterns[person].remove(pattern) def who_wants_it(self, text: str) -> None: """ returns a list of people that want to be notified by a message that matches any of the registered patterns """ who_wants_it = [] for (person, patterns) in self.patterns.items(): for pattern in patterns: if re.search(pattern, text, re.MULTILINE) is not None: who_wants_it.append(person) break return who_wants_it def get_patterns(self, person: str) -> List[str]: """ get a list of patterns for a person """ if person in self.patterns: return self.patterns[person] return [] def load_from_file(self, filename: str) -> None: """ Load people:patterns from a file """ try: with open(filename) as f: as_json = json.load(f) except FileNotFoundError: return for (name, patterns) in as_json['patterns'].items(): self.patterns[name] = patterns def save_to_file(self, filename: str) -> None: """ save people:patterns to a file """ with open(filename, 'w') as f: json.dump({'patterns': self.patterns}, f) <file_sep>/slack_today_i_did/type_aware/json.py """ Support dumping and loading of typing types. """ import typing import functools from json_tricks import nonp def encode_type(obj): if isinstance(obj, type) or isinstance(obj.__class__, typing.TypingMeta): return {'__type_repr__': repr(obj)} return obj class TypeHook(object): def __init__(self, types): self.type_lookup_map = {repr(type_obj): type_obj for type_obj in types} def __call__(self, dct): if isinstance(dct, dict) and '__type_repr__' in dct: return self.type_lookup_map.get(dct['__type_repr__'], dct) return dct def _append_to_key(kwargs, key, obj): objs = [] if key in kwargs: objs = list(kwargs[key]) objs.append(obj) kwargs[key] = objs def _wrap_dumper(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): _append_to_key(kwargs, 'extra_obj_encoders', encode_type) return fn(*args, **kwargs) return wrapper def _wrap_loader(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): known_types = kwargs.pop('known_types', tuple()) _append_to_key(kwargs, 'extra_obj_pairs_hooks', TypeHook(known_types)) return fn(*args, **kwargs) return wrapper dump = _wrap_dumper(nonp.dump) dumps = _wrap_dumper(nonp.dumps) load = _wrap_loader(nonp.load) loads = _wrap_loader(nonp.loads) <file_sep>/main.py import json import asyncio from slack_today_i_did.bot_file import TodayIDidBot from slack_today_i_did.bot_repl import ReplBot from slack_today_i_did.our_repo import ElmRepo import os import argparse def setup(): config_found = True try: with open('priv.json') as f: data = json.load(f) except FileNotFoundError: print('not using config file..') print('some features may be disabled!') config_found = False repo = None os.makedirs('reports', exist_ok=True) if config_found: os.makedirs('repos', exist_ok=True) github_data = data['github'] repo = ElmRepo(github_data['folder'], github_data['token'], github_data['org'], github_data['repo']) else: data = {} return (data, repo) def setup_slack(data, repo): return TodayIDidBot( data.get('token', ''), rollbar_token=data.get('rollbar-token', None), elm_repo=repo ) def setup_cli(data, repo): return ReplBot( data.get('token', ''), rollbar_token=data.get('rollbar-token', None), elm_repo=repo ) def main(): parser = argparse.ArgumentParser(description='Start the slack-today-i-did-bot') parser.add_argument( '--repl', '-r', action='store_true', help='run the repl', default=False ) parser.add_argument( '--slack', '-s', action='store_true', help='run the slack bot', default=False ) args = parser.parse_args() if args.repl and args.slack: print('Please only start the repl or the slack bot!') exit(-1) (data, repo) = setup() if args.repl: print('starting repl..') client = setup_cli(data, repo) elif args.slack: print('starting slack client..') client = setup_slack(data, repo) else: print('starting slack client..') client = setup_slack(data, repo) loop = asyncio.get_event_loop() loop.run_until_complete(client.main_loop()) if __name__ == '__main__': main() <file_sep>/slack_today_i_did/bot_file.py """ This file contains the bot itself To add a new function: - add an entry in `known_functions`. The key is the command the bot will know, the value is the command to run - You must add type annotitions for the bot to match args up correctly """ from typing import Dict, Any from slack_today_i_did.rollbar import Rollbar from slack_today_i_did.extensions import ( BasicStatements, KnownNamesExtensions, NotifyExtensions, ReportExtensions, SessionExtensions, RollbarExtensions, ElmExtensions, ExtensionExtensions ) from slack_today_i_did.generic_bot import GenericSlackBot, ChannelMessage, ChannelMessages import slack_today_i_did.self_aware as self_aware class Extensions( BasicStatements, KnownNamesExtensions, NotifyExtensions, ReportExtensions, SessionExtensions, RollbarExtensions, ElmExtensions, ExtensionExtensions ): pass class TodayIDidBot(Extensions, GenericSlackBot): def __init__(self, *args, **kwargs): kwargs = self._setup_from_kwargs_and_remove_fields(**kwargs) GenericSlackBot.__init__(self, *args, **kwargs) self.reports = {} self.name = 'today-i-did' self._setup_known_names() self._setup_notify() self._setup_sessions() self._setup_command_history() self._setup_enabled_tokens() def _setup_from_kwargs_and_remove_fields(self, **kwargs: Dict[str, Any]) -> Dict[str, Any]: rollbar_token = kwargs.pop('rollbar_token', None) if rollbar_token is None: self.rollbar = None else: self.rollbar = Rollbar(rollbar_token) self.repo = kwargs.pop('elm_repo', None) self.reports_dir = kwargs.pop('reports_dir', 'reports') self.known_names_file = kwargs.pop('known_names_file', 'names.json') self.notify_file = kwargs.pop('notify_file', 'notify.json') self.session_file = kwargs.pop('session_file', 'sessions.json') self.command_history_file = kwargs.pop('command_history_file', 'command_history.json') return kwargs def _setup_command_history(self) -> None: known_functions = {action.__name__: action for action in self.known_functions().values()} self.command_history.load_from_file(known_functions, (ChannelMessages,), self.command_history_file) @property def features_enabled(self): return { "repo": self.repo is not None, "rollbar": self.rollbar is not None } def _actually_parse_message(self, message): GenericSlackBot._actually_parse_message(self, message) strings = [] for attachment in message.get('attachments', []): strings.extend(self.attachment_strings(attachment)) if 'text' in message: strings.append(message['text']) people_who_want_notification = [] for string in strings: people_who_want_notification.extend(self.notify.who_wants_it(string)) people_who_want_notification = set(people_who_want_notification) for person in people_who_want_notification: self.ping_person(message['channel'], person) if self.command_history.needs_save: self.command_history.save_to_file(self.command_history_file) def parse_direct_message(self, message): user = message['user'] text = message['text'] if self.was_directed_at_me(text): return self._actually_parse_message(message) name = self.user_name_from_id(user) for (channel_name, reports) in self.reports.items(): for report in reports.values(): if report.is_for_user(name): report.add_response(name, text) self.send_message(name, 'Thanks!') if self.sessions.has_running_session(user): self.sessions.add_message(user, text) self.sessions.save_to_file(self.session_file) def on_tick(self): for (channel, reports) in self.reports.items(): for report in reports.values(): if report.is_time_to_bother_people(): report.bother_people(self) elif report.is_time_to_end(): self.single_report_responses(channel, report) def known_statements(self): return { 'FOR': self.for_statement, 'AT': self.at_statement, 'WAIT': self.wait_statement, 'NOW': self.now_statement, 'NUM': self.num_statement, '!!': self.last_command_statement } def known_user_functions(self): return { 'bother': self.bother, 'bother-all-now': self.bother_all_now, 'report-responses': self.report_responses, 'responses': self.responses, 'func-that-return': self.functions_that_return, 'error-help': self.error_help, 'help': self.help, 'list': self.list, 'reload-funcs': self.reload_functions, 'reload': self.reload_branch, 'status': self.status, 'house-party': self.party, 'rollbar-item': self.rollbar_item, 'elm-progress': self.elm_progress, 'elm-progress-on': self.elm_progress_on, 'find-017-matches': self.find_elm_017_matches, 'how-hard-to-port': self.how_hard_to_port, 'who-do-you-know': self.get_known_names, 'know-me': self.add_known_name, 'when-you-hear': self.when_you_hear, 'forget': self.stop_listening, 'start-session': self.start_session, 'end-session': self.end_session, 'tokens-status': self.tokens_status, 'disable-token': self.disable_token, 'enable-token': self.enable_token, 'known-ext': self.known_extensions, 'disable-ext': self.disable_extension, 'enable-ext': self.enable_extension, 'load-ext': self.load_extension } def reload_branch(self, channel: str, branch: str = None) -> ChannelMessages: """ reload a branch and trigger a restart """ if branch is None: branch = self_aware.git_current_version() if branch.startswith('HEAD DETACHED'): return [] on_branch_message = 'On branch' if branch.startswith(on_branch_message): branch = branch[len(on_branch_message):] self_aware.git_checkout(branch) self_aware.restart_program() return [] def status(self, channel: str, show_all: str = None) -> ChannelMessages: """ provides meta information about the bot """ current_version = self_aware.git_current_version() message = f"I am running on {current_version}\n" if show_all is not None: message += '-------------\n' message += '\n'.join( f'{feature} is {"enabled" if is_enabled else "disabled"}' for (feature, is_enabled) in self.features_enabled.items() ) message += '\n-------------\n' message += f'Python version: {self_aware.python_version()}\n' message += f'Ruby version: {self_aware.ruby_version()}\n' return ChannelMessage(channel, message) def party(self, channel: str) -> ChannelMessages: """ TADA """ return ChannelMessage(channel, ':tada:') <file_sep>/tests/test_command_history.py import pytest from typing import Union import os import slack_today_i_did.command_history as command_history MOCK_CHANNEL = 'dave' MOCK_FUNCTION_NAME = 'MOCK_FUNCTION' MOCK_TEST_FILE = '.testdata_command_history' def MOCK_FUNCTION(): pass MOCK_KNOWN_TOKENS = { 'MOCK_FUNCTION': MOCK_FUNCTION } MOCK_UNION = Union[int, str] MOCK_KNOWN_TYPES = (MOCK_UNION,) def test_add_pattern(): commands = command_history.CommandHistory() assert commands.last_command(MOCK_CHANNEL) is None commands.add_command(MOCK_CHANNEL, MOCK_FUNCTION, []) last_command = commands.last_command(MOCK_CHANNEL) assert last_command['action'] == MOCK_FUNCTION assert last_command['args'] == [] assert commands.needs_save == True assert len(commands.history) == 1 assert len(commands.history[MOCK_CHANNEL]) == 1 def test_saving_and_loading(tmpdir): history_file = str(tmpdir.join(MOCK_TEST_FILE)) commands = command_history.CommandHistory() commands.load_from_file(MOCK_KNOWN_TOKENS, MOCK_KNOWN_TYPES, history_file) assert commands.last_command(MOCK_CHANNEL) is None assert commands.needs_save == False commands.add_command(MOCK_CHANNEL, MOCK_FUNCTION, [MOCK_UNION]) commands.save_to_file(history_file) assert commands.last_command(MOCK_CHANNEL) is not None new_commands = command_history.CommandHistory() new_commands.load_from_file(MOCK_KNOWN_TOKENS, MOCK_KNOWN_TYPES, history_file) assert new_commands.last_command(MOCK_CHANNEL) is not None assert commands == new_commands <file_sep>/slack_today_i_did/bot_repl.py from slack_today_i_did.bot_file import TodayIDidBot import prompt_toolkit.layout.lexers import prompt_toolkit.auto_suggest from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.shortcuts import ( create_prompt_application, create_asyncio_eventloop ) from prompt_toolkit.history import FileHistory from prompt_toolkit.contrib.completers import WordCompleter class ReplBot(TodayIDidBot): def __init__(self, *args, **kwargs): TodayIDidBot.__init__(self, *args, **kwargs) self._setup_cli_history() def _setup_cli_history(self): self.cli_history = FileHistory('.cli_history') async def __aenter__(self): self.eventloop = create_asyncio_eventloop() self.completer = WordCompleter(self.known_tokens()) config = { 'complete_while_typing': True, 'enable_history_search': True, 'history': self.cli_history, 'auto_suggest': Suggestions(), 'completer': self.completer, 'lexer': prompt_toolkit.layout.lexers.SimpleLexer() } self.cli = CommandLineInterface( application=create_prompt_application(f'{self.name} >>> ', **config), eventloop=self.eventloop ) return self async def __aexit__(self, *args, **kwargs): return self async def get_message(self): incoming = await self.cli.run_async() incoming = f'<@{self.name}> {incoming.text}' data = [{ "text": incoming, "type": "message", "channel": "CLI", "user": "CLI" }] return data def ping(self): return self.send_to_websocket({"type": "ping"}) def send_to_websocket(self, data): if 'type' not in data: return if data['type'] == 'message': print(data['text']) def set_known_users(self): return def user_name_from_id(self, my_id): for (name, id) in self.known_users.items(): if id == my_id: return name return None def open_chat(self, name: str) -> str: return name def send_message(self, name: str, message: str) -> None: json = {"type": "message", "channel": id, "text": message} self.send_to_websocket(json) def send_channel_message(self, channel: str, message: str) -> None: json = {"type": "message", "channel": channel, "text": message} self.send_to_websocket(json) def connected_user(self, username: str) -> str: return username def attachment_strings(self, attachment): strings = [] for (k, v) in attachment.items(): if isinstance(v, str): strings.append(v) for field in attachment.get('fields', []): strings.append(field['title']) strings.append(field['value']) return strings class Suggestions(prompt_toolkit.auto_suggest.AutoSuggestFromHistory): def get_suggestion(self, cli, buffer, document): return prompt_toolkit.auto_suggest.AutoSuggestFromHistory.get_suggestion( self, cli, buffer, document ) <file_sep>/tests/test_notify.py import pytest import os import slack_today_i_did.notify as notify MOCK_PERSON = 'dave' MOCK_VALID_PATTERN = '[a]' MOCK_INVALID_PATTERN = '[' MOCK_TEXT_WITH_PATTERN = 'a' MOCK_TEXT_WITHOUT_PATTERN = "b" MOCK_TEST_FILE = '.testdata_notify' def test_add_pattern(): notification = notify.Notification() notification.add_pattern(MOCK_PERSON, MOCK_VALID_PATTERN) assert MOCK_PERSON in notification.patterns assert notification.patterns[MOCK_PERSON] == [MOCK_VALID_PATTERN] def test_forget_pattern(): notification = notify.Notification() notification.add_pattern(MOCK_PERSON, MOCK_VALID_PATTERN) notification.forget_pattern(MOCK_PERSON, MOCK_VALID_PATTERN) assert MOCK_PERSON in notification.patterns assert len(notification.patterns[MOCK_PERSON]) == 0 notification.add_pattern(MOCK_PERSON, MOCK_VALID_PATTERN) notification.forget_pattern(MOCK_PERSON, MOCK_INVALID_PATTERN) assert MOCK_PERSON in notification.patterns assert len(notification.patterns[MOCK_PERSON]) == 1 def test_who_wants_it(): notification = notify.Notification() notification.add_pattern(MOCK_PERSON, MOCK_VALID_PATTERN) who_wants_it = notification.who_wants_it(MOCK_TEXT_WITHOUT_PATTERN) assert len(who_wants_it) == 0 who_wants_it = notification.who_wants_it(MOCK_TEXT_WITH_PATTERN) assert len(who_wants_it) == 1 assert who_wants_it[0] == MOCK_PERSON def test_saving_and_loading(tmpdir): notification = notify.Notification() notification.load_from_file(MOCK_TEST_FILE) assert len(notification.patterns) == 0 notification.add_pattern(MOCK_PERSON, MOCK_VALID_PATTERN) notification.save_to_file(MOCK_TEST_FILE) assert len(notification.patterns) == 1 new_notification = notify.Notification() new_notification.load_from_file(MOCK_TEST_FILE) assert len(new_notification.patterns) == 1 assert notification.patterns == new_notification.patterns os.remove(MOCK_TEST_FILE) <file_sep>/README.md # slack-today-i-did A chat-ops bot designed around the principle of ensuring that types for functions are correct. ## Features - slack and repl support - live-reload of functions - live-reload of the entire project - type safe interactions - useful error hints - enable/disable features at runtime - command history ## Setup - You must have Python 3.6 installed - Use virtualenv - To install deps run `pip install -r requirements.txt` - In order to use this bot, you must create a file called `priv.json` which looks like this: ``` { "token": "<SLACK_BOT_TOKEN>", "rollbar-token" : "<ROLLBAR_READ_TOKEN>", "github" : { "token" : "<GITHUB_OAUTH_TOKEN", "repo" : "NoRedInk", "org" : "NoRedInk", "folder" : "repos" } } ``` ## Running - `python main.py` starts up the slack bot by default - `python main.py --repl` starts up the local repl <file_sep>/tests/test_parser.py import pytest import slack_today_i_did.parser as parser MOCK_TOKENS = { 'hello': lambda x:x, 'NOW': lambda x:x } TEXT_WITHOUT_TOKENS = 'dave fish' TEXT_WITH_TOKEN = "hello dave" TEXT_WITH_TOKEN_MISPELLED = "hfllo" TEXT_WITH_TOKENS = "hello dave NOW" def test_tokens_with_index_on_no_tokens(): tokens = parser.tokens_with_index(MOCK_TOKENS, TEXT_WITHOUT_TOKENS) assert len(tokens) == 0 def test_tokens_with_index_on_single_token(): tokens = parser.tokens_with_index(MOCK_TOKENS, TEXT_WITH_TOKEN) assert len(tokens) == 1 first_token = tokens[0] assert first_token[0] == 0 assert first_token[1] == 'hello' def test_tokens_with_index_on_tokens(): tokens = parser.tokens_with_index(MOCK_TOKENS, TEXT_WITH_TOKENS) assert len(tokens) == 2 first_token = tokens[0] second_token = tokens[1] assert first_token[0] == 0 assert first_token[1] == 'hello' assert second_token[0] == 11 assert second_token[1] == 'NOW' def test_tokenize_on_no_tokens(): tokens = parser.tokenize(TEXT_WITHOUT_TOKENS, MOCK_TOKENS) assert len(tokens) == 0 def test_tokenize_on_one_token(): tokens = parser.tokenize(TEXT_WITH_TOKEN, MOCK_TOKENS) assert len(tokens) == 1 first_token = tokens[0] assert first_token[0] == 0 assert first_token[1] == 'hello' assert first_token[2] == 'dave' def test_tokenize_on_tokens(): tokens = parser.tokenize(TEXT_WITH_TOKENS, MOCK_TOKENS) assert len(tokens) == 2 first_token = tokens[0] assert first_token[0] == 0 assert first_token[1] == 'hello' assert first_token[2] == 'dave ' second_token = tokens[1] assert second_token[0] == 11 assert second_token[1] == 'NOW' assert second_token[2] == '' def test_parse_no_tokens(): known_funcs = {'error-help': lambda x:x} stuff = parser.parse([], known_funcs) assert stuff.func_call.func_name == 'error-help' assert stuff.func_call.args == [parser.Constant('NO_TOKENS', str)] def test_parse_first_func_not_in_known_funcs(): # `eval` trusts tokenize to have extracted # only known function names into tokens with pytest.raises(KeyError): stuff = parser.parse([(0, 'help', ''), (0, 'hello', 'dave')], MOCK_TOKENS) def test_eval_help_with_arg(): funcs_with_help = dict(MOCK_TOKENS, help=lambda x:x) tokens = parser.tokenize('help ' + TEXT_WITH_TOKENS, funcs_with_help) stuff = parser.parse(tokens, funcs_with_help) assert stuff.func_call.func_name == 'help' assert stuff.func_call.args[0] == parser.FuncCall('hello', [parser.Constant('dave ', str)], None) assert stuff.func_call.args[1] == parser.FuncCall('NOW', [], None) def test_eval_help_with_badly_spelled_function(): funcs_with_help = dict(MOCK_TOKENS, help=lambda x:x) tokens = parser.tokenize('help ' + TEXT_WITH_TOKEN_MISPELLED, funcs_with_help) stuff = parser.parse(tokens, funcs_with_help) assert stuff.func_call.func_name == 'help' assert stuff.func_call.args == [parser.Constant('hfllo', str)] result = stuff.evaluate(stuff.func_call) assert result.result == 'hfllo' assert result.errors == [] def test_eval_first_func_with_one_arg(): known_funcs = {'hello': lambda x:x} stuff = parser.parse([(0, 'hello', 'world')], known_funcs) assert stuff.func_call.func_name == 'hello' assert stuff.func_call.args == [parser.Constant('world', str)] result = stuff.evaluate(stuff.func_call) assert result.result == 'world' assert result.errors == [] def test_eval_second_func_with_one_arg(): known_funcs = {'cocoa': lambda x:x + 'cocoa', 'double': lambda x:x * 2} known_funcs['double'].__annotations__['return'] = str stuff = parser.parse([(0, 'cocoa', ''), (0, 'double', 'cream')], known_funcs) assert stuff.func_call.func_name == 'cocoa' assert stuff.func_call.args == [parser.FuncCall('double', [parser.Constant('cream', str)], str)] result = stuff.evaluate(stuff.func_call) assert result.result == 'creamcreamcocoa' assert result.errors == [] def test_eval_second_func_with_error(): known_funcs = {'cocoa': lambda x:x + 'cocoa', 'koan': lambda x: 1 / 0} stuff = parser.parse([(0, 'cocoa', ''), (0, 'koan', 'x')], known_funcs) assert stuff.func_call.func_name == 'cocoa' assert stuff.func_call.args == [parser.FuncCall('koan', [parser.Constant('x', str)], None)] result = stuff.evaluate(stuff.func_call) assert result.result == None assert 'koan threw division by zero' in result.errors[0] def test_eval_type_mismtach(): def koan(x: int) -> None: return 1 / 0 known_funcs = {'koan': koan} stuff = parser.parse([(0, 'koan', 'x')], known_funcs) assert stuff.func_call.func_name == 'koan' assert stuff.func_call.args == [parser.Constant('x', str)] result = stuff.evaluate(stuff.func_call) assert 'You tried to give me' in result.errors[0] assert 'but I wanted a `<class \'int\'>`' in result.errors[0] def test_eval_arg_mismtach(): def more(a: str, b: str) -> str: return a + b + ' more' known_funcs = {'more': more} stuff = parser.parse([(0, 'more', 'x')], known_funcs) assert stuff.func_call.func_name == 'more' assert stuff.func_call.args == [parser.Constant('x', str)] result = stuff.evaluate(stuff.func_call) assert 'I wanted things to look like' in result.errors[0] assert 'Need some more' in result.errors[0] <file_sep>/tests/test_sessions.py import pytest import os import slack_today_i_did.reports as reports MOCK_PERSON = 'dave' MOCK_CHANNEL = '#durp' MOCK_TEXT = 'abcdflk' MOCK_TEST_FILE = '.testdata_sessions' def test_start_session(): sessions = reports.Sessions() sessions.start_session(MOCK_PERSON, MOCK_CHANNEL) assert MOCK_PERSON in sessions.sessions assert sessions.has_running_session(MOCK_PERSON) assert sessions.get_entry(MOCK_PERSON).get('channel') == MOCK_CHANNEL assert len(sessions.get_entry(MOCK_PERSON).get('messages')) == 0 sessions.add_message(MOCK_PERSON, MOCK_TEXT) assert sessions.get_entry(MOCK_PERSON).get('channel') == MOCK_CHANNEL assert len(sessions.get_entry(MOCK_PERSON).get('messages')) == 1 assert sessions.get_entry(MOCK_PERSON).get('messages') == [MOCK_TEXT] def test_end_session(): sessions = reports.Sessions() sessions.start_session(MOCK_PERSON, MOCK_CHANNEL) sessions.add_message(MOCK_PERSON, MOCK_TEXT) sessions.end_session(MOCK_PERSON) assert sessions.get_entry(MOCK_PERSON).get('channel') == MOCK_CHANNEL assert len(sessions.get_entry(MOCK_PERSON).get('messages')) == 1 assert sessions.get_entry(MOCK_PERSON).get('messages') == [MOCK_TEXT] assert not sessions.has_running_session(MOCK_PERSON) def test_session_saving_and_loading(tmpdir): sessions = reports.Sessions() sessions.load_from_file(MOCK_TEST_FILE) assert len(sessions.sessions) == 0 sessions.start_session(MOCK_PERSON, MOCK_CHANNEL) sessions.add_message(MOCK_PERSON, MOCK_TEXT) sessions.save_to_file(MOCK_TEST_FILE) new_sessions = reports.Sessions() new_sessions.load_from_file(MOCK_TEST_FILE) assert len(new_sessions.sessions) == 1 assert sessions.sessions == new_sessions.sessions os.remove(MOCK_TEST_FILE) def test_session_retiring(): sessions = reports.Sessions() sessions.start_session(MOCK_PERSON, MOCK_CHANNEL) sessions.add_message(MOCK_PERSON, MOCK_TEXT) sessions.retire_session(MOCK_PERSON, MOCK_TEST_FILE) assert len(sessions.sessions) == 0 with open(MOCK_TEST_FILE) as f: assert MOCK_TEXT in f.read() os.remove(MOCK_TEST_FILE) <file_sep>/slack_today_i_did/text_tools.py def levenshtein(current_word: str, next_word: str) -> int: ''' Returns how similar a word is to the next word as a number no changes return 0 >>> levenshtein('a', 'a') 0 Add a character adds 1 for each character added >>> levenshtein('a', 'ab') 1 >>> levenshtein('a', 'abc') 2 Removing a character adds 1 for each character >>> levenshtein('a', '') 1 >>> levenshtein('abc', '') 3 Replacing a character adds 1 for each character >>> levenshtein('abcdf', 'zxcvb') 4 ''' if current_word == '': return len(next_word) if len(current_word) < len(next_word): current_word, next_word = next_word, current_word previous_row = list(range(len(next_word) + 1)) for i, current_character in enumerate(current_word): current_row = [i + 1] for j, next_character in enumerate(next_word): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (current_character != next_character) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row[:] return previous_row[-1] def token_based_levenshtein(current_words: str, next_words: str) -> int: ''' Returns how similar a word is to the next word as a number no changes return 0 >>> token_based_levenshtein('a', 'a') 0 Add a character adds 1 for each character added >>> token_based_levenshtein('a', 'ab') 1 >>> token_based_levenshtein('a', 'abc') 2 Removing a character adds 1 for each character >>> token_based_levenshtein('a', '') 1 >>> token_based_levenshtein('abc', '') 3 Replacing a character adds 1 for each character >>> token_based_levenshtein('abcdf', 'zxcvb') 4 Adding a word adds 1 char for each word >>> token_based_levenshtein('a', 'a-b') 1 >>> token_based_levenshtein('a', 'a-be-c') 3 >>> token_based_levenshtein('a-b', 'a-be-c') 2 >>> token_based_levenshtein('c-b', 'a-be-c') 3 ''' words = current_words.split('-') next_words = next_words.split('-') if len(words) == 0: return len(next_words) if len(words) < len(next_words): words, next_words = next_words, words previous_row = list(range(len(next_words) + 1)) for i, current_word in enumerate(words): current_row = [i + 1] for j, coming_word in enumerate(next_words): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (current_word != coming_word) word_diff = levenshtein(current_word, coming_word) if word_diff > 1: current_row.append(word_diff) else: current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row[:] return previous_row[-1] <file_sep>/tests/conftest.py import contextlib import pytest @pytest.fixture def message_context(mocker): '''Sets up the specified `bot`'s state as if it just received a message from `sender` and about to parse it. with message_context(bot, MOCK_PERSON): do_stuff_with_the_bot(bot) ''' @contextlib.contextmanager def wrapper(bot, sender): bot_qualname = f'{bot.__class__.__module__}.{bot.__class__.__qualname__}' mocker.patch( f'{bot_qualname}._last_sender', new_callable=mocker.PropertyMock, return_value=sender) mocker.patch.object( bot, 'user_name_from_id', return_value=sender) mocker.patch.object( bot, 'connected_user', return_value=bot.__class__.__name__) mocker.patch.object( bot, 'was_directed_at_me', return_value=True) yield mocker.stopall() return wrapper <file_sep>/slack_today_i_did/extensions.py import datetime from typing import List import json import re from collections import defaultdict import importlib import types from slack_today_i_did.reports import Report from slack_today_i_did.generic_bot import BotExtension, ChannelMessage, ChannelMessages from slack_today_i_did.reports import Sessions from slack_today_i_did.known_names import KnownNames from slack_today_i_did.notify import Notification import slack_today_i_did.parser as parser import slack_today_i_did.text_tools as text_tools class BasicStatements(BotExtension): def for_statement(self, text: str) -> List[str]: """ enter usernames seperated by commas """ return [blob.strip() for blob in text.split(',')] def at_statement(self, text: str) -> datetime.datetime: """ enter a time in the format HH:MM """ return datetime.datetime.strptime(text.strip(), '%H:%M') def wait_statement(self, text: str) -> datetime.datetime: """ enter how much time to wait in the format HH:MM """ return datetime.datetime.strptime(text.strip(), '%H:%M') def now_statement(self) -> datetime.datetime: """ return the current time """ return datetime.datetime.utcnow() def num_statement(self, text: str) -> int: """ return a number value """ try: return int(text) except: return 0 class ExtensionExtensions(BotExtension): def _setup_enabled_tokens(self): """ Store disabled tokens in a dict of token: user Store disabled extensions in just a list of class names """ self._disabled_tokens = {} self._disabled_extensions = [] def _disabled_message(self, who: str, channel: str) -> ChannelMessages: # TODO: this function is currently evaluated in the wrong way by the evaluator # so we send the message by hand self.send_channel_message(channel, f'This function has been disabled by {who}.') return [] def _flatten_bases(self, cls): """ Get all the extensions applied to a bot instance """ bases = cls.__bases__ known_bases = [] for base in bases: if base.__name__ == 'object': continue current_bases = self._flatten_bases(base) known_bases.append(base) if BotExtension in current_bases: known_bases.extend(current_bases) return known_bases def known_functions(self): known_functions = BotExtension.known_functions(self) try: if len(self._disabled_tokens) == 0: return known_functions except: return known_functions wrapped_functions = { k: v for (k, v) in known_functions.items() if k not in self._disabled_tokens } wrapped_functions.update({ token: lambda *args, **kwargs: self._disabled_message(who, *args, **kwargs) for (token, who) in self._disabled_tokens.items() }) return wrapped_functions def known_extensions(self, channel: str) -> ChannelMessages: """ List all extensions used by the current bot """ known_bases = list(set(self._flatten_bases(self.__class__))) message = 'Currently known extensions:\n' message += '\n'.join(base.__name__ for base in known_bases) return ChannelMessage(channel, message) def tokens_status(self, channel: str) -> ChannelMessages: """ Display all the known tokens and if they are enabled """ known_tokens = [ (token, token not in self._disabled_tokens) for token in self.known_tokens() ] message = '\n'.join(f'{token}: {is_enabled}' for (token, is_enabled) in known_tokens) return ChannelMessage(channel, message) def _manage_extension(self, extension_name: str, is_to_enable: bool, disabler: str) -> None: """ Disable or enable an extension, setting who disabled it """ known_bases = list(set(self._flatten_bases(self.__class__))) flipped_tokens = { func.__name__: func_alias for (func_alias, func) in self.known_functions().items() } extensions = [base for base in known_bases if base.__name__ == extension_name] for extension in extensions: for func in extension.__dict__: if func not in flipped_tokens: continue if is_to_enable: self._disabled_tokens.pop(flipped_tokens[func], None) else: self._disabled_tokens[flipped_tokens[func]] = disabler if is_to_enable: self._disabled_extensions.remove(extension.__name__) else: self._disabled_extensions.append(extension.__name__) def enable_extension(self, channel: str, extension_name: str) -> ChannelMessages: """ enable an extension and all it's exposed tokens by name """ self._manage_extension(extension_name, is_to_enable=True, disabler=self._last_sender) return [] def disable_extension(self, channel: str, extension_name: str) -> ChannelMessages: """ disable an extension and all it's exposed tokens by name """ self._manage_extension(extension_name, is_to_enable=False, disabler=self._last_sender) return [] def load_extension(self, channel: str, extension_name: str = None) -> ChannelMessages: """ Load extensions. By default, load everything. Otherwise, load a particular extension """ known_bases = list(set(self._flatten_bases(self.__class__))) known_bases_as_str = [base.__name__ for base in known_bases] func_names = [func.__name__ for func in self.known_functions().values()] meta_funcs = [ func.__name__ for func in self.known_functions().values() if parser.is_metafunc(func) ] # make sure to pick up new changes importlib.invalidate_caches() # import and reload ourselves extensions = importlib.import_module(__name__) importlib.reload(extensions) extension_names = dir(extensions) if extension_name is not None and extension_name.strip() != "": if extension_name not in extension_names: suggestions = [ (text_tools.levenshtein(extension_name, name), name) for name in extension_names ] message = 'No such extension! Maybe you meant one of these:\n' message += ' | '.join(name for (_, name) in sorted(suggestions)[:5]) return ChannelMessage(channel, message) else: extension_names = [extension_name] for extension in extension_names: # skip if the extension is not a superclass if extension not in known_bases_as_str: continue extension_class = getattr(extensions, extension) for (func_name, func) in extension_class.__dict__.items(): # we only care about reloading things in our tokens if func_name not in func_names: continue # ensure that meta_funcs remain so if func_name in meta_funcs: func = parser.metafunc(func) setattr(self, func_name, types.MethodType(func, self)) return [] @parser.metafunc def enable_token(self, channel: str, tokens) -> ChannelMessages: """ enable tokens """ for token in tokens: if token.func_name in self._disabled_tokens: self._disabled_tokens.pop(token.func_name, None) return [] @parser.metafunc def disable_token(self, channel: str, tokens) -> ChannelMessages: """ disable tokens """ for token in tokens: func_name = token.func_name self._disabled_tokens[func_name] = self._last_sender return [] class KnownNamesExtensions(BotExtension): def _setup_known_names(self) -> None: self.known_names = KnownNames() self.known_names.load_from_file(self.known_names_file) def get_known_names(self, channel: str) -> ChannelMessages: """ Grabs the known names to this bot! """ message = [] for (person, names) in self.known_names.people.items(): message.append(f'<@{person}> goes by the names {" | ".join(names)}') if len(message) == '': message = "I don't know nuffin or no one" return ChannelMessage(channel, '\n'.join(message)) def add_known_name(self, channel: str, name: str) -> ChannelMessages: """ adds a known name to the collection for the current_user """ person = self._last_sender self.known_names.add_name(person, name) self.known_names.save_to_file(self.known_names_file) return [] class NotifyExtensions(BotExtension): def _setup_notify(self) -> None: self.notify = Notification() self.notify.load_from_file(self.notify_file) def when_you_hear(self, channel: str, pattern: str) -> ChannelMessages: """ notify the user when you see a pattern """ person = self._last_sender try: re.compile(pattern) except Exception as e: return ChannelMessage(channel, f'Invalid regex due to {e.msg}') self.notify.add_pattern(person, pattern) self.notify.save_to_file(self.notify_file) return ChannelMessage( channel, f'Thanks! You be notified when I hear that pattern. Use `forget` to stop me notifying you!' ) def stop_listening(self, channel: str, pattern: str) -> ChannelMessages: """ stop notify the user when you see a pattern """ person = self._last_sender self.notify.forget_pattern(person, pattern) self.notify.save_to_file(self.notify_file) return [] def ping_person(self, channel: str, person: str) -> ChannelMessages: """ notify a person about a message. Ignore direct messages """ if self.is_direct_message(channel): return return ChannelMessage(channel, f"<@{person}> ^") class ReportExtensions(BotExtension): def responses(self, channel: str) -> ChannelMessages: """ list the last report responses for the current channel """ if channel not in self.reports: return ChannelMessage( channel, f'No reports found for channel {channel}' ) message = "" for report in self.reports[channel].values(): message += f'for the report: {report.name}' message += '\n\n'.join( f'User {user} responded with:\n{response}' for (user, response) in report.responses.items() # noqa: E501 ) return ChannelMessage(channel, message) def report_responses(self, channel: str, name: str) -> ChannelMessages: """ list the last report responses for the current channel """ name = name.strip() if channel not in self.reports or name not in self.reports[channel]: return ChannelMessage( channel, f'No reports found for channel {channel}' ) return self.single_report_responses(channel, self.reports[channel][name]) def single_report_responses(self, channel: str, report) -> ChannelMessages: """ Send info on a single response """ message = '\n\n'.join( f'User {user} responded with:\n{response}' for (user, response) in report.responses.items() # noqa: E501 ) if message == '': message = f'Nobody replied to the report {report.name}' else: message = f'For the report: {report.name}\n' + message return ChannelMessage(channel, message) def bother(self, channel: str, name: str, users: List[str], at: datetime.datetime, wait: datetime.datetime) -> ChannelMessages: # noqa: E501 """ add a report for the given users at a given time, reporting back in the channel requested """ time_to_run = (at.hour, at.minute) wait_for = (wait.hour, wait.minute) self.add_report(Report(channel, name, time_to_run, users, wait_for, reports_dir=self.reports_dir)) return [] def bother_all_now(self, channel: str) -> ChannelMessages: """ run all the reports for a channel """ messages = [] for report in self.reports.get(channel, {}).values(): bothers = [ChannelMessage(*bother) for bother in report.bother_people()] messages.extend(bothers) return messages def add_report(self, report): if report.channel not in self.reports: self.reports[report.channel] = {} self.reports[report.channel][report.name] = report class SessionExtensions(BotExtension): def _setup_sessions(self) -> None: self.sessions = Sessions() self.sessions.load_from_file(self.session_file) def start_session(self, channel: str) -> ChannelMessages: """ starts a session for a user """ person = self._last_sender self.sessions.start_session(person, channel) self.sessions.save_to_file(self.session_file) message = """ Started a session for you. Send a DMs to me with what you're working on throughout the day. Tell me `end-session` to finish the session and post it here! """ return ChannelMessage(channel, message.strip()) def end_session(self, channel: str) -> ChannelMessages: """ ends a session for a user """ person = self._last_sender if not self.sessions.has_running_session(person): return ChannelMessage(channel, 'No session running.') self.sessions.end_session(person) self.sessions.save_to_file(self.session_file) entry = self.sessions.get_entry(person) message = f'Ended a session for the user <@{person}>. They said the following:\n' message += '\n'.join(entry['messages']) return ChannelMessage(entry['channel'], message) class RollbarExtensions(BotExtension): def rollbar_item(self, channel: str, field: str, counter: int) -> ChannelMessages: """ takes a counter, gets the rollbar info for that counter """ rollbar_info = self.rollbar.get_item_by_counter(counter) if field == '' or field == 'all': pretty = json.dumps(rollbar_info, indent=4) else: pretty = rollbar_info.get( field, f'Could not find the field {field}' ) return ChannelMessage(channel, f'{pretty}') class ElmExtensions(BotExtension): def elm_progress(self, channel: str, version: str) -> ChannelMessages: """ give a version of elm to get me to tell you how many number files are on master """ version = version.strip() self.repo.get_ready() message = "" if version == '0.17': message += f"There are {self.repo.number_of_016_files}" elif version == '0.16': message += f"There are {self.repo.number_of_017_files}" else: num_016 = self.repo.number_of_016_files num_017 = self.repo.number_of_017_files message += f"There are {num_016} 0.16 files." message += f"\nThere are {num_017} 0.17 files." message += f"\nThat puts us at a total of {num_017 + num_016} Elm files." return ChannelMessage(channel, message) def elm_progress_on(self, channel: str, branch_name: str) -> ChannelMessages: """ give a version of elm to get me to tell you how many number files are on master """ self.repo.get_ready(branch_name) message = "" num_016 = self.repo.number_of_016_files num_017 = self.repo.number_of_017_files message += f"There are {num_016} 0.16 files." message += f"\nThere are {num_017} 0.17 files." message += f"\nThat puts us at a total of {num_017 + num_016} Elm files." # noqa: E501 return ChannelMessage(channel, message) def find_elm_017_matches(self, channel: str, filename_pattern: str) -> ChannelMessages: # noqa: E501 """ give a filename of elm to get me to tell you how it looks on master """ # noqa: E501 self.repo.get_ready() message = "We have found the following filenames:\n" filenames = self.repo.get_files_for_017(filename_pattern) message += " | ".join(filenames) return ChannelMessage(channel, message) def how_hard_to_port(self, channel: str, filename_pattern: str) -> ChannelMessages: """ give a filename of elm to get me to tell you how hard it is to port Things are hard if: contains ports, signals, native or html. Ports and signals are hardest, then native, then html. """ self.repo.get_ready() message = "We have found the following filenames:\n" with self.repo.cached_lookups(): files = self.repo.get_017_porting_breakdown(filename_pattern) message += f'Here\'s the breakdown for the:' total_breakdowns = defaultdict(int) for (filename, breakdown) in files.items(): total_hardness = sum(breakdown.values()) message += f'\nfile {filename}: total hardness {total_hardness}\n' message += ' | '.join( f'{name} : {value}' for (name, value) in breakdown.items() ) for (name, value) in breakdown.items(): total_breakdowns[name] += value message += '\n---------------\n' message += 'For a total of:\n' message += ' | '.join( f'{name} : {value}' for (name, value) in total_breakdowns.items() ) return ChannelMessage(channel, message) <file_sep>/slack_today_i_did/parser.py from typing import Any, TypeVar, Callable, Dict, List, Tuple, NamedTuple, Union import copy import functools # tokenizer types Token = Tuple[int, str] TokenAndRest = Tuple[int, str, str] # parser types FuncArg = Union['Constant', 'FuncCall'] Constant = NamedTuple( 'Constant', [('value', Any), ('return_type', type)]) FuncCall = NamedTuple( 'FuncCall', [('func_name', str), ('args', List[FuncArg]), ('return_type', type)]) FuncCallBinding = NamedTuple( 'FuncCallBinding', [('func_call', FuncCall), ('evaluate', Callable[[FuncCall, List[FuncArg]], 'FuncResult'])]) FuncResult = NamedTuple( 'FuncResult', [('result', Any), ('return_type', type), ('action', Callable), ('args', List[Any]), ('errors', List[str])]) ArgsResult = NamedTuple( 'ArgsResult', [('result', List[Any]), ('return_types', List[type]), ('errors', List[str])]) FunctionMap = Dict[str, Callable] def metafunc(fn): fn.is_metafunc = True return fn def is_metafunc(fn): return getattr(fn, 'is_metafunc', False) def fill_in_the_gaps(message: str, tokens: List[Token]) -> List[TokenAndRest]: """ take things that look like [(12, FOR)] turn into [(12, FOR, noah)] """ if len(tokens) < 1: return [] if len(tokens) == 1: start_index = tokens[0][0] token = tokens[0][1] bits_after_token = message[start_index + len(token) + 1:] return [(start_index, token, bits_after_token)] builds = [] for (i, (start_index, token)) in enumerate(tokens): if i == len(tokens) - 1: bits_after_token = message[start_index + len(token) + 1:] builds.append((start_index, token, bits_after_token)) continue end_index = tokens[i + 1][0] bits_after_token = message[start_index + len(token) + 1: end_index] builds.append((start_index, token, bits_after_token)) return builds def tokens_with_index(known_tokens: List[str], message: str) -> List[Token]: """ get the tokens out of a message, in order, along with the index it was found at """ build = [] start_index = 0 end_index = 0 for word in message.split(' '): if word in known_tokens: token = word start_index = end_index + message[end_index:].index(token) end_index = start_index + len(token) build.append((start_index, token)) return sorted(build, key=lambda x: x[0]) def tokenize(text: str, known_tokens: List[str]) -> List[TokenAndRest]: """ Take text and known tokens """ text = text.strip() tokens = fill_in_the_gaps(text, tokens_with_index(known_tokens, text)) return tokens def parse(tokens: List[TokenAndRest], known_functions: FunctionMap) -> FuncCallBinding: args = [] # when we can't find anything if len(tokens) == 0: first_function_name = 'error-help' args.append(Constant('NO_TOKENS', str)) # when we have stuff to work with! else: first_function_name = tokens[0][1] first_arg = tokens[0][2].strip() if len(first_arg) > 0: args.append(Constant(first_arg, str)) if len(tokens) > 1: for (start_index, function_name, arg_to_function) in tokens[1:]: func = known_functions[function_name] actual_arg = [Constant(arg_to_function, str)] if len(arg_to_function) > 0 else [] return_type = func.__annotations__.get('return', None) args.append(FuncCall(function_name, actual_arg, return_type)) action = known_functions[first_function_name] return_type = action.__annotations__.get('return', None) evaluator = functools.partial(evaluate_func_call, known_functions) return FuncCallBinding( FuncCall(first_function_name, args, return_type), evaluator) def evaluate_func_call( known_functions: FunctionMap, func_call: FuncCall, default_args: List[FuncArg] = []) -> FuncResult: """ Evaluate `func_call` in the context of `known_functions` after prepending `default_args` to `func_call`'s arguments """ action = known_functions[func_call.func_name] if is_metafunc(action): args = default_args + [Constant(func_call.args, List[FuncArg])] else: args = default_args + func_call.args args_result = evaluate_args(known_functions, args) if len(args_result.errors) > 0: return FuncResult(None, None, None, [], args_result.errors) argument_errors = [] # TODO: simply copy.deepcopy and pop('return', None) after # https://github.com/python/typing/issues/306 is resolved. # `-> ChannelMessages` blows up if you try to copy.deepcopy the annotations. annotations = dict(action.__annotations__) return_type = annotations.pop('return', None) annotations = copy.deepcopy(annotations) # check arity mismatch num_keyword_args = len(action.__defaults__) if action.__defaults__ else 0 num_positional_args = len(annotations) - num_keyword_args if num_positional_args > len(args_result.result): argument_errors.append( mismatching_args_messages( action, annotations, args_result.result, args_result.return_types ) ) mismatching_types = mismatching_types_messages( action, annotations, args_result.result, args_result.return_types ) if len(mismatching_types) > 0: argument_errors.append(mismatching_types) if len(argument_errors) > 0: return FuncResult(None, None, None, [], argument_errors) try: return FuncResult(action(*args_result.result), return_type, action, args_result.result, []) except Exception as e: error_message = exception_error_messages([(func_call.func_name, e)]) return FuncResult(None, None, None, [], [error_message]) def evaluate_args( known_functions: FunctionMap, args: List[FuncArg]) -> ArgsResult: result = [] return_types = [] all_errors = [] for arg in args: if isinstance(arg, Constant): result.append(arg.value) return_types.append(arg.return_type) elif isinstance(arg, FuncCall): func_result = evaluate_func_call(known_functions, arg) result.append(func_result.result) return_types.append(func_result.return_type) if len(func_result.errors) > 0: all_errors.extend(func_result.errors) return ArgsResult(result, return_types, all_errors) def exception_error_messages(errors) -> str: message = f'I got the following errors:\n' message += '```\n' message += '\n'.join( f'- {func_name} threw {error}' for (func_name, error) in errors ) message += '\n```' return message def mismatching_args_messages(action, annotations, arg_values, arg_types) -> str: message = f'I wanted things to look like for function `{action.__name__}`:\n' # noqa: E501 message += '```\n' message += '\n'.join( f'- {arg_name} : {arg_type}' for (arg_name, arg_type) in annotations.items() ) message += '\n```' message += "\nBut you gave me:\n" message += '```\n' message += '\n'.join(f'- {arg_value} : {arg_type}' for (arg_value, arg_type) in zip(arg_values, arg_types)) message += '\n```' if len(annotations) < len(arg_values): return f'Too many arguments!\n{message}' else: return f'Need some more arguments!\n{message}' def mismatching_types_messages(action, annotations, arg_values, arg_types) -> str: messages = [] for (arg_value, arg_type, (arg_name, annotation)) in zip(arg_values, arg_types, annotations.items()): if annotation == Any or isinstance(annotation, TypeVar): continue if arg_type != annotation: messages.append(f'Type mistmach for function `{action.__name__}`') messages.append( f'You tried to give me a `{arg_type}` but I wanted a `{annotation}` for the arg `{arg_name}`!' # noqa: E501 ) return '\n'.join(messages) <file_sep>/slack_today_i_did/self_aware.py import os import subprocess import sys import psutil import logging def git_checkout(branch): os.system('git pull') os.system(f'git checkout {branch}') def git_current_version(): byte_text = subprocess.check_output(["git", "status"], stderr=subprocess.STDOUT) text = byte_text.decode() first_line = text.split('\n')[0] return first_line def python_version(): info = sys.version_info version = f'{info[0]}.{info[1]}.{info[2]}' return version def ruby_version(): byte_text = subprocess.check_output(["ruby", "--version"], stderr=subprocess.STDOUT) text = byte_text.decode() first_line = text.split('\n')[0] return first_line def restart_program(): """Restarts the current program, with file objects and descriptors cleanup """ try: p = psutil.Process(os.getpid()) for handler in p.get_open_files() + p.connections(): os.close(handler.fd) except Exception as e: logging.error(e) python = sys.executable os.execl(python, python, *sys.argv) <file_sep>/slack_today_i_did/rollbar.py """ A file for dealing with rollbar related things """ import requests class Rollbar(object): def __init__(self, token): self.token = token self.base_url = "https://api.rollbar.com" def request(self, url): actual_url = self.base_url + url + f"?access_token={self.token}" return requests.get(actual_url) def get_item_by_id(self, id): response = self.request(f'/api/1/item/{id}') json = response.json() return json def get_item_by_counter(self, counter): response = self.request(f'/api/1/item_by_counter/{counter}') json = response.json() return json['result'] <file_sep>/tests/test_today_i_did_bot.py import pytest import os import inspect import typing import functools import datetime from slack_today_i_did import parser from slack_today_i_did.bot_file import TodayIDidBot MOCK_PERSON = 'dave' MOCK_CHANNEL = '#durp' MOCK_START_SESSION_TEXT = 'start-session' MOCK_TEST_FILE = '.testdata_sessions' MOCK_COMMAND_HISTORY = '.testdata_test_today_i_did_bot_command_history' @pytest.fixture def bot(tmpdir): reports_dir = tmpdir.mkdir("reports") return TodayIDidBot( '', rollbar_token='', elm_repo=None, reports_dir=str(reports_dir), command_history_file=str(tmpdir.join('command_history.json'))) def test_start_session(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': MOCK_START_SESSION_TEXT }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert 'Started a session for you' in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 def test_save_and_load_known_user_func_history(mocker, bot, message_context): dangerous_commands = ('reload', 'reload-funcs') default_args = ('channel',) sample_args = { int: 'NUM 1', str: 'orange', datetime.datetime: 'NOW', typing.List[str]: 'FOR blurb,blabi', inspect._empty: 'help', # guessing it's help's `args` param } expected_func_names = [] for command, func in bot.known_user_functions().items(): if command in dangerous_commands: continue signature = inspect.signature(func) args = (sample_args[param.annotation] for (name, param) in signature.parameters.items() if name not in default_args) message_text = f'{command} {" ".join(args)}'.strip() with message_context(bot, sender=MOCK_PERSON): spy = mocker.spy(bot, func.__name__) mocker.patch.object(bot.rollbar, 'get_item_by_counter', return_value={}) mocker.patch.object(bot, 'repo') # preserve important attributes on the spy functools.update_wrapper(spy, func) if parser.is_metafunc(func): parser.metafunc(spy) bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': message_text }) assert spy.call_count == 1 expected_func_names.append(func.__name__) second_bot = TodayIDidBot('', command_history_file=bot.command_history_file, reports_dir=bot.reports_dir) saved_func_names = [command['action'].__name__ for command in second_bot.command_history.history[MOCK_CHANNEL]] assert saved_func_names == expected_func_names <file_sep>/slack_today_i_did/better_slack.py """ A slack client with much better async support """ from slackclient import SlackClient import websockets import asyncio import ssl import json ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # os x is dumb so this fixes the openssl cert import try: ssl_context.load_verify_locations('/usr/local/etc/openssl/cert.pem') except: pass # we need to redefine these because the slackclient library is bad class SlackLoginError(Exception): pass class SlackConnectionError(Exception): pass class BetterSlack(SlackClient): """ a better slack client with async/await support """ def __init__(self, *args, **kwargs): SlackClient.__init__(self, *args, **kwargs) self.known_users = {} self._conn = None self.message_queue = [] self._should_reconnect = False self._in_count = 0 async def __aenter__(self): reply = self.server.api_requester.do(self.token, "rtm.start") if reply.status_code != 200: raise SlackConnectionError else: login_data = reply.json() if login_data["ok"]: self.ws_url = login_data['url'] if not self._should_reconnect: self.server.parse_slack_login_data(login_data) self._conn = websockets.connect(self.ws_url, ssl=ssl_context) else: raise SlackLoginError self.websocket = await self._conn.__aenter__() return self async def __aexit__(self, *args, **kwargs): await self._conn.__aexit__(*args, **kwargs) async def main_loop(self, parser=None, on_tick=None): async with self as self: while True: while len(self.message_queue) > 0: await self.websocket.send(self.message_queue.pop(0)) if parser is not None: incoming = await self.get_message() try: parser(incoming) except Exception as e: print(f'Error: {e}') if on_tick() is not None: on_tick() self._in_count += 1 if self._in_count > (0.5 * 60 * 3): self.ping() self._in_count = 0 asyncio.sleep(0.5) async def get_message(self): incoming = await self.websocket.recv() json_data = "" json_data += "{0}\n".format(incoming) json_data = json_data.rstrip() data = [] if json_data != '': for d in json_data.split('\n'): data.append(json.loads(d)) for item in data: self.process_changes(item) return data def ping(self): return self.send_to_websocket({"type": "ping"}) def send_to_websocket(self, data): """ Send a JSON message directly to the websocket. See `RTM documentation <https://api.slack.com/rtm` for allowed types. :Args: data (dict) the key/values to send the websocket. """ data = json.dumps(data) self.message_queue.append(data) def set_known_users(self): response = self.api_call('users.list') if not response['ok']: return for member in response['members']: self.known_users[member['name']] = member['id'] def user_name_from_id(self, my_id): for (name, id) in self.known_users.items(): if id == my_id: return name return None def open_chat(self, name: str) -> str: if name not in self.known_users: self.set_known_users() person = self.known_users[name] response = self.api_call('im.open', user=person) return response['channel']['id'] def send_message(self, name: str, message: str) -> None: id = self.open_chat(name) json = {"type": "message", "channel": id, "text": message} self.send_to_websocket(json) def send_channel_message(self, channel: str, message: str) -> None: json = {"type": "message", "channel": channel, "text": message} self.send_to_websocket(json) def connected_user(self, username: str) -> str: if username not in self.known_users: self.set_known_users() return self.known_users[username] def attachment_strings(self, attachment): strings = [] for (k, v) in attachment.items(): if isinstance(v, str): strings.append(v) for field in attachment.get('fields', []): strings.append(field['title']) strings.append(field['value']) return strings <file_sep>/slack_today_i_did/known_names.py import json from typing import List class KnownNames(object): """ Alias a person to a group of names, with saving and loading from disk """ def __init__(self): self.people = {} def add_name(self, person: str, name: str) -> None: if person not in self.people: self.people[person] = [] self.people[person].append(name) def get_names(self, person: str) -> List[str]: return self.people.get(person, []) def load_from_file(self, filename: str) -> None: try: with open(filename) as f: as_json = json.load(f) except FileNotFoundError: return for (person, names) in as_json['people'].items(): self.people[person] = names def save_to_file(self, filename: str) -> None: with open(filename, 'w') as f: json.dump({'people': self.people}, f) <file_sep>/tests/test_generic_bot.py import pytest from slack_today_i_did.generic_bot import GenericSlackBot MOCK_PERSON = 'dave' MOCK_CHANNEL = '#general' @pytest.fixture def bot(): return GenericSlackBot('') def test_func_that_return(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': 'func-that-return None' }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert "The following functions return" in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 def test_help_without_arg(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': 'help' }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert "Main functions:" in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 def test_help_on_metafunc(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': 'help help' }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert "I'll tell you about it" in mocked_channel_message.call_args[0][1] assert "FuncArg" not in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 def test_help_on_func(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': 'help func-that-return' }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert "functions that return things" in mocked_channel_message.call_args[0][1] assert "text : <class 'str'>" in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 def test_help_on_mispelled_func(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': 'help helc' }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert "I did find the following functions" in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 def test_help_on_mispelled_something(mocker, bot, message_context): mocked_channel_message = mocker.patch.object(bot, 'send_channel_message') with message_context(bot, sender=MOCK_PERSON): bot.parse_direct_message({ 'user': MOCK_PERSON, 'channel': MOCK_CHANNEL, 'text': 'help hdebf8u3ijr9jndsiix' }) assert MOCK_CHANNEL == mocked_channel_message.call_args[0][0] assert "I don't know what you mean and have no suggestions" in mocked_channel_message.call_args[0][1] assert mocked_channel_message.call_count == 1 <file_sep>/slack_today_i_did/command_history.py from slack_today_i_did.type_aware import json def makes_state_change(f): def wrapper(self, *args, **kwargs): f(self, *args, **kwargs) self.needs_save = True return wrapper def saves_state(f): def wrapper(self, *args, **kwargs): f(self, *args, **kwargs) self.needs_save = False return wrapper class CommandHistory(object): @saves_state def __init__(self): self.history = {} @makes_state_change def add_command(self, channel, command, args): if channel not in self.history: self.history[channel] = [] self.history[channel].append({'action': command, 'args': args}) def last_command(self, channel): if channel not in self.history: return None return self.history[channel][-1] def __eq__(self, other): if not isinstance(other, self.__class__): return False for channel in self.history: if channel not in other.history: return False if self.history[channel] != other.history[channel]: return False return True @saves_state def load_from_file(self, known_tokens, known_types, filename: str) -> None: """ Load command history from a file """ try: with open(filename) as f: as_json = json.load(f, known_types=known_types) except FileNotFoundError: return except: # sometimes bad things happen to good people return for (channel, commands) in as_json['channels'].items(): for command_entry in commands: command_entry = self._command_entry_from_json(known_tokens, command_entry) self.add_command(channel, command_entry['action'], command_entry['args']) @saves_state def save_to_file(self, filename: str) -> None: """ save command history to a file """ channels = { 'channels': { channel: [self._command_entry_to_json(command) for command in commands] for (channel, commands) in self.history.items() } } # if we can't save it, exit early try: channel_json = json.dumps(channels) with open(filename, 'w') as f: f.write(channel_json) except: return None self.needs_save = False def _command_entry_to_json(self, command_entry): action = command_entry['action'].__name__ return { 'action': action, 'args': command_entry['args'] } def _no_longer_exists(self, *args, **kwargs) -> str: return 'this thing no longer exists!' def _command_entry_from_json(self, known_tokens, json): return { 'action': known_tokens.get(json['action'], self._no_longer_exists), 'args': json['args'] } <file_sep>/.flake8 [flake8] max-line-length: 120 doctests = True
8ccb0f24c4243894278fe534deb2517e51defaef
[ "Markdown", "INI", "Python", "Text", "Shell" ]
28
Shell
eeue56/slack-today-i-did
3db3d5eaedc8d7a1aa6d4adfff79385988717eec
aa83550e89fa11d76f6ac7fa8f8674af56e50db8
refs/heads/master
<repo_name>luyikk/IFS<file_sep>/IFSClient/IFSClient.cs using IFSServ; using Netx.Client; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IFS { public class IFSClient { public NetxSClient Client { get; } public INetxSClientBuilder INetxtBuilder { get; } private IFSService service { get; } public IFSClient(string host, int port, string key) { INetxtBuilder = new NetxSClientBuilder() .ConfigConnection(p => //配置服务器IP { p.Host = host; p.Port = port; p.VerifyKey = key; p.ServiceName = "IFServ"; }) .ConfigSessionStore(() => new Netx.Client.Session.SessionFile()); Client = INetxtBuilder.Build(); } public IFSService GetFSService()=> Client.Get<IFSService>(); } } <file_sep>/ISFSrv/IFSOption.cs using System; using System.Collections.Generic; using System.Text; namespace IFSServ { public class IFSOption { public string Path { get; set; } = "./file"; } } <file_sep>/ISFSrv/Program.cs using System; using Netx.Service.Builder; using Microsoft.Extensions.DependencyInjection; using System.Reflection; using IFSServ.Interface; namespace IFSServ { class Program { static void Main(string[] args) { var server = new NetxServBuilder() .ConfigBase(p => { p.VerifyKey = "123123"; p.ServiceName = "IFServ"; }) .ConfigNetWork(p => p.Port = 1322) .RegisterDescriptors(p => { p.Configure<IFSOption>(option => { option.Path = "./file"; }); p.AddSingleton<IUserVerification, UserVerification>(); }) .RegisterService(Assembly.GetExecutingAssembly()) .Build(); server.Start(); while (true) { Console.ReadLine(); } } } } <file_sep>/IFSClient/IFSService.cs using Netx; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IFSServ { [Build] public interface IFSService { [TAG(1000)] Task<bool> LogOn(string username, string password); [TAG(1001)] Task<List<(string filename, string fullname, byte type, byte[] data)>> GetFs(string path); [TAG(1002)] Task<bool> Del(string filename); } } <file_sep>/ISFSrv/Interface/IUserVerification.cs using System; using System.Collections.Generic; using System.Text; namespace IFSServ.Interface { public interface IUserVerification { bool Verification(string username, string password); } public class UserVerification : IUserVerification { public bool Verification(string username, string password) { return true; } } } <file_sep>/ISFSrv/Interface/IFileActor.cs using Netx; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IFSServ { [Build] public interface IFileActor { [TAG(1)] Task<List<(string filename, string fullname, byte type, byte[] data)>> GetFileList(string basepath, string path); [TAG(2)] Task<bool> Del(string file); } } <file_sep>/Unit.serv/UnitFileInfoGet.cs using IFS; using IFSServ; using IFSServ.Interface; using Microsoft.Extensions.DependencyInjection; using Netx.Actor; using Netx.Service.Builder; using System; using System.Reflection; using Xunit; using Xunit.Abstractions; namespace Unit.serv { public class UnitFileInfoGet { private readonly ITestOutputHelper output; public UnitFileInfoGet(ITestOutputHelper tempOutput) { output = tempOutput; } [Fact] public async void TestServer() { var server = new NetxServBuilder() .ConfigBase(p => { p.VerifyKey = "123123"; p.ServiceName = "IFServ"; }) .ConfigNetWork(p => p.Port = 1322) .RegisterDescriptors(p => { p.Configure<IFSOption>(option => { option.Path = "./"; }); p.AddSingleton<IUserVerification, UserVerification>(); }) .RegisterService(typeof(IFSController).Assembly) .Build(); server.Start(); var client = new IFSClient("127.0.0.1", 1322, "123123"); var service = client.GetFSService(); await service.LogOn("username", "password"); var dir = await service.GetFs("./"); Assert.True(dir.Count > 0); server.Stop(); } [Fact] public async void TestGetFileInfo() { var files = await (new IFSActorController()).GetFileList("./", "./"); Assert.NotNull(files); output.WriteLine($"file length:{files.Count}"); } } } <file_sep>/ISFSrv/IFSController.cs using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Netx.Loggine; using Netx.Service; using System.IO; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using IFSServ.Interface; namespace IFSServ { public class IFSController : AsyncController, IFSService { public ILog Log { get; } public IFSOption Option { get; } public string BasePath => Path.GetFullPath(Option.Path); public IUserVerification Verification { get; } public bool LogIn { get; private set; } public IFSController(IUserVerification verification, IOptions<IFSOption> options, ILogger<IFSController> logger) { Log = new DefaultLog(logger); Option = options.Value; Verification = verification; if (!Directory.Exists(Option.Path)) { Log.Info($"Create base path {Option.Path}"); Directory.CreateDirectory(Option.Path); } } public Task<bool> LogOn(string username, string password) { LogIn = Verification.Verification(username, password); return Task.FromResult(LogIn); } public async Task<bool> Del(string filename) { var ls = Path.GetFullPath(filename, BasePath); checkPathPermission(ls); return await Actor<IFileActor>().Del(ls); } public async Task<List<(string filename, string fullname, byte type, byte[] data)>> GetFs(string path) { checkLogIN(); var ls = Path.GetFullPath(path, BasePath); checkPathPermission(ls); return await Actor<IFileActor>().GetFileList(BasePath, ls); } private void checkPathPermission(string path) { if (path.IndexOf(BasePath) != 0) throw new IOException("Permission denied"); } private void checkLogIN() { if (!LogIn) throw new Exception("Permission denied"); } } } <file_sep>/ISFSrv/IFSActorController.cs using Netx.Actor; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace IFSServ { //12311 [ActorOption(maxQueueCount: 1500, ideltime: 3000)] public class IFSActorController : ActorController, IFileActor { [Netx.Actor.Open(OpenAccess.Internal)] public Task<List<(string filename, string fullname, byte type, byte[] data)>> GetFileList(string basepath,string path) { var files = from p in GetFileInfos(path) select ( p.Name, Path.GetRelativePath(basepath, p.FullName), p is FileInfo ? (byte)0 : (byte)1, p is FileInfo ? GetMD5HashFromFile(p.FullName) : null ); return Task.FromResult(files.ToList()); } private FileSystemInfo[] GetFileInfos(string path) { DirectoryInfo directoryInfo = new DirectoryInfo(path); if (!directoryInfo.Exists) { throw new IOException($"not find path:{path}"); } else { return directoryInfo.GetFileSystemInfos(); } } [Netx.Actor.Open(OpenAccess.Internal)] public Task<bool> Del(string file) { if (File.Exists(file)) { File.Delete(file); return Task.FromResult(true); } return Task.FromResult(false); } public byte[] GetMD5HashFromFile(string fileName) { using (FileStream file = new FileStream(fileName, System.IO.FileMode.Open,FileAccess.Read)) { MD5 md5 = new MD5CryptoServiceProvider(); return md5.ComputeHash(file); } } } }
b2d2e6f32f1231055dc98c057d1ece2e751107a6
[ "C#" ]
9
C#
luyikk/IFS
8505fc595003592dac39657941c53a1ecc8246d5
fbd7b601fbbad8d9744297c11e71a209b376cc6f
refs/heads/master
<file_sep>public class HelloWorld{ system.out.print("hello"); system.out.print("World"); system.out.print("Good Bye!!"); system.out.print("whatever I do for you but it is not enough"); system.out.print("say something"); system.out.print("git diff test"); sysout.out.print("git diff test2"); }
23038011c87aa902f60da583f0eaca311bd5d90b
[ "Java" ]
1
Java
minyjoy/gitTest1
ef950f0f817d5aa852187570e9f5280db444acca
023bedda4d56b12e4a51961718e1a64c9f5ebb44
refs/heads/master
<repo_name>Rayn-hard/Rock-Paper-Scissors<file_sep>/main.py import random choices = ( "rock", "paper", "scissors" ) user_input = input("ENTER YOUR CHOICE [1]rock, [2]paper, OR [3]scissors: ") cpu_input = random.choices(choices) print("\nYOUR CHOICE: " + user_input) print("YOUR OPPONENT'S CHOICE: " + cpu_input[0]) if (user_input == cpu_input[0]): print("\nRESULT: It's a Tie!") elif (user_input == "rock"): if (cpu_input == "paper"): print("\nRESULT: CPU WON!") else: print("\nRESULT YOU WON!") elif (user_input == "paper"): if (cpu_input == "scissors"): print("\nRESULT: CPU WON!") else: print("\nRESULT YOU WON!") elif (user_input == "scissors"): if (cpu_input == "rock"): print("\nRESULT: CPU WON!") else: print("\nRESULT YOU WON!") else: print("\nTRY AGAIN!")
235e7d51a8e29a29e4759fecc62ffd246233c6d0
[ "Python" ]
1
Python
Rayn-hard/Rock-Paper-Scissors
6a84d11e733231deac0dff510409d1ba8fccb5fb
0bf360103236874b648fdbcf1c8b4d598daecf23
refs/heads/main
<file_sep>from django.shortcuts import render,redirect,get_object_or_404 from blog.models import Post from blog import forms from django.http import HttpResponseRedirect from taggit.models import Tag from django.contrib.auth.decorators import login_required # Create your views here. def postlist_view(request,tag_slug=None): post_list=Post.objects.all() tag=None if tag_slug: tag=get_object_or_404(Tag,slug=tag_slug) post_list=post_list.filter(tags__in=[tag]) return render(request,'blog/post_list.html',{'post_list':post_list,'tag':tag}) def postcreate_view(request): form=forms.CreateForm() if request.method=='POST': form=forms.CreateForm(request.POST) if form.is_valid(): form.save() return redirect('/home') return render(request,'blog/post_create.html',{'form':form}) @login_required def postdetail_view(request,year,month,day,post): post=get_object_or_404(Post,status='published',slug=post,publish__year=year,publish__month=month,publish__day=day) comments=post.comments.filter(active=True) csubmit=False if request.method=='POST': form=forms.CommentForm(request.POST) if form.is_valid(): new_comment=form.save(commit=False) new_comment.post=post new_comment.save() csubmit=True else: form=forms.CommentForm() likes=post.likes.filter(active=True) click=False if request.method=='POST': form1=forms.LikeForm(request.POST) if form1.is_valid(): new_like=form1.save(commit=False) new_like.post=post new_like.save() click=True else: form1=forms.LikeForm() return render(request,'blog/post_detail.html',{'post':post,'comments':comments,'csubmit':csubmit,'form':form,'form1':form1,'click':click,'likes':likes}) def postupdate_view(request,id): post_list=Post.objects.get(id=id) if request.method=='POST': form=forms.UpdateForm(request.POST,instance=post_list) if form.is_valid(): form.save() return redirect('/home') return render(request,'blog/post_update.html',{'post_list':post_list}) def postdelete_view(request,id): post=Post.objects.get(id=id) post.delete() return redirect('/home') def signup_view(request): form=forms.SignUpForm() if request.method=='POST': form=forms.SignUpForm(request.POST) if form.is_valid(): user=form.save(commit=True) user.set_password(<PASSWORD>) user.save() return HttpResponseRedirect('/accounts/login') return render(request,'blog/signup.html',{'form':form}) def logout_view(request): return render(request,'blog/logout.html') <file_sep>"""blogproject13 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('home/',views.postlist_view,name='home'), path('create/',views.postcreate_view), path('(?p<year>\d{4})/(?p<month>\d{2})/(?p<day>\d{2})/(?p<post>[-\w+])/$',views.postdetail_view,name='detail'), path('update/<int:id>',views.postupdate_view,name='list'), path('delete/<int:id>',views.postdelete_view), path('signup/',views.signup_view), path('accounts/',include('django.contrib.auth.urls')), path('logout/',views.logout_view), path('tag/(?p<tag_slug>[-\w]+)/$',views.postlist_view,name='post_tags'), ] <file_sep>from django import forms from blog.models import Post,Comment,Like from django.contrib.auth.models import User class CreateForm(forms.ModelForm): class Meta: model=Post fields='__all__' class UpdateForm(forms.ModelForm): class Meta: model=Post fields=('title','body') class CommentForm(forms.ModelForm): class Meta: model=Comment fields=('name','body') class LikeForm(forms.ModelForm): class Meta: model=Like fields=('uname',) class SignUpForm(forms.ModelForm): class Meta: model=User fields=('username','<PASSWORD>','email') <file_sep>from django.contrib import admin from blog.models import Post,Comment,Like class PostAdmin(admin.ModelAdmin): list_display=['title','slug','author','body','publish','created','updated','status'] list_filter=('status','created') prepopulated_fields={'slug':('title',)} search_fields=('title','body') raw_id_fields=('author',) date_hierarchy='publish' class CommentAdmin(admin.ModelAdmin): list_display=['post','name','email','body','created','updated','active'] list_filter=('created','active') date_hierarchy='created' class LikeAdmin(admin.ModelAdmin): list_display=['post','uname','email','created','updated','active'] list_filter=('created','active') date_hierarchy='created' # Register your models here. admin.site.register(Post,PostAdmin) admin.site.register(Comment,CommentAdmin) admin.site.register(Like,LikeAdmin) <file_sep>from django.http import HttpResponse class AppMaintainance(object): def __init__(self,get_response): self.get_response=get_response def __call__(self,request): return HttpResponse('<h1>currently our application is under maintainance ..please try again sometime.!</h1>') <file_sep># Generated by Django 2.1 on 2021-02-05 16:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0003_like'), ] operations = [ migrations.RenameField( model_name='like', old_name='name', new_name='uname', ), ]
e21cfdb8678c294077f2e7d21f9b8a74a15b26fd
[ "Python" ]
6
Python
BaluG123/blogremote_repo1
a07c4115187b991934e8931c1a1686a149a994f0
19cc0a83ec1c9494ee905c1ff4dece58da386089
refs/heads/master
<file_sep>spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:postgres://bzcpxabopdlmdf:3d6cf<PASSWORD>6@ec2-52-1-20-236.compute-1.amazonaws.com:5432/dfagg9s7tge7ak spring.datasource.username=bzcpxabopdlmdf spring.datasource.password=<PASSWORD> spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true <file_sep>package com.rodrigo.bookstore.dtos; import java.io.Serializable; import com.rodrigo.bookstore.domain.Livro; public class LivroDTO implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Integer id; private String titulo; private String nomeAutor; private String textoLivro; public LivroDTO() { super(); // TODO Auto-generated constructor stub } public LivroDTO(Livro obj) { super(); this.id = obj.getId(); this.titulo = obj.getTitulo(); this.nomeAutor = obj.getNomeAutor(); this.textoLivro = obj.getTextoLivro(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getNomeAutor() { return nomeAutor; } public void setNomeAutor(String nomeAutor) { this.nomeAutor = nomeAutor; } public String getTextoLivro() { return textoLivro; } public void setTextoLivro(String textoLivro) { this.textoLivro = textoLivro; } } <file_sep>spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost/BOOKSTORE?createDatabaseIfNotExist=true&serverTimezone=UTC&useSSl=false spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true <file_sep>package com.rodrigo.bookstore.resources.exception; import javax.servlet.ServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.rodrigo.bookstore.exception.DataIntegrityVioletionException; import com.rodrigo.bookstore.exception.ObjNotFoundException; @ControllerAdvice public class ResourceExceptionHandler { @ExceptionHandler(ObjNotFoundException.class) public ResponseEntity<StandardError> objNotFoundException(ObjNotFoundException e, ServletRequest request) { StandardError error = new StandardError(System.currentTimeMillis(), HttpStatus.NOT_FOUND.value(), e.getMessage()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error); } @ExceptionHandler(DataIntegrityVioletionException.class) public ResponseEntity<StandardError> DataIntegrityVioletionException(DataIntegrityVioletionException e, ServletRequest request) { StandardError error = new StandardError(System.currentTimeMillis(), HttpStatus.BAD_REQUEST.value(), e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error); } }
7ad9924d7f280b93c23b8f5b70f36e8b47d6fa5d
[ "Java", "INI" ]
4
INI
RodrigoARDSJ/BookStore-Back
857a927908ede45bbe08b8d9be04c18f7883f770
51905bbb9f5bbf9a1c84e56d734b7ffdf6bbf409
refs/heads/master
<file_sep>class PostsController < ApplicationController def update @post = Post.find(params[:id]) return head(:forbidden) unless current_user.admin? || current_user.vip? || current_user.try(:id) == @post.id @post.update(content: params[:post][:content]) end end
2645b696d8d1de0cdc34e81e072c4a52b566c3ed
[ "Ruby" ]
1
Ruby
ns5001/devise_roles_lab-wdf-000
0163bb5923057f7c4f41efddfb3e692f7a3258b4
54270beab1e7332203a3a45645109c458219df00
refs/heads/master
<repo_name>Nick-T-Hansen/data-structures-lists<file_sep>/Program.cs using System; using System.Collections.Generic; namespace data_structures_lists { class Program { static void planetPrinter(List<string> stringList){ foreach(string item in stringList){ Console.WriteLine(item); } } static void Main(string[] args) { List<string> planetList = new List<string>(){"Mercury", "Mars"}; planetList.ForEach(planet => Console.Write($"{planet}" + " ")); Console.WriteLine(); // Add() Jupiter and Saturn at the end of the list. planetList.Add("Jupiter"); planetList.Add("Saturn"); planetList.ForEach(planet => Console.Write($"{planet}" + " ")); Console.WriteLine(); //adding using the planetPrinter method Console.WriteLine("//// Testing new method planetPrinter ////"); planetPrinter(planetList); Console.WriteLine("//// End method test ////"); // Create another List that contains that last two planet of our solar system. List<string> lastPlanets = new List<string>(){"Uranus", "Neptune"}; foreach(string aplanet in lastPlanets){ Console.Write($"{aplanet}" + " "); } Console.WriteLine(); // Combine the two lists by using AddRange(). planetList.AddRange(lastPlanets); foreach(string planet in planetList){ Console.Write($"{planet}" + " "); } Console.WriteLine(); // Use Insert() to add Earth, and Venus in the correct order. planetList.Insert(1, "Venus"); planetList.Insert(2, "Earth"); foreach(string planet in planetList){ Console.Write($"{planet}" + " "); } Console.WriteLine(); // Use Add() again to add Pluto to the end of the list. planetList.Add("Pluto"); foreach(string planet in planetList){ Console.Write($"{planet}" + " "); } Console.WriteLine(); // Now that all the planets are in the list, slice the list using GetRange() in order to extract the rocky planets into a new list called rockyPlanets. The rocky planets will remain in the original planets list. List<string> rockyPlanets = planetList.GetRange(0, 4); foreach(string planet in rockyPlanets){ Console.Write($"{planet}" + " "); } Console.WriteLine(); // Being good amateur astronomers, we know that Pluto is now a dwarf planet, so use the Remove() method to eliminate it from the end of planetList. planetList.Remove("Pluto"); foreach(string planet in planetList){ Console.Write($"{planet}" + " "); } Console.WriteLine(); // ------------------------<< Numbers exercise >>------------------------------ Random random = new Random(); List<int> numbers = new List<int> { random.Next(10), random.Next(10), random.Next(10), random.Next(10), random.Next(10), }; for(int i = 0; i < numbers.Count; i++) { if (numbers.Contains(i)) { Console.WriteLine($"{i} is in the list"); } else { Console.WriteLine ($"{i} is not in the list of numbers."); } } } } }
bb3ed65fbea457df5de619d9803c8c684504d5c0
[ "C#" ]
1
C#
Nick-T-Hansen/data-structures-lists
51a1b507e98c4cd23bb9f3a20f97958ed9e9aaff
ca1b0a4b81fad667e79f66cd6c911804b0437def
refs/heads/master
<file_sep># jQuery plugin "animateSubelements" ### Plugin animate subelements -direct children of selected element with specific parameters: - animation type, - properitys specific for animation type (in array), - delay and - displaySub ### How to install? Plugin is in js folder in animateSubelementsPlugin.js file. Copy this file to your js files and import to your code: ``` import animateSubelementsPlugin from "./animateSubelementsPlugin.js"; ``` Remember to change the script type attribute in the html file with the main js file in this way: ```<script type="module" src="<your js file js>"></script>``` ### How to use? ##### You must put 3 parameters: 1. animation type in string - like "fadeIn", "fadeOut", "slideDown", "slideUp", "animate" or another 2. properity in array - parameters corresponding to the type of animation selected above 3. delay in ms - daley animation 4. displaySub in string - "none" if animation subelements must "display: none" before animation start or "" if not ``` $("<example_elements>").animateSubelements({ animation: "<animation type>", properity: [<properity1>, <properity1>, <...> ], delay: <number in ms>, displaySub: "<"none" or "">" }) ``` ### Settings defaults If you use a plugin without parameters or do not put one of the parameters, the plugin will set the default parameters: ``` { animation: "fadeOut", properity: [500], delay: 500, displaySub: "" } ``` ### Example: ``` $("div").animateSubelements({ animation: "fadeIn", properity: [600], delay: 600, displaySub: "none" }); ``` ``` $(".test2").animateSubelements({ animation: "animate", properity: [ { width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 500 ], delay: 500 }); ``` ### How to start a demo? Clone this repository and put commands: ``` npm install npm run browsersync ``` <file_sep>/* plugin animate subelements, direct children of selected element with specific parameters: animation type, properitys specific for aniamtion type (in array), delay and displaySub (none if animation subelement must display none before animation start or "" if not). */ export default (function($) { $.fn.animateSubelements = function(config) { const options = $.extend( { animation: "fadeOut", properity: [500], delay: 500, displaySub: "" }, config ); return this.each(function() { const subelement = $(this).children(); subelement.css("display", options.displaySub); subelement.each(function(i) { $(this).delay(options.delay * (i + 1)); $(this)[options.animation](...options.properity); }); }); }; })(jQuery); <file_sep>import animateSubelementsPlugin from "./animateSubelementsPlugin.js"; //Examples runing $(".test1").animateSubelements({ animation: "slideDown", properity: [500], delay: 500, displaySub: "none" }); $(".test3").animateSubelements({ animation: "slideUp", properity: [500], delay: 500 }); $("div").animateSubelements({ animation: "fadeIn", properity: [600], delay: 600, displaySub: "none" }); $(".test2").animateSubelements({ animation: "animate", properity: [ { width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 500 ], delay: 500 });
d0de83292bd4bc375b948d5e73648abf6160d6e3
[ "Markdown", "JavaScript" ]
3
Markdown
jaceksanko/jQuery_plugin_animate_subelements
f277ebc283bffc334bd0957561294b6bdc029da0
96c96305718ba358bbc7ae61b415e092985d4be2
refs/heads/main
<file_sep>#include<stdio.h> #include<iostream.h> #include<stdlib.h> #include<string.h> #include<conio.h> #include<ctype.h> #include<dos.h> #include<graphics.h> #define true 1 #define false 0 void disp(); void printmenu();void intro(); void levelmenu();void easy(); void initial(int x); void draw(int x, int y, int i); void userwin(int no);int check(int key); int load,i,step,level,num[25],win; void main() { int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi"); intro(); levelmenu(); clrscr(); cleardevice(); setbkcolor(RED); easy(); } void levelmenu() { level=0; clrscr(); cleardevice(); setbkcolor(BLACK); settextstyle(1,0,2); setcolor(GREEN); outtextxy(240,240,"Press 1 to start"); outtextxy(240,260,"----------------"); outtextxy(240,280,"1. Start"); outtextxy(240,300,"2. Rules"); outtextxy(240,330,"Enter a choice: "); gotoxy(50+4,22); scanf("%d", &level); if(level==2) { outtextxy(20,40,"Read the rules :"); outtextxy(20,80,"1: Arrange the nos in ascending order"); outtextxy(20,120,"2: Press the no key to move the nos"); outtextxy(20,160,"3: X-Exit"); delay(3000); levelmenu(); } } void intro() { int i,j; clrscr(); cleardevice(); setbkcolor(0); gotoxy (25,12); settextstyle(4,0,6); for(i=0;i<=10;i++) { setcolor(i%16); outtextxy(2,2,"SHUFFLE GAME"); settextstyle(1,0,7); outtextxy(20,200,""); delay(100); outtextxy(180,200,"G"); delay(100); outtextxy(220,200,"A"); delay(100); outtextxy(260,200,"M"); delay(100); outtextxy(300,200,"E"); delay(100); outtextxy(220,300,""); delay(100); outtextxy(260,300,""); delay(100); outtextxy(180,400,""); delay(100); outtextxy(220,400,""); settextstyle(4,0,8); delay(100); getch(); } } void printmenu() { int i; gotoxy(33,1);printf("PUZZEL GAME"); gotoxy(1,2); for(i=0; i<80; i++) printf("\xcd"); printf("\t\t\t\tX=exit game\n"); for(i=0; i<80; i++) printf("\xcd"); gotoxy (35,23);printf("Moves = %d", step); } void easy() { int i, x, y,key; char press[2]; if(load==false) initial(9); else load=false; do{ start: printmenu(); i=0; for(y=8; y<17; y+=4) for(x=33; x<44; x+=5) { draw(x,y,i); i++; } userwin(8); if(win==true) { cleardevice(); outtextxy(2,2,"You have won the game"); delay(2000); disp(); delay(2000); win=false; return; } gotoxy (55,17);printf("Tips:"); gotoxy (61,18);printf("Number will move"); gotoxy (61,19);printf("when you key in!"); gotoxy (43,23);fflush(stdin); press[0]=toupper(getche()); if(press[0]=='X') { disp(); exit(1); }key=atoi(press); if((check(key))==0) { goto start; } step++; if(step==50) { cleardevice(); outtextxy(20,200,"YOU HAVE SURPASSED MAXIMUM POSSIBLE MOVES"); delay(1500); disp(); delay(2500); exit(1); } for(i=0; i<9; i++) { if(num[i]==key) num[i]=0; else if(num[i]==0) num[i]=key; } }while(1); } void initial(int x) { int i,no; step=0; no=0%x; if(no==1) no+=5; for(i=0; i<x; i++) { num[i]=no; no+=2; if(no>=x) if(!(no%2)) no=1; else no=0; } } void draw(int x, int y, int i) { gotoxy (x,y); if(level==1) { printf("%c%c%c",201,205,187); gotoxy (x,y+1); printf("%c",186); if(num[i]==0) printf(" "); else printf("%d", num[i]); printf("%c",186); gotoxy (x,y+2); printf("%c%c%c",200,205,188); } } void disp() { cleardevice(); setbkcolor(BLACK); settextstyle(4,0,4); setcolor(RED); outtextxy(200,100,"CREDITS:"); settextstyle(2,0,13); outtextxy(300,220,"<NAME>"); outtextxy(300,260,"AIML"); outtextxy(300,300,"2020-2024"); delay(2500); } int check(int key) { int i, valid=0; if(level==1) for(i=0; i<9; i++) { if(num[i]==key) { valid=true; switch(i) { case 0: if(num[1]!=0 && num[3]!=0)valid=0;break; case 1: if(num[0]!=0 && (num[2]!=0 && num[4]!=0)) valid=0;break; case 2: if(num[1]!=0 && num[5]!=0)valid=0;break; case 3: if(num[0]!=0 && (num[4]!=0 && num[6]!=0)) valid=0;break; case 4: if((num[1]!=0 && num[3]!=0) && (num[5]!=0 && num[7]!=0))valid=0;break; case 5: if(num[2]!=0 && (num[4]!=0 && num[8]!=0)) valid=false;break; case 6: if(num[3]!=0 && num[7]!=0)valid=0;break; case 7: if(num[4]!=0 && (num[6]!=0 && num[8]!=0)) valid=0;break; case 8: if(num[5]!=0 && num[7]!=0)valid=0;break; default:valid=0;break; } } } return valid; } void userwin(int no) { int i; for(i=0; i<no ; i++) if(num[i]!=i+1) { win=false; break; } else win=true; } <file_sep># **bgi or dos error resolve** Puzzel game made for project in c++ To check the whether graphics driver is available or not, you have to quit the turbo c++ shell and you will be taken to the C:\TURBOC3\BIN. You will have to change the directory to check whether bgi driver is available or not. So you can change directory by CD... and press enter. After changing the directory you will be taken to C:\TURBOC3\ after which you will have to go to next directory by entering C:\TURBOC3\BGI and press enter to check whether bgi graphics driver is available. If available then only this program will run successfully <file_sep> <a href="https://discord.gg/uxZSS9HavF"><img src="https://img.shields.io/discord/766634629657919512?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a> ![GitHub followers](https://img.shields.io/github/followers/katochayush?style=social) ![Twitter Follow](https://img.shields.io/twitter/follow/AYUSHKATOCH12?style=social) ![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCFhFdoMvHFGS7kpKZ3vC5ig?style=social) # Puzzle-game-c Puzzle game made for project in c++ This program is good example of using graphics concept to develop an application using C++. Under this game a number game has been prepared by which users will able to get graphical mode on command line interface. # How-to-play To start this game, you have to press any key, for few seconds the color of the written texts in graphics will change in different colors and it will be redirected to the next section. In the next section you will be given choice for making your selection. There will be two types of option. Option 1 will be to play the game and option 2 will be the instruction which you have to follow while playing this game If you will press 2, the instruction will be shown on the above screen and if you will press 1 its screen will change and redirected to next section where you have to play the game by moving the numbers. You have to press number which you want to move and use arrow keys to move the particular number to the desired location
38c66844109ed5ad5a2a692125f408abde303dd5
[ "Markdown", "C++" ]
3
C++
katochayush/Puzzel-game-c
ea2e19af72d848251e4a6f1a6e1646abd527bc35
8c78d8edf877ab65d038d2b1d77c009321c27c17
refs/heads/master
<repo_name>ursm/ember-decorators<file_sep>/tests/unit/inject-test.js import Ember from 'ember'; import { moduleFor } from 'ember-qunit'; import { test } from 'qunit'; import { controller } from 'ember-decorators/controller'; import { service } from 'ember-decorators/service'; moduleFor('Inject Decorators', { integration: true }); test('service decorator works without service name', function(assert) { const FooService = Ember.Object.extend(); this.register('service:foo', FooService); this.register('class:baz', Ember.Object.extend({ @service foo: null })); const baz = this.container.lookup('class:baz'); assert.ok(baz.get('foo') instanceof FooService, 'service injected correctly'); }); test('service decorator works with service name', function(assert) { const FooService = Ember.Object.extend(); this.register('service:foo', FooService); this.register('class:baz', Ember.Object.extend({ @service('foo') fooService: null })); const baz = this.container.lookup('class:baz'); assert.ok(baz.get('fooService') instanceof FooService, 'service injected correctly'); }); test('controller decorator works without controller name', function(assert) { const FooController = Ember.Controller.extend(); this.register('controller:foo', FooController); this.register('class:baz', Ember.Controller.extend({ @controller foo: null })); const baz = this.container.lookup('class:baz'); assert.ok(baz.get('foo') instanceof FooController, 'service injected correctly'); }); test('controller decorator works with controller name', function(assert) { const FooController = Ember.Controller.extend(); this.register('controller:foo', FooController); this.register('class:baz', Ember.Controller.extend({ @controller('foo') foo: null })); const baz = this.container.lookup('class:baz'); assert.ok(baz.get('foo') instanceof FooController, 'service injected correctly'); }); <file_sep>/addon/object/index.js import Ember from 'ember'; import computedMacro from 'ember-macro-helpers/computed'; import extractValue from '../utils/extract-value'; import { decorator, decoratorWithParams } from '../utils/decorator-wrappers'; import { decoratorWithRequiredParams } from '../utils/decorator-macros'; /** * Decorator that turns the target function into an Action * * Adds an `actions` object to the target object and creates a passthrough * function that calls the original. This means the function still exists * on the original object, and can be used directly. * * Before: * * ```js * export default Ember.Component.extend({ * actions: { * foo() { * // do something * } * } * }); * ``` * * After: * * ```js * import { action } from 'ember-decorators/object'; * * export default MyComponent extends Ember.Component { * @action * foo() { * // do something * } * } * ``` * * @function */ export const action = decorator(function(target, key, desc) { const value = extractValue(desc); if (typeof value !== 'function') { throw new Error('The @action decorator must be applied to functions'); } if (!target.hasOwnProperty('actions')) { let parentActions = target.actions; target.actions = parentActions ? Object.create(parentActions) : {}; } target.actions[key] = value; return value; }); /** * Decorator that turns a function into a computed property. * * In your application where you would normally have: * * ```javascript * foo: Ember.computed('someKey', 'otherKey', function() { * var someKey = this.get('someKey'); * var otherKey = this.get('otherKey'); * * // Do Stuff * }) * ``` * * You replace with this: * * ```javascript * import computed from 'ember-decorators/object'; * * // ..... <snip> ..... * @computed('someKey', 'otherKey') * foo(someKey, otherKey) { * // Do Stuff * } * ``` * * #### Without Dependent Keys * * ```javascript * foo: Ember.computed(function() { * // Do Stuff * }) * ``` * * You replace with this: * * ```javascript * import computed from 'ember-decorators/object'; * * // ..... <snip> ..... * @computed * foo() { * // Do Stuff * } * ``` * * #### "Real World" * * ```javascript * import Ember from 'ember'; * import computed from 'ember-decorators/object'; * * export default Ember.Component.extend({ * @computed('first', 'last') * name(first, last) { * return `${first} ${last}`; * } * }); * ``` * * * #### "Real World get/set syntax" * * ```javascript * import Ember from 'ember'; * import computed from 'ember-decorators/object'; * * export default Ember.Component.extend({ * @computed('first', 'last') * name: { * get(first, last) { * return `${first} ${last}`; * }, * * set(value, first, last) { * // ... * } * } * }); * ``` * * @function * @param {...String} propertyNames - List of property keys this computed is dependent on */ export const computed = decoratorWithParams(function(target, key, desc, params) { if (!desc.writable) { throw new Error('ember-decorators does not support using getters and setters'); } let value = extractValue(desc); return computedMacro(...params, value); }); /** * Decorator that wraps [Ember.observer](https://emberjs.com/api/#method_observer) * * Triggers the target function when the dependent properties have changed * * ```javascript * import Ember from 'ember'; * import { observes } from 'ember-decorators/object'; * * export default Ember.Component.extend({ * @observes('foo') * bar() { * //... * } * }); * ``` * * @function * @param {...String} eventNames - Names of the events that trigger the function */ export const observes = decoratorWithRequiredParams(Ember.observer, 'Cannot `observe` without property names'); /** * Decorator that modifies a computed property to be read only. * * Usage: * * ```javascript * import Ember from 'ember'; * import { computed, readOnly } from 'ember-decorators/object'; * * export default Ember.Component.extend({ * @readOnly * @computed('first', 'last') * name(first, last) { * return `${first} ${last}`; * } * }); * ``` * * @function */ export const readOnly = decorator(function(target, name, desc) { var value = extractValue(desc); return value.readOnly(); });
e1a69cb8189ef49803073eae918a196a9832b2fe
[ "JavaScript" ]
2
JavaScript
ursm/ember-decorators
bb7aadbe75eec37525015d66d128aff9eff1a832
13150a83c97a0cc907ae2aae84531753b0a1446c
refs/heads/master
<file_sep># frozen_string_literal: true module RequestHandler VERSION = '0.14.0'.freeze end <file_sep># frozen_string_literal: true require 'spec_helper' describe RequestHandler do context 'SchemaParser' do context 'BodyParser' do let(:valid_body) do <<-JSON { "data": { "attributes": { "name": "About naming stuff and cache invalidation" } } } JSON end let(:invalid_body) do <<-JSON { "data": { "attributes": { "foo": "About naming stuff and cache invalidation" } } } JSON end context 'valid schema' do let(:testclass) do Class.new(RequestHandler::Base) do options do body do schema(Dry::Validation.JSON do required(:name).filled(:str?) end) end end def to_dto OpenStruct.new( body: body_params ) end end end it 'raises a SchemaValidationError with invalid data' do request = build_mock_request(params: {}, headers: {}, body: invalid_body) testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::SchemaValidationError) end it 'raises a MissingArgumentError with missing data' do request = instance_double('Rack::Request', params: {}, env: {}, body: nil) testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::MissingArgumentError) end it 'works for valid data' do request = build_mock_request(params: {}, headers: {}, body: valid_body) testhandler = testclass.new(request: request) expect(testhandler.to_dto).to eq(OpenStruct.new(body: { name: 'About naming stuff and cache invalidation' })) end end context 'invalid schema' do let(:testclass) do Class.new(RequestHandler::Base) do options do body do schema 'Foo' end end def to_dto OpenStruct.new( body: body_params ) end end end it 'raises a InternalArgumentError valid data' do request = build_mock_request(params: {}, headers: {}, body: valid_body) testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::InternalArgumentError) end end end context 'FilterParser' do let(:valid_params) do { 'filter' => { 'name' => 'foo' } } end let(:invalid_params) do { 'filter' => { 'bar' => 'foo' } } end context 'valid schema' do let(:testclass) do Class.new(RequestHandler::Base) do options do filter do schema(Dry::Validation.Form do required(:name).filled(:str?) end) defaults(foo: 'bar') end end def to_dto OpenStruct.new( filter: filter_params ) end end end it 'raises a SchemaValidationError with invalid data' do request = build_mock_request(params: invalid_params, headers: {}, body: '') testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::SchemaValidationError) end it 'raises a MissingArgumentError with missing data' do request = build_mock_request(params: nil, headers: {}, body: '') testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::MissingArgumentError) end it 'works for valid data' do request = build_mock_request(params: valid_params, headers: {}, body: '') testhandler = testclass.new(request: request) expect(testhandler.to_dto).to eq(OpenStruct.new(filter: { name: 'foo', foo: 'bar' })) end end context 'invalid schema' do let(:testclass) do Class.new(RequestHandler::Base) do options do filter do schema 'Foo' end end def to_dto OpenStruct.new( filter: filter_params ) end end end it 'raises a InternalArgumentError with valid data' do request = build_mock_request(params: valid_params, headers: {}, body: '') testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::InternalArgumentError) end end end context 'QueryParser' do let(:valid_params) do { 'name' => 'foo', 'filter' => { 'post' => 'bar' } } end let(:invalid_params) do { 'name' => nil, 'filter' => { 'post' => 'bar' } } end context 'valid schema' do let(:testclass) do Class.new(RequestHandler::Base) do options do query do schema(Dry::Validation.Form do optional(:name).filled(:str?) end) end end def to_dto OpenStruct.new( query: query_params ) end end end it 'raises a SchemaValidationError with invalid data' do request = build_mock_request(params: invalid_params, headers: {}, body: '') testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::SchemaValidationError) end it 'raises a MissingArgumentError with missing data' do request = build_mock_request(params: nil, headers: {}, body: '') testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::MissingArgumentError) end it 'works for valid data' do request = build_mock_request(params: valid_params, headers: {}, body: '') testhandler = testclass.new(request: request) expect(testhandler.to_dto).to eq(OpenStruct.new(query: { name: 'foo' })) end end context 'invalid schema' do let(:testclass) do Class.new(RequestHandler::Base) do options do query do schema 'Foo' end end def to_dto OpenStruct.new( query: query_params ) end end end it 'raises a InternalArgumentError with valid data' do request = build_mock_request(params: valid_params, headers: {}, body: '') testhandler = testclass.new(request: request) expect { testhandler.to_dto }.to raise_error(RequestHandler::InternalArgumentError) end end end end end
0a3a67a31ea532ff63d1fd01c170f1cc15ca0aab
[ "Ruby" ]
2
Ruby
ahmgeek/request_handler
d62ac8d9d6ece346b109e74d749a019a9258fe85
cf0f60ddbec3688b90aca673d12d8b67fa27ffb6
refs/heads/master
<file_sep>from django.http import JsonResponse from celery.result import AsyncResult from .models import Task from .tasks import work_with_file def submit(request): url = request.POST['url'] email = request.POST.get('email', False) task = work_with_file.delay(url, email) Task.objects.create(url=url, identifier=task.id, status='running').save() answer = {'id': task.id} return JsonResponse(answer) def check(request): ident = request.GET.get('id') try: task = Task.objects.get(identifier=ident) except Task.DoesNotExist: answer = {'status': 'task does not exist'} return JsonResponse(answer, status=404) if task.status == 'done': answer = {'md5': task.md5, 'status': 'done', 'url': task.url} return JsonResponse(answer) else: if Task.status == 'failed' or AsyncResult(ident).failed(): answer = {'status': 'failed'} task.status = 'failed' task.save() return JsonResponse(answer, status=500) else: answer = {'status': 'running'} return JsonResponse(answer, status=102) <file_sep>from django.urls import path, re_path from . import views urlpatterns = [ path('submit', views.submit, name='submit'), path('check', views.check, name='check'), ] <file_sep>from django.contrib import admin from .models import Task class TaskAdmin(admin.ModelAdmin): list_display = ('url', 'md5', 'status', 'identifier', 'email') admin.site.register(Task, TaskAdmin)<file_sep>Django>=2.2.7,<2.3.0 celery>=4.3.0,<4.4.0 django-celery>=3.3.1,<3.4.0<file_sep>from django.db import models class Task(models.Model): url = models.CharField(max_length=128) md5 = models.CharField(max_length=32, null=True, blank=True) status = models.CharField(max_length=20) identifier = models.CharField(max_length=32) email = models.CharField(max_length=32, null=True, blank=True) <file_sep>import hashlib from urllib.request import urlretrieve from urllib.parse import urlsplit from django.core.mail import send_mail from .models import Task from BostonGeneTestTask.celery import app @app.task def work_with_file(url, email): fname = download_file(url) fhash = md5(fname) if email: send_email(email, url, fhash) task = Task.objects.get(url=url, md5=None) task.status = 'done' task.md5 = fhash task.email = email task.save() return url, fhash def download_file(url): split = urlsplit(url) fname = 'files/' + split.path.split('/')[-1] urlretrieve(url, fname) return fname def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def send_email(email, url, fhash): send_mail('md5 hash', 'url: ' + url + '\nmd5: ' + fhash, '<EMAIL>', [email], fail_silently=False)<file_sep>#Запуск проекта: >docker-compose up<file_sep>from __future__ import absolute_import, unicode_literals import os from celery import Celery # Setting the Default Django settings module from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BostonGeneTestTask.settings') app = Celery('BostonGeneTestTask') # Using a String here means the worker will always find the configuration information app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
2c16ff821df505538cbf7f9aaa206a75a65a02a7
[ "Markdown", "Python", "Text" ]
8
Python
VovkoO/boston-gene-test-task
de42ccb45fff59580d172b475f4d5397af4d7c1c
2b95168ff163b728c0026a1ac37054fd7443f5c2
refs/heads/master
<file_sep>package net.thehorizonmc.hub.dueling.handler; import net.thehorizonmc.hub.dueling.Dueling; import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; /** * Created by Ethan on 4/1/2016. */ public class ChallengeHandler { /** * Map that keeps track of who requests who to a sumo challenge. */ public Map<Player, Player> request = new HashMap<Player, Player>(); /** * Map that keeps track of whoever challenged and their challenge. */ public Map<Player, Player> challengerMap = new HashMap<Player, Player>(); /** * Map that keeps track of whoever was challenged and their challenger. */ public Map<Player, Player> challengedMap = new HashMap<Player, Player>(); /** * Instance of the class */ public Dueling instance; /** * Constructor * @param instance */ public ChallengeHandler(Dueling instance) { this.instance = instance; } /** * Finalize a challenge between two players. * @param challenger * @param target */ public void challenge(Player challenger, Player target) { challengerMap.put(challenger, target); challengedMap.put(target, challenger); instance.getGame().initiated.add(challenger); instance.getGame().initiated.add(target); // Find open mat. // instance.getGame().find(challenger, target); } /** * Find the targeted player for a player. * @param challenger * @return */ public Player getTarget(Player challenger) { if(!challengerMap.containsKey(challenger)) return null; return challengerMap.get(challenger); } /** * Get a player's challenger. * @param target * @return */ public Player getChalleneger(Player target) { if(!challengedMap.containsKey(target)) return null; return challengedMap.get(target); } }
af623c021b48045c3c80582912f43d92b464aec5
[ "Java" ]
1
Java
Violantic/Hub
628fad6bf59456150b2e59fc779b5cff1bdd7376
0b762cf38acd0552448ec59d5b9ab1bc77f7dcd0
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Runtime.Serialization.Formatters.Binary; using System; using System.IO; public class game_handler : MonoBehaviour { public List<GameObject> indice_objetos; public List<GameObject> spawns; public List<int> vidas_j; public List<int> puntos_j; public float offset_x_lifes; // Use this for initialization void Start() { load_data(); } void spawn_j1() { for (int i = 0; i < vidas_j[0]; i++) //Recorro las vidas del Jugador { GameObject newVida = Instantiate(indice_objetos[4], GameObject.Find("corchete1").transform); //Instanciar una nueva vida y agregar como hijo al corchete correspondiente newVida.GetComponent<RectTransform>().position += new Vector3((i) * offset_x_lifes, 0, 0); //Posiciono vida segun el offset (elemento i) newVida.name = "Vida" + i; } GameObject newBilly = Instantiate(indice_objetos[0], spawns[0].transform.position, Quaternion.identity); newBilly.name = "Billy"; newBilly.GetComponent<player_handler>().player_n = 1; } void spawn_j2() { for (int i = 0; i < vidas_j[0]; i++) //Recorro las vidas del Jugador { GameObject newVida = Instantiate(indice_objetos[4], GameObject.Find("corchete2").transform); //Instanciar una nueva vida y agregar como hijo al corchete correspondiente newVida.GetComponent<RectTransform>().position += new Vector3((i) * offset_x_lifes, 0, 0); //Posiciono vida segun el offset (elemento i) newVida.name = "Vida" + i; } GameObject newCormano = Instantiate(indice_objetos[1], spawns[1].transform.position, Quaternion.identity); newCormano.name = "Cormano"; newCormano.GetComponent<player_handler>().player_n = 2; } void actualizar_puntos(int n_jugador) { string numero_corchete_jugador = "corchete" + n_jugador.ToString(); GameObject.Find(numero_corchete_jugador).transform.Find("txt_puntos").GetComponent<Text>().text = "$" + puntos_j[n_jugador - 1].ToString(); } public void set_vidas(int valor, int jugador_n) { Debug.Log(jugador_n); vidas_j[jugador_n] += valor; //Le incrementa x vidas al jugador_n if (valor < 0) { check_vidas(jugador_n); //Chequeamos si le quedan vidas para respawnear if(vidas_j[jugador_n] >= 0) eliminar_vida(jugador_n); //Actualizo GUI } } void check_vidas(int jugador_n) { if (vidas_j[jugador_n] >= 0) //Compruebo si el jugador tiene mas de 0 vidas { string nombre_jugador = "respawn_j" + (jugador_n+1); Invoke(nombre_jugador, 2.0f); //Respawneo al jugador dentro de 2 segundos } else //Se murio y no tiene mas vidas { for(int i = 0; i < vidas_j.Count; i++) //Recorro cuantos jugadores existan para ver si alguno tiene vidas, sino termino el juego { if(vidas_j[i] > 0) //Si algun jugador todavia tiene vidas o esta vivo con su ultima { return; //No termino el juego, finalizo la funcion } } Invoke("back_menu", 3.0f); //Espero 3 segundos para volver al menu } } void back_menu() { SceneManager.LoadScene(0); //Carga el menu principal } void respawn_j1() { GameObject newBilly = Instantiate(indice_objetos[0], spawns[0].transform.position, Quaternion.identity); newBilly.name = "Billy"; newBilly.GetComponent<player_handler>().player_n = 1; } void respawn_j2() { GameObject newCormano = Instantiate(indice_objetos[1], spawns[1].transform.position, Quaternion.identity); newCormano.name = "Cormano"; newCormano.GetComponent<player_handler>().player_n = 2; } void eliminar_vida(int jugador_n) //Actualiza las vidas en la interfaz (GUI/HUD) { string nombre_corchete = "corchete" + (jugador_n+1); if(GameObject.Find(nombre_corchete).transform.Find("Vida" + vidas_j[jugador_n])) { Destroy(GameObject.Find(nombre_corchete).transform.Find("Vida" + vidas_j[jugador_n]).gameObject); } } public void asignar_puntos(int n_jugador, int puntos_n) { puntos_j[n_jugador] += puntos_n; //Le agrego puntos_n al jugador_n actualizar_puntos(n_jugador+1); } // Update is called once per frame void Update () { } void load_data() { int cant_players = 1; if (File.Exists(Application.persistentDataPath + "/gamedata.dat")) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/gamedata.dat", FileMode.Open); //Generamos lectura del archivo cant_players = (int)bf.Deserialize(file); //Todas las lineas de lectura (importante orden) file.Close(); for(int i = 0; i < cant_players; i++) { vidas_j[i] = 0; //Le asigno 2 vidas a la cantidad de players que se haya seleccionado } } spawn_j1(); //Siempre spawnea al menos al jugador 1 if(cant_players > 1) { spawn_j2(); } for(int i = 0; i < cant_players; i++) { actualizar_puntos(i+1); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //Libreria de UI y Funciones de Interfaz using UnityEngine.SceneManagement; //Libreria para administrar escenas using System.Runtime.Serialization.Formatters.Binary; using System; using System.IO; public class menu_handler : MonoBehaviour { bool opc_act = true; //True es 1 player, false es 2 player public GameObject pistola1; public GameObject pistola2; public datos data_g = new datos(); //Creamos un objeto del tipo datos (serializable) // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Z)) //Tecla select { opc_act = !opc_act; //Siempre va a la opcion contraria (el opuesto) if(opc_act) //Si es player 1 (cambiar grafico pistola a player 1) { data_g.players = 1; pistola1.GetComponent<Image>().enabled = true; pistola2.GetComponent<Image>().enabled = false; } else //Si es player 2 (cambiar grafico pistola a player 2) { data_g.players = 2; pistola2.GetComponent<Image>().enabled = true; pistola1.GetComponent<Image>().enabled = false; } } if(Input.GetKeyDown(KeyCode.X)) //Start { save_data(); SceneManager.LoadScene(1); //Cambio a la escena 1 (escena del juego) } } void save_data() { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/gamedata.dat", FileMode.Create); bf.Serialize(file, data_g.players); //Guardo este dato //Si tuviera mas datos los guardo aca, importante el orden porque se leeran en mismo orden file.Close(); } [Serializable] public class datos { public int players = 1; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class camara_handler : MonoBehaviour { public GameObject min; public GameObject max; public bool min_act = false; public bool max_act = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (max_act && !min_act) { if (max.transform.position.x < GameObject.FindGameObjectWithTag("Nivel").GetComponent<level_handler>().max.transform.position.x) { transform.position += new Vector3(0.02f, 0, 0); //Aumenta posicion de camara en 5X } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class spawn_e1 : MonoBehaviour { public int num_enemigo; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void OnBecameVisible() { GameObject newEnemy = Instantiate(GameObject.Find("GameHandler").GetComponent<game_handler>().indice_objetos[num_enemigo], transform.position, Quaternion.identity); //Instanciamos nuevo enemigo Destroy(gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class bala : MonoBehaviour { Vector2 velocidad; public float vel_desp; public int n_jugador; //Numero de jugador propietario de este proyectil // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void FixedUpdate() { GetComponent<Rigidbody2D>().position += velocidad * Time.deltaTime; } private void OnBecameInvisible() { Destroy(gameObject); } private void OnCollisionEnter2D(Collision2D collision) { if(transform.tag == "Bala_E" && collision.gameObject.tag == "Player") { collision.gameObject.GetComponent<player_handler>().muerte(); } else if(transform.tag == "Bala_J" && collision.gameObject.tag == "Enemigo") { collision.gameObject.GetComponent<enemy1_handler>().muerte(); GameObject.Find("GameHandler").GetComponent<game_handler>().asignar_puntos(n_jugador, collision.gameObject.GetComponent<enemy1_handler>().puntos); //Asignamos puntos al jugador que lo mato } } public void asignar_velocidad(float angulo) { velocidad.x = vel_desp * Mathf.Cos(deg2rad(angulo)); //ADYACENTE = HIPOTENUSA * COS ANGULO velocidad.y = vel_desp * Mathf.Sin(deg2rad(angulo)); //OPUESTO = HIPOTENUSA * SIN ANGULO } public float deg2rad(float angulo) { return angulo * 3.14f / 180.0f; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class enemy1_handler : MonoBehaviour { Vector2 velocidad; bool is_grounded = false; bool plataforma = false; bool cooldown = true; public float vel_desp; public float vel_salto; public GameObject bala; public GameObject spawns; public GameObject laser_spawn; public int puntos; //Puntos que otorgara el enemigo al morir private Vector2 pos_min; private Vector2 pos_max; public enum estados { idle, walking, jump, shooting, dead } public estados estado_actual = estados.walking; enum direcciones { derecha, izquierda, arriba, abajo, derarr, derab, izqarr, izqab } direcciones direccion = direcciones.izquierda; // Use this for initialization void Start () { pos_min = GameObject.Find("min").transform.position; pos_max = GameObject.Find("max").transform.position; GetComponent<Animator>().SetInteger("estado", 7); Invoke("disparar", 1.5f); } // Update is called once per frame void Update() { if (estado_actual != estados.dead) //Si no esta muerto entonces chequeo teclas, etc { if(estado_actual == estados.walking && is_grounded) { if(!GetComponent<SpriteRenderer>().flipX) { velocidad.x = -vel_desp; } else { velocidad.x = vel_desp; } } } } public void muerte() { if (estado_actual != estados.dead) //Si no estaba muerto, muere { velocidad.x = 0; GetComponent<Animator>().SetInteger("estado", 6); //Cambio estado 1 (animacion caminar) estado_actual = estados.dead; Destroy(gameObject, 1.0f); } } private void FixedUpdate() { if (!is_grounded) { velocidad += Physics2D.gravity * Time.deltaTime; //Multiplicamos gravedad * tiempo para obtener velocidad (v = a*t) } GetComponent<Rigidbody2D>().position += velocidad * Time.deltaTime; check_limites(); } void check_limites() { if (GetComponent<Rigidbody2D>().position.x > pos_max.x) { GetComponent<Rigidbody2D>().position = new Vector2(pos_max.x, GetComponent<Rigidbody2D>().position.y); } else if (GetComponent<Rigidbody2D>().position.x < pos_min.x) { GetComponent<Rigidbody2D>().position = new Vector2(pos_min.x, GetComponent<Rigidbody2D>().position.y); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Suelo" || (collision.gameObject.tag == "Plataforma" && velocidad.y < 0)) { if (!is_grounded) { is_grounded = true; velocidad.y = 0; GetComponent<Animator>().SetInteger("estado", 0); //Cambio estado 1 (animacion caminar) if (collision.gameObject.tag == "Plataforma") plataforma = true; else plataforma = false; if (estado_actual == estados.dead) velocidad.x = 0; } } else if (collision.gameObject.tag == "Plataforma" && velocidad.y > 0) { GetComponent<Animator>().SetInteger("estado", 5); //Cambio estado trepar velocidad.y += vel_salto * 1.0f; } if (collision.gameObject.tag == "Obstaculo") //Si colisiona un obstaculo { velocidad.x = 0; //Velocidad en X es 0 (no avanza) RaycastHit2D col = Physics2D.Raycast(new Vector2(laser_spawn.transform.position.x, laser_spawn.transform.position.y), new Vector2(0, 1)); //Creamos Raycast (suerte de laser) para detectar plataforma sup if (col != null && col.collider != null) //Si colisiono con algo y no estoy tratando de detectar la nada misma { if (col.collider.gameObject.tag == "Plataforma") { if(is_grounded) saltar(); } } GetComponent<SpriteRenderer>().flipX = !GetComponent<SpriteRenderer>().flipX; //Hago el volteado contrario (opuesto) } if(estado_actual != estados.dead && collision.gameObject.tag == "Bala_J") //Si colisiono con bala de jugador { GameObject.Find("GameHandler").GetComponent<game_handler>().asignar_puntos(collision.gameObject.GetComponent<bala>().n_jugador, puntos); //Asignamos puntos al jugador que lo mato muerte(); } } private void OnCollisionExit2D(Collision2D collision) //Al salir de colision { if ((collision.gameObject.tag == "Plataforma" || collision.gameObject.tag == "Obstaculo") && velocidad.y <= 0) //Chequeo si el objeto del cual sali es una plataforma u obstaculo { if (collision.transform.position.y < transform.position.y) { is_grounded = false; //Habilito la caida GetComponent<Animator>().SetInteger("estado", 7); //Estado cayendo (animacion) } } } void saltar() { velocidad.x = 0; GetComponent<Animator>().SetInteger("estado", 7); //Cambio estado 2 (animacion jump) velocidad.y += vel_salto; is_grounded = false; } void disparar() { if(is_grounded && estado_actual != estados.dead) { int resultado = Random.Range(0, 11); //Recordar que al ser int el maximo no sera inclusivo (en este caso es de 0 a 10) if(resultado > 5) { estado_actual = estados.shooting; velocidad.x = 0; GameObject jugador = GameObject.FindGameObjectWithTag("Player").transform.Find("Corazon").gameObject; Vector2 distancia = new Vector2(jugador.transform.position.x - Mathf.Abs(transform.position.x), (jugador.transform.position.y - transform.position.y)); //Distancia entre enemigo y jugador (Vector) if(distancia.x > 0) { GetComponent<SpriteRenderer>().flipX = true; } else { GetComponent<SpriteRenderer>().flipX = false; } float angulo = Mathf.Atan2(distancia.y, distancia.x); //Utilizo Pitagoras (Tang Ang = Op / Ady) para obtener el angulo al que tendria que apuntar angulo *= Mathf.Rad2Deg; if(angulo < 0f) angulo += 360; angulo = Mathf.Round(angulo / 45); //Esto es para que solo pueda rotar cada 45° angulo *= 45; Vector3 spawn_bala = determinar_posicion(angulo); //Determinare el punto de spawn de la bala GameObject newBala = Instantiate(bala, spawn_bala, Quaternion.identity); newBala.GetComponent<bala>().asignar_velocidad(angulo); newBala.tag = "Bala_E"; //Le pongo etiqueta de Bala_E (bala enemigo) Invoke("cooldown_reincorporarse", 1.0f); //Reincorporo para correr } } Invoke("disparar", 1.5f); } void cooldown_reincorporarse() { estado_actual = estados.walking; GetComponent<Animator>().SetInteger("estado", 0); } Vector3 determinar_posicion(float angulo) { if(angulo == 0) { GetComponent<Animator>().SetInteger("estado", 3); return spawns.transform.Find("Spawn_D").transform.position; } else if(angulo == 90) { GetComponent<Animator>().SetInteger("estado", 1); return spawns.transform.Find("Spawn_AR").transform.position; } else if(angulo == 180) { GetComponent<Animator>().SetInteger("estado", 3); return spawns.transform.Find("Spawn_I").transform.position; } else if(angulo == 270) { GetComponent<Animator>().SetInteger("estado", 4); return spawns.transform.Find("Spawn_AB").transform.position; } else if(angulo == 45) { GetComponent<Animator>().SetInteger("estado", 2); return spawns.transform.Find("Spawn_DARR").transform.position; } else if(angulo == 135) { GetComponent<Animator>().SetInteger("estado", 2); return spawns.transform.Find("Spawn_IARR").transform.position; } else if(angulo == 225) { GetComponent<Animator>().SetInteger("estado", 4); return spawns.transform.Find("Spawn_IAB").transform.position; } else if(angulo == 315) { GetComponent<Animator>().SetInteger("estado", 4); return spawns.transform.Find("Spawn_DAB").transform.position; } return new Vector3(0,0,0); } void habilitar_cooldown() { cooldown = true; GetComponent<Animator>().SetInteger("estado", 0); } public void check_direccion(Vector3 posicion) { GameObject newBala = Instantiate(bala, posicion, Quaternion.identity); switch (direccion) { case direcciones.derecha: newBala.GetComponent<bala>().asignar_velocidad(0); break; case direcciones.izquierda: newBala.GetComponent<bala>().asignar_velocidad(180); break; case direcciones.arriba: newBala.GetComponent<bala>().asignar_velocidad(90); break; case direcciones.abajo: newBala.GetComponent<bala>().asignar_velocidad(270); break; case direcciones.derab: newBala.GetComponent<bala>().asignar_velocidad(315); break; case direcciones.derarr: newBala.GetComponent<bala>().asignar_velocidad(45); break; case direcciones.izqab: newBala.GetComponent<bala>().asignar_velocidad(225); break; case direcciones.izqarr: newBala.GetComponent<bala>().asignar_velocidad(135); break; } } private void OnBecameInvisible() //Al salir de la camara { Destroy(gameObject); //Destruye el objeto } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class player_handler : MonoBehaviour { Vector2 velocidad; bool is_grounded = false; bool plataforma = false; bool cooldown = true; public int player_n; public float vel_desp; public float vel_salto; public GameObject spr1; public GameObject bala; public GameObject spr2; public GameObject spawns; public GameObject spr_sup; public GameObject spr_inf; public GameObject ref_colA; public GameObject ref_colI; public GameObject ref_posA; public GameObject ref_posI; public GameObject ref_flipV; public GameObject ref_flipF; Vector2 last_collider; public List<KeyCode> tecla; private Vector2 pos_min; private Vector2 pos_max; enum estados { idle, walking, jump, dead } estados estado_actual = estados.idle; bool[] teclas = { false, false, false, false }; //0 Arriba, 1 Abajo,2 Izquierda, 3 Derecha enum direcciones {derecha,izquierda,arriba,abajo,derarr,derab,izqarr,izqab } direcciones direccion = direcciones.derecha; void Start() { //Bloque pos_min = GameObject.Find("min").transform.position; pos_max = GameObject.Find("max").transform.position; GetComponent<Animator>().SetInteger("estado", 2); spr2.transform.position += new Vector3(-0.09f, 0, 0); } void Update () { //Actualizar if (estado_actual != estados.dead) //Si no esta muerto entonces chequeo teclas, etc { Vector3 posicion = transform.position; //Creamos una variable para copiar la posicion del transform provisoriamente //SI presiono tal tecla hace tal cosa if (Input.GetKeyDown(tecla[1]) && GetComponent<Animator>().GetInteger("estado") != 3) { teclas[2] = true; velocidad.x = -vel_desp; if (!spr1.GetComponent<SpriteRenderer>().flipX) { spr1.GetComponent<SpriteRenderer>().flipX = true; spr2.GetComponent<SpriteRenderer>().flipX = true; if (is_grounded) spr2.transform.position += new Vector3(-0.07f, 0, 0); else spr2.transform.position += new Vector3(0.09f, 0, 0); } if (is_grounded) { GetComponent<Animator>().SetInteger("estado", 1); //Cambio estado 1 (animacion walk) } } if (Input.GetKeyDown(tecla[3]) && GetComponent<Animator>().GetInteger("estado") != 3) { teclas[3] = true; velocidad.x = vel_desp; if (spr1.GetComponent<SpriteRenderer>().flipX) { spr1.GetComponent<SpriteRenderer>().flipX = false; spr2.GetComponent<SpriteRenderer>().flipX = false; if (is_grounded) spr2.transform.position += new Vector3(+0.07f, 0, 0); else spr2.transform.position += new Vector3(-0.09f, 0, 0); } if (is_grounded) GetComponent<Animator>().SetInteger("estado", 1); //Cambio estado 1 (animacion walk) } if (((Input.GetKeyUp(tecla[1]) && velocidad.x < 0) || (Input.GetKeyUp(tecla[3]) && velocidad.x > 0))) { velocidad.x = 0.0f; if (is_grounded) GetComponent<Animator>().SetInteger("estado", 0); //Cambio estado 1 (animacion walk) } if (Input.GetKeyDown(tecla[2]) && is_grounded) { velocidad.x = 0.0f; GetComponent<Animator>().SetInteger("estado", 3); //Agacha spr2.transform.position = ref_posA.transform.position; transform.position += new Vector3(0, -0.2f, 0); GetComponent<BoxCollider2D>().offset = ref_colA.GetComponent<BoxCollider2D>().offset; GetComponent<BoxCollider2D>().size = ref_colA.GetComponent<BoxCollider2D>().size; if (spr1.GetComponent<SpriteRenderer>().flipX) { spr2.transform.position = new Vector2(ref_flipV.transform.position.x, spr2.transform.position.y); } else { spr2.transform.position = new Vector2(ref_flipF.transform.position.x, spr2.transform.position.y); } } if (Input.GetKeyUp(tecla[2]) && (GetComponent<Animator>().GetInteger("estado") == 3 || GetComponent<Animator>().GetInteger("estado") == 0 || GetComponent<Animator>().GetInteger("estado") == 1)) { GetComponent<Animator>().SetInteger("estado", 0); //Idle transform.position += new Vector3(0, 0.2f, 0); if(spr1.GetComponent<SpriteRenderer>().flipX) { spr2.transform.position = ref_flipV.transform.position; } else { spr2.transform.position = ref_flipF.transform.position; } GetComponent<BoxCollider2D>().offset = ref_colI.GetComponent<BoxCollider2D>().offset; GetComponent<BoxCollider2D>().size = ref_colI.GetComponent<BoxCollider2D>().size; } if (Input.GetKeyDown(tecla[0])) teclas[0] = true; if (Input.GetKeyDown(tecla[2])) teclas[1] = true; if (Input.GetKeyUp(tecla[1])) teclas[2] = false; if (Input.GetKeyUp(tecla[3])) teclas[3] = false; if (Input.GetKeyUp(tecla[0])) teclas[0] = false; if (Input.GetKeyUp(tecla[2])) teclas[1] = false; if (Input.GetKeyUp(tecla[5]) && is_grounded) //Salto { if (GetComponent<Animator>().GetInteger("estado") != 3) { GetComponent<Animator>().SetInteger("estado", 2); //Cambio estado 2 (animacion jump) velocidad.y += vel_salto; is_grounded = false; if (!spr1.GetComponent<SpriteRenderer>().flipX) { spr2.transform.position += new Vector3(-0.09f, 0, 0); } else { spr2.transform.position += new Vector3(0.09f, 0, 0); } } else if (plataforma) //Si esta agachado voy a querer ver si esta en plataforma para bajarlo { plataforma = false; GetComponent<Animator>().SetInteger("estado", 2); spr2.transform.position += new Vector3(0, -0.0911f, 0); is_grounded = false; if (!spr1.GetComponent<SpriteRenderer>().flipX) { spr2.transform.position += new Vector3(-0.09f, 0, 0); } else { spr2.transform.position += new Vector3(0.09f, 0, 0); } } } if (Input.GetKeyDown(tecla[4]) && cooldown) { cooldown = false; chequear_teclas(); Invoke("habilitar_cooldown", 0.5f); } } } public void muerte() { if (estado_actual != estados.dead) //Si no estaba muerto, entonces muere { GetComponent<Animator>().SetInteger("estado", 5); //Cambio estado 1 (animacion caminar) spr_sup.GetComponent<Animator>().SetInteger("estado", 7); estado_actual = estados.dead; GameObject.Find("GameHandler").GetComponent<game_handler>().set_vidas(-1, player_n-1); //Quitamos vida al jugador string nombre_spawn = "spawn_j" + player_n; GameObject.Find(nombre_spawn).transform.position = Camera.main.transform.position; Destroy(gameObject, 2.0f); } } private void FixedUpdate() { detectar_suelo(); detectar_obstaculo(); if (!is_grounded) { velocidad += Physics2D.gravity * Time.deltaTime; //Multiplicamos gravedad * tiempo para obtener velocidad (v = a*t) } GetComponent<Rigidbody2D>().position += velocidad * Time.deltaTime; check_limites(); } void detectar_obstaculo() { RaycastHit2D col; if (!spr1.GetComponent<SpriteRenderer>().flipX) col = Physics2D.Raycast(new Vector2(transform.Find("Pies").transform.position.x, transform.Find("Pies").transform.position.y), new Vector2(1, 0)); else col = Physics2D.Raycast(new Vector2(transform.Find("Pies").transform.position.x, transform.Find("Pies").transform.position.y), new Vector2(-1, 0)); if (col && col.transform.tag == "Obstaculo") //Si colisiona un obstaculo { if (Mathf.Abs(col.point.x - transform.Find("Pies").transform.position.x) < 0.08f) { Debug.Log(col.point.x - transform.Find("Corazon").transform.position.x); velocidad.x = 0; //Velocidad en X es 0 (no avanza) if (GetComponent<Animator>().GetInteger("estado") == 1) //Si estaba caminando { GetComponent<Animator>().SetInteger("estado", 0); //Lo pongo en reposo } if (!spr1.GetComponent<SpriteRenderer>().flipX) { transform.position += new Vector3(-0.09f, 0, 0); } else { transform.position += new Vector3(0.09f, 0, 0); } } } } void detectar_suelo() { RaycastHit2D col = Physics2D.Raycast(new Vector2(transform.Find("Corazon").transform.position.x, transform.Find("Corazon").transform.position.y), new Vector2(0, -10)); if (col && GetComponent<Animator>().GetInteger("estado") != 3 && (col.collider.tag == "Suelo" || col.collider.tag == "Plataforma" || col.collider.tag == "Obstaculo")) { last_collider = col.point; if (Mathf.Abs(col.point.y - transform.Find("Pies").transform.position.y) > 0.05f && is_grounded) //Si la distancia entre pies y collider (suelo) es mayor a 10 { cayendo(); } else if(Mathf.Abs(col.point.y - transform.Find("Pies").transform.position.y) <= 0.03f) { transform.position = new Vector3(transform.position.x, col.point.y + (transform.position.y - transform.Find("Pies").transform.position.y) + 0.03f, transform.position.z); if (col.transform.tag == "Suelo" || (col.transform.tag == "Obstaculo" && velocidad.y < 0) || (col.transform.tag == "Plataforma" && velocidad.y < 0)) { if (!is_grounded) { is_grounded = true; velocidad.y = 0; if (velocidad.x != 0) //Si la velocidad es diferente a 0, es porque me estoy moviendo hacia algun lado GetComponent<Animator>().SetInteger("estado", 1); //Cambio estado 1 (animacion caminar) else GetComponent<Animator>().SetInteger("estado", 0); //Cambio estado 0 (animacion idle) spr_sup.GetComponent<Animator>().SetInteger("estado", 0); //CAmbio a idle la parte de arriba tambien if (!spr1.GetComponent<SpriteRenderer>().flipX) { spr2.transform.position += new Vector3(0.09f, 0, 0); } else { spr2.transform.position += new Vector3(-0.09f, 0, 0); } if (col.transform.tag == "Plataforma") plataforma = true; else plataforma = false; if (estado_actual == estados.dead) velocidad.x = 0; } } } } else { if(GetComponent<Animator>().GetInteger("estado") != 3) transform.position = new Vector3(transform.position.x, last_collider.y + (transform.position.y - transform.Find("Pies").transform.position.y) + 0.1f, transform.position.z); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.transform.tag == "Bala_E" || collision.gameObject.transform.tag == "Enemigo") //Si colisiono con bala de enemigo { if (collision.gameObject.transform.tag == "Enemigo" && collision.gameObject.transform.GetComponent<enemy1_handler>().estado_actual == enemy1_handler.estados.dead) { return; //Salgo y no ejecuto muerte porque el enemigo ya esta muerto y no quiero que afecte al personaje } muerte(); if (is_grounded) //Si esta en el suelo cuando murio velocidad.x = 0; //Detener } else if (collision.gameObject.transform.tag == "Plataforma" && velocidad.y > 0 && teclas[0] == true) { GetComponent<Animator>().SetInteger("estado", 4); //Cambio estado trepar spr_sup.GetComponent<Animator>().SetInteger("estado", 6); velocidad.y += vel_salto * 1.2f; } } void check_limites() { if(GetComponent<Rigidbody2D>().position.x > pos_max.x) { GetComponent<Rigidbody2D>().position = new Vector2(pos_max.x, GetComponent<Rigidbody2D>().position.y); } else if(GetComponent<Rigidbody2D>().position.x < pos_min.x) { GetComponent<Rigidbody2D>().position = new Vector2(pos_min.x, GetComponent<Rigidbody2D>().position.y); } float ancho_camara = Camera.main.aspect * Camera.main.orthographicSize; //Obtengo mitad del ancho de la camara segun su relacion de aspecto en la proyeccion ortografica if (GetComponent<Rigidbody2D>().position.x < Camera.main.transform.position.x - ancho_camara) //Si me fui en X al inferior de la camara entonces { GetComponent<Rigidbody2D>().position = new Vector2(Camera.main.transform.position.x - ancho_camara, GetComponent<Rigidbody2D>().position.y); } if (GetComponent<Rigidbody2D>().position.x > GameObject.Find("cam_max").transform.position.x) //Si me fui en X al inferior de la camara entonces { GetComponent<Rigidbody2D>().position = new Vector2(GameObject.Find("cam_max").transform.position.x, GetComponent<Rigidbody2D>().position.y); } } void cayendo() { is_grounded = false; //Habilito la caida GetComponent<Animator>().SetInteger("estado", 2); //Estado cayendo (animacion) if (!spr1.GetComponent<SpriteRenderer>().flipX) { spr2.transform.position += new Vector3(-0.09f, 0, 0); } else { spr2.transform.position += new Vector3(0.09f, 0, 0); } } void habilitar_cooldown() { cooldown = true; spr_sup.GetComponent<Animator>().SetInteger("estado", 0); } void chequear_teclas() { Vector3 posicion = new Vector3(); if (teclas[0]) //Arriba { if (teclas[2]) { direccion = direcciones.izqarr; spr_sup.GetComponent<Animator>().SetInteger("estado", 2); posicion = spawns.transform.Find("Spawn_IARR").transform.position; } else if (teclas[3]) { direccion = direcciones.derarr; spr_sup.GetComponent<Animator>().SetInteger("estado", 2); posicion = spawns.transform.Find("Spawn_DARR").transform.position; } else { direccion = direcciones.arriba; spr_sup.GetComponent<Animator>().SetInteger("estado", 4); posicion = spawns.transform.Find("Spawn_AR").transform.position; } } else if (teclas[1]) //Abajo { if (teclas[2]) { direccion = direcciones.izqab; spr_sup.GetComponent<Animator>().SetInteger("estado", 3); posicion = spawns.transform.Find("Spawn_IAB").transform.position; } else if (teclas[3]) { direccion = direcciones.derab; spr_sup.GetComponent<Animator>().SetInteger("estado", 3); posicion = spawns.transform.Find("Spawn_DAB").transform.position; } else { direccion = direcciones.abajo; spr_sup.GetComponent<Animator>().SetInteger("estado", 5); posicion = spawns.transform.Find("Spawn_AB").transform.position; } } else if (teclas[2]) //Izquierda { direccion = direcciones.izquierda; spr_sup.GetComponent<Animator>().SetInteger("estado", 1); posicion = spawns.transform.Find("Spawn_I").transform.position; } else if (teclas[3]) //Derecha { direccion = direcciones.derecha; spr_sup.GetComponent<Animator>().SetInteger("estado", 1); posicion = spawns.transform.Find("Spawn_D").transform.position; } else { spr_sup.GetComponent<Animator>().SetInteger("estado", 1); if(spr1.GetComponent<SpriteRenderer>().flipX) { posicion = spawns.transform.Find("Spawn_I").transform.position; direccion = direcciones.izquierda; } else { posicion = spawns.transform.Find("Spawn_D").transform.position; direccion = direcciones.derecha; } } check_direccion(posicion); } public void check_direccion(Vector3 posicion) { GameObject newBala = Instantiate(bala, posicion, Quaternion.identity); newBala.GetComponent<bala>().n_jugador = 0; //Le identificamos la bala como del player 0 (player 1) switch (direccion) { case direcciones.derecha: newBala.GetComponent<bala>().asignar_velocidad(0); break; case direcciones.izquierda: newBala.GetComponent<bala>().asignar_velocidad(180); break; case direcciones.arriba: newBala.GetComponent<bala>().asignar_velocidad(90); break; case direcciones.abajo: newBala.GetComponent<bala>().asignar_velocidad(270); break; case direcciones.derab: newBala.GetComponent<bala>().asignar_velocidad(315); break; case direcciones.derarr: newBala.GetComponent<bala>().asignar_velocidad(45); break; case direcciones.izqab: newBala.GetComponent<bala>().asignar_velocidad(225); break; case direcciones.izqarr: newBala.GetComponent<bala>().asignar_velocidad(135); break; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class cam_trigger : MonoBehaviour { public bool minmax; //Min falso, Max verdadero // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void OnTriggerEnter2D(Collider2D collision) { if(collision.transform.tag == "Player") { if(minmax) { transform.parent.GetComponent<camara_handler>().max_act = true; } else { transform.parent.GetComponent<camara_handler>().min_act = true; } } } private void OnTriggerExit2D(Collider2D collision) { if (collision.transform.tag == "Player") { if(minmax) { transform.parent.GetComponent<camara_handler>().max_act = false; } else { transform.parent.GetComponent<camara_handler>().min_act = false; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class level_handler : MonoBehaviour { public GameObject min; public GameObject max; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
5b6ddfa5e692eadcc5abb7a8436bf1f618deaf14
[ "C#" ]
9
C#
Osbbyx/Sunset-Riders
d4aba384201f82926c86339f6790495304eb4516
f2f18261c312eb06bf5c0132993b774ffaabf6c1
refs/heads/master
<file_sep>import Vue from 'vue'; import Router from 'vue-router'; import routes from './common/config/router'; Vue.use(Router); export default new Router({ routes }); <file_sep>/** * 规则: * 一、例如:index/index,以index结尾的,path和name默认去除index * 二、例如:shop/list,默认生成name为shop_list(如果结尾为index,例如shop/index则是shop) * 三、填写后不会自动生成 */ const routes = [ { // redirect:重定向,在layout路径下都会默认先进入index页面 redirect: { name: 'index' }, // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. // component: () => import(/* webpackChunkName: "about" */ '../../views/Layout.vue'), component: 'Layout', children: [ { // path: '/index', // name: 'index', // component: () => import('../../views/Index/index.vue'), meta: { title: '后台首页' }, component: 'Index/index', }, { meta: { title: '图片管理' }, component: 'Images/index', }, { meta: { title: '商品列表' }, component: 'Shop/Goods/List', }, { meta: { title: '商品规格' }, component: 'Shop/Size/ProSpec', }, ], }, { // path: '/login', // name: 'login', // component: () => import(/* webpackChunkName: "about" */ '../../views/Login/index.vue'), meta: { title: '登录页面' }, component: 'Login/index', }, // path: '*',输入的地址(路由)不对时(不存在),默认跳转的页面。 { path: '*', redirect: { name: 'index' }, }, ]; // 去除index function getValue(str) { const index = str.lastIndexOf('/'); const val = str.substring(index + 1, str.length); if (val === 'index') { return str.substring(index, -1); } return str; } // 自动生成路由 function createRoute(arr) { for (let i = 0; i < arr.length; i += 1) { if (!arr[i].component) return; // 去除index const val = getValue(arr[i].component.toLowerCase()); arr[i].name = arr[i].name || val.replace(/\//g, '_'); // 生成name // 生成path arr[i].path = arr[i].path || `/${val}`; // 自动生成component const componentFun = import(`../../views/${arr[i].component}.vue`); arr[i].component = () => componentFun; if (arr[i].children && arr[i].children.length > 0) { createRoute(arr[i].children); } } } // 获取路由信息方法l const getRoutes = () => { // 生成路由详细信息 createRoute(routes); return routes; }; export default getRoutes(); <file_sep>import Vue from 'vue'; import ElementUi from 'element-ui'; import router from './router'; import App from './App.vue'; import store from './store'; // 引入全局配置文件 import $conf from './common/config/config'; Vue.config.productionTip = false; Vue.prototype.$conf = $conf; Vue.use(ElementUi); new Vue({ router, store, render: h => h(App), }).$mount('#app');
83943168cf51a9fcba7c259ceaf609987b1a0992
[ "JavaScript" ]
3
JavaScript
wmxsycamore/backoffice-store-management
12117bede308ab8608f908bec498c1ddc9d8e901
277694f302a32988eded51cc55efeb32e9730664
refs/heads/master
<repo_name>Rayer/Iris<file_sep>/src/Main/MoManager.h /** * Project Iris */ #ifndef _MOMANAGER_H #define _MOMANAGER_H #include <list> #include <boost/uuid/uuid.hpp> #include "MoMLayer.h" #include "Loopable.h" namespace Iris { class MoManager : public MoMLayer { private: std::list<Loopable *> module_list; public: Iris_State update(double delta, Context *context) override; boost::uuids::uuid register_module(Loopable *module) override; bool remove_module(boost::uuids::uuid id) override; }; } #endif //_MOMANAGER_H<file_sep>/src/Main/Iris_State.h /** * Project Iris */ #ifndef _IRIS_STATE_H #define _IRIS_STATE_H enum Iris_State { RUNNING, STOP, PAUSE }; #endif //_IRIS_STATE_H<file_sep>/src/Main/Loopable.h /** * Project Iris */ #ifndef _LOOPABLE_H #define _LOOPABLE_H #include "IDModule.h" namespace Iris { class Context; class Loopable : public IDModule { public: /** * @param delta */ virtual void update(double delta, Context* context) = 0; virtual std::string name() = 0; virtual ~Loopable() = default; }; } #endif //_LOOPABLE_H<file_sep>/README.md note : - run `git pull --recurse-submodules` `git submodule update --init` - For Mariadbpp testing, change `deps/mariadbpp/test/CMakeFile.txt` user and password entry - In deps/mariadbpp/test/CMakeFile.txt, change line to this : `target_link_libraries(mariadbpp_tests mariadbclientpp gtest_main mariadbclient)` todo : - Use configuration based design for test - Use configuration based design for main - Use standalone CMakeFile for test<file_sep>/src/Data/SqlKVDatabase.h // // Created by <NAME> on 2018/6/5. // #ifndef IRIS_SQLDATABASE_H #define IRIS_SQLDATABASE_H #include "KVDataPersistenceLayer.h" #include <mariadb++/connection.hpp> namespace Iris { class SqlKVDatabase : public KVDataPersistenceLayer { mariadb::account_ref m_account_setup; std::string m_db; mariadb::connection_ref m_con; std::map<std::string, std::shared_ptr<KVSpace> > m_space_map; public: SqlKVDatabase(std::string host, std::string user, std::string pass, std::string database, long port = 3306); ~SqlKVDatabase() override; std::shared_ptr<KVSpace> get_space(const std::string &name) override; void wipe(bool force) override; }; } #endif //IRIS_SQLDATABASE_H <file_sep>/src/Exceptions/DPLException.cpp // // Created by Rayer on 2018/6/19. // #include <string> #include <boost/format.hpp> #include "DPLException.h" using namespace Iris; const char *DPLException::what() const noexcept { return what_output.c_str(); } //This wrapped_exception will cause unnecessery copy.... //But wrapped exception cant be reference, hence wrapped exception will be out of scope and invalid soon. DPLException::DPLException(const std::string &reason, const std::string &driver_output) noexcept : wrapped_exception(*this), std::exception() { what_output = generate_message(reason, driver_output); } std::string DPLException::generate_message(const std::string &reason, const std::string &driver_output) { DPLException::reason = reason; DPLException::driver_output = driver_output; boost::format output = boost::format("DPL Exception raised\nOS message : %1%\nreason : %2%\ndriver_output : %3%\n") % wrapped_exception.what() % reason % driver_output; return output.str(); } DPLException::DPLException(const std::exception &wrapped, const std::string &reason, const std::string &driver_output) noexcept : wrapped_exception(wrapped), std::exception() { } <file_sep>/src/Exceptions/SqlException.cpp // // Created by Rayer on 2018/6/22. // #include "SqlException.h" #include <boost/format.hpp> const char *Iris::SqlException::what() const noexcept { return what_output.c_str(); } Iris::SqlException::SqlException(const std::string &reason, const std::string &sql_command, const std::string &driver_output) noexcept : DPLException(reason, driver_output) { what_output = generate_message(reason, sql_command, driver_output); } Iris::SqlException::SqlException(const std::exception &wrapped, const std::string &reason, const std::string &sql_command, const std::string &driver_output) noexcept : DPLException(wrapped, reason, driver_output) { what_output = generate_message(reason, sql_command, driver_output); } std::string Iris::SqlException::generate_message(const std::string &reason, const std::string &sql_command, const std::string &driver_output) { this->sql = sql_command; boost::format output = boost::format( "\nSQL Exception raised\nOS message : %1%\nsql_command : %2%\nreason : %3%\ndriver_output : %4%\n") % wrapped_exception.what() //Don't use what(), it will cause loop. Dont use DPLException::what() too, will include duplicated message % this->sql % reason % driver_output; return output.str(); } <file_sep>/src/Exceptions/DPLException.h // // Created by Rayer on 2018/6/19. // #ifndef IRIS_DPLEXCEPTION_H #define IRIS_DPLEXCEPTION_H #include <exception> namespace Iris { class DPLException : public std::exception { protected: //Use this to std::exception wrapped_exception; std::string what_output; std::string reason; std::string driver_output; public: DPLException(const std::exception& wrapped_exception, const std::string &reason, const std::string &driver_output = "") noexcept; DPLException(const std::string &reason, const std::string &driver_output = "") noexcept; const char *what() const noexcept override; //Provide a noexcept copy constructor DPLException(const DPLException &) = default; public: ~DPLException() override = default; std::string generate_message(const std::string &reason, const std::string &driver_output); }; } #endif //IRIS_DPLEXCEPTION_H <file_sep>/src/Main/Context.h /** * Project Iris */ #ifndef _CONTEXT_H #define _CONTEXT_H namespace Iris { class Context { bool running; public: bool isRunning() const; void setRunning(bool running); }; } #endif //_CONTEXT_H<file_sep>/src/Main/MoMLayer.h /** * Project Iris */ #ifndef _MOMLAYER_H #define _MOMLAYER_H #include "Iris_State.h" #include <string> #include <boost/uuid/uuid.hpp> namespace Iris { class Context; class Loopable; class MoMLayer { public: /** * @param delta * @param context */ virtual Iris_State update(double delta, Context *context) = 0; /** * @param module */ virtual boost::uuids::uuid register_module(Loopable *module) = 0; /** * @param id */ virtual bool remove_module(boost::uuids::uuid id) = 0; virtual ~MoMLayer() = default; }; } #endif //_MOMLAYER_H<file_sep>/src/Main/IDModule.h /** * Project Iris */ #ifndef _IDMODULE_H #define _IDMODULE_H #include <boost/uuid/uuid.hpp> namespace Iris { class IDModule { public: /** * @param tag */ virtual void set_tag(boost::uuids::uuid tag) = 0; virtual boost::uuids::uuid tag() = 0; }; } #endif //_IDMODULE_H<file_sep>/src/Exceptions/SqlException.h // // Created by Rayer on 2018/6/22. // #ifndef IRIS_SQLEXCEPTION_H #define IRIS_SQLEXCEPTION_H #include <string> #include "DPLException.h" namespace Iris { class SqlException : public DPLException { std::string sql; std::string generate_message(const std::string &reason, const std::string &sql_command, const std::string &driver_output); public: SqlException(const std::exception& wrapped, const std::string &reason, const std::string &sql_command = "", const std::string &driver_output = "") noexcept; SqlException(const std::string &reason, const std::string &sql_command = "", const std::string &driver_output = "") noexcept; const char *what() const noexcept override; ~SqlException() override = default; }; } #endif //IRIS_SQLEXCEPTION_H <file_sep>/test/LoopSystemTest.cpp // // Created by <NAME> on 14/11/2017. // #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Main/Loopable.h> #include <Main/MoMLayer.h> #include <Main/MoManager.h> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> #include <utility> #include <Main/Context.h> using namespace Iris; int update_count = 0; class TemplateModule : public Loopable { boost::uuids::uuid m_tag; std::string m_name; public: explicit TemplateModule(std::string name) : m_name(std::move(name)), m_tag(boost::uuids::nil_uuid()) { } void update(double delta, Context *context) override { update_count++; } void set_tag(boost::uuids::uuid uuid) override { m_tag = uuid; } boost::uuids::uuid tag() override { return m_tag; } std::string name() override { return m_name; } }; TEST(LoopSystemTest, Register_UUID_Test) { Loopable *clazz1, *clazz2; clazz1 = new TemplateModule("TestModule1"); clazz2 = new TemplateModule("TestModule2"); EXPECT_EQ(clazz1->tag(), boost::uuids::nil_uuid()); EXPECT_EQ(clazz2->tag(), boost::uuids::nil_uuid()); MoMLayer *ml = new MoManager(); ml->register_module(clazz1); ml->register_module(clazz2); EXPECT_NE(clazz1->tag(), boost::uuids::nil_uuid()); EXPECT_NE(clazz2->tag(), boost::uuids::nil_uuid()); EXPECT_NE(clazz1->tag(), clazz2->tag()); delete ml; delete clazz1; delete clazz2; } TEST(LoopSystemTest, Reg_Remove_Module_Test) { Loopable *clazz1, *clazz2; clazz1 = new TemplateModule("TestModule1"); clazz2 = new TemplateModule("TestModule2"); Context* context = new Context(); update_count = 0; typedef boost::uuids::uuid UUID; MoMLayer *ml = new MoManager(); UUID u1 = ml->register_module(clazz1); UUID u2 = ml->register_module(clazz2); ml->update(0, context); EXPECT_EQ(update_count, 2); ml->remove_module(u2); ml->update(0, context); EXPECT_EQ(update_count, 3); ml->remove_module(u1); ml->update(0, context); EXPECT_EQ(update_count, 3); delete ml; delete clazz1; delete clazz2; } <file_sep>/src/Data/DataPersistenceManager.cpp // // Created by Rayer on 17/08/2017. // #include "DataPersistenceManager.h" #include "SimpleKVDevDB.h" using namespace Iris; KVDataPersistenceLayer *DataPersistenceManager::dataPersistenceLayer = nullptr; //TODO: Add pre-compiler to determine debug and release for different instance....or load from file. KVDataPersistenceLayer *DataPersistenceManager::getInstance() { if (dataPersistenceLayer == nullptr) { dataPersistenceLayer = new SimpleKVDevDB(); } return dataPersistenceLayer; } <file_sep>/src/Data/SqlKVDatabaseSpace.cpp // // Created by <NAME> on 2018/6/5. // #include "SqlKVDatabaseSpace.h" #include <boost/format.hpp> #include "Exceptions/SqlException.h" #include <boost/serialization/variant.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <mariadb++/exceptions.hpp> #include "Utils/SqlCmd.h" using namespace mariadb; using namespace where_clause; Iris::KVSpace::ValueType Iris::SqlKVDatabaseSpace::get_value(const std::string &key) { //std::string sql_string = (boost::format("select `value` from %1% where `key`='%2%'") % space_name % key).str(); std::string sql_string = SqlQuery(space_name).addQuery("`value`").where(Eq("`key`", key)).generate(); try { result_set_ref result = sql_connect->query(sql_string); if (result->row_count() == 0) throw SqlException{"get_value not found key!", sql_string, sql_connect->error()}; result->next(); std::string data = result->get_string("value"); ValueType ret; std::stringstream ss; ss << data; boost::archive::text_iarchive ar(ss); ar >> ret; return ret; } catch(mariadb::exception::base& ex) { //wrap up as DPL/SQL exceptions throw SqlException{ex, "set_value", sql_string, sql_connect->error()}; } catch(Iris::DPLException& dpl) { throw dpl; } } void Iris::SqlKVDatabaseSpace::set_value(const std::string &key, const Iris::KVSpace::ValueType &value) { //Use sql_string on demend.... //std::string sql_string = (boost::format("select 1 from %1% where `key` = '%2%';") % space_name % key).str(); std::string sql_string = SqlQuery(space_name).addQuery("1").where(Eq("`key`", key)).generate(); try { sql_connect->query(sql_string); bool update = 0 != sql_connect->query(sql_string)->row_count(); std::stringstream blob; boost::archive::text_oarchive ar(blob); ar << value; //static boost::format update_string = boost::format("update `%1%` set `value` = '%3%' where `key` = '%2%';"); //static boost::format insert_string = boost::format("insert into `%1%` (`key`, `value`) values ('%2%','%3%');"); //sql_string = ((update ? update_string : insert_string) % space_name % key % blob.str()).str(); if (update) { sql_string = SqlUpdate(space_name).setValue("`value`", blob.str()).where(Eq("`key`", key)).generate(); } else { sql_string = SqlInsert(space_name).insertValue("`key`", key).insertValue("`value`", blob.str()).generate(); } if (!sql_connect->execute(sql_string)) throw SqlException{"set_value failed", sql_string, sql_connect->error()}; } catch(mariadb::exception::base& ex) { //wrap up as DPL/SQL exceptions throw SqlException{ex, "set_value", sql_string, sql_connect->error()}; } catch(Iris::DPLException& dpl) { throw dpl; } } Iris::SqlKVDatabaseSpace::SqlKVDatabaseSpace(const std::string &name, mariadb::connection_ref conn) { space_name = name; this->sql_connect = conn; } bool Iris::SqlKVDatabaseSpace::remove(const std::string &key) { return false; } void Iris::SqlKVDatabaseSpace::wipe() { std::string sql_string = (boost::format("drop table %1%;") % space_name).str(); if (!sql_connect->execute(sql_string)) throw SqlException{"wipe failed", sql_string, sql_connect->error()}; } void Iris::SqlKVDatabaseSpace::refresh() { //not used now. } <file_sep>/src/Data/SqlKVDatabase.cpp // // Created by <NAME> on 2018/6/5. // #include "SqlKVDatabase.h" #include "SqlKVDatabaseSpace.h" #include <boost/format.hpp> #include <Exceptions/SqlException.h> #include <mariadb++/exceptions.hpp> #include "Utils/SqlCmd.h" using namespace Iris; using namespace mariadb; using namespace where_clause; std::shared_ptr<KVSpace> SqlKVDatabase::get_space(const std::string &name) { //Find space map first if (m_space_map.find(name) != m_space_map.end()) return m_space_map[name]; //std::string sql_string = ( // boost::format("select 1 from information_schema.tables where table_schema='%1%' and table_name='%2%';") % // m_db % name).str(); std::string sql_string = SqlQuery("information_schema.tables").addQuery("1").where( Eq("table_schema", m_db) & Eq("table_name", name)).generate(); try { result_set_ref result = m_con->query(sql_string); if (result->row_count() == 0) { sql_string = (boost::format("CREATE TABLE %1%\n" "(\n" " `key` varchar(256) PRIMARY KEY NOT NULL,\n" " value varchar(1024)\n" ");\n" "CREATE UNIQUE INDEX %1%_key_uindex ON %1% (`key`);") % name).str(); if (m_con->execute(sql_string) == 0xffffffff) throw SqlException{"Fail to create in get_space", sql_string, m_con->error()}; } std::shared_ptr<KVSpace> space = std::make_shared<SqlKVDatabaseSpace>(name, m_con); m_space_map.insert(std::make_pair(name, space)); return space; } catch(mariadb::exception::base& ex) { //wrap up as DPL/SQL exceptions throw SqlException{ex, "set_value", sql_string, m_con->error()}; } catch(Iris::DPLException& dpl) { throw dpl; } } void SqlKVDatabase::wipe(bool force) { //TODO: Dangerous operation, need a WARN log //std::string sql_String = ( // boost::format("select TABLE_NAME from information_schema.tables where table_schema='%1%';") % m_db).str(); std::string sql_String = SqlQuery("information_schema.tables").addQuery("TABLE_NAME").where( Eq("table_schema", m_db)).generate(); result_set_ref result = m_con->query(sql_String); while (result->next()) { m_con->execute((boost::format("drop table %1%;") % result->get_string("TABLE_NAME")).str()); } } SqlKVDatabase::SqlKVDatabase(std::string host, std::string user, std::string pass, std::string database, long port) { m_account_setup = account::create(host, user, pass, database, (u32) port); m_db = database; m_account_setup->set_auto_commit(true); m_con = connection::create(m_account_setup); if (!m_con->connect()) throw SqlException{"Fail to initial SqlDataBase!", "", m_con->error()}; } SqlKVDatabase::~SqlKVDatabase() { if (m_con) m_con->disconnect(); } <file_sep>/test/ItemTest.cpp // // Created by <NAME> on 23/08/2017. // <file_sep>/src/Data/SimpleKVDevDB.h // // Created by Rayer on 15/08/2017. // #ifndef IRIS_SIMPLEDEVDB_H #define IRIS_SIMPLEDEVDB_H #include "KVDataPersistenceLayer.h" #include "SimpleKVDevDBSpace.h" #include <boost/filesystem.hpp> /** * DPL Implementation for development */ namespace Iris { class SimpleKVDevDB : public KVDataPersistenceLayer { protected: std::map<std::string, std::shared_ptr<SimpleKVDevDBSpace>> space_map; public: void serialize(std::string folder = boost::filesystem::complete( boost::filesystem::temp_directory_path()).generic_string()); void deserialize(std::string folder = boost::filesystem::complete( boost::filesystem::temp_directory_path()).generic_string()); std::shared_ptr<KVSpace> get_space(const std::string &name) override; void wipe(bool force) override; SimpleKVDevDB() = default; ~SimpleKVDevDB() = default; }; } #endif //IRIS_SIMPLEDEVDB_H <file_sep>/test/CharacterManagerTest.cpp // // Created by <NAME> on 28/07/2017. // <file_sep>/src/Data/DataPersistenceManager.h // // Created by Rayer on 17/08/2017. // #ifndef IRIS_DATAPERSISTENCEMANAGER_H #define IRIS_DATAPERSISTENCEMANAGER_H namespace Iris { class KVDataPersistenceLayer; /** * Data Persistence Selector, will deliver different DPL implementation by compiling time */ class DataPersistenceManager { private: static KVDataPersistenceLayer *dataPersistenceLayer; DataPersistenceManager() = default; public: static KVDataPersistenceLayer *getInstance(); }; } #endif //IRIS_DATAPERSISTENCEMANAGER_H <file_sep>/src/Utils/SqlCmd.cpp #include "SqlCmd.h" #include <boost/algorithm/string.hpp> SqlQuery::SqlQuery(const std::string &table) { m_tablename = table; } SqlQuery &SqlQuery::addQuery(const std::string &query) { m_queryItemList.push_back(query); return *this; } std::string SqlQuery::generate() { std::stringstream buffer; buffer << "SELECT "; for (auto iter = m_queryItemList.begin(); iter != m_queryItemList.end(); ++iter) { if (iter != m_queryItemList.begin()) { buffer << "," << *iter; } else { buffer << *iter; } } buffer << " FROM " << m_tablename; if (!m_whereString.empty()) buffer << " WHERE " << m_whereString; if (!m_orderString.empty()) buffer << " " << m_orderString; buffer << ";"; return buffer.str(); } SqlQuery &SqlQuery::where(const std::string &condition) { m_whereString = condition; return *this; } SqlQuery &SqlQuery::where(const where_clause::Exp &exp) { return where(exp.str()); } SqlUpdate::SqlUpdate(const std::string &tablename) { m_tablename = tablename; } SqlUpdate &SqlUpdate::setValue(const std::string &key, const std::string &value) { m_kvList.emplace_back(key, value); return *this; } SqlUpdate &SqlUpdate::setValue(const std::string &key, int value) { m_kvList.emplace_back(key, std::to_string(value)); return *this; } SqlUpdate &SqlUpdate::setValue(const std::string &key, double value) { std::stringstream buf; buf << value; m_kvList.emplace_back(key, buf.str()); return *this; } SqlUpdate &SqlUpdate::where(const std::string &where_clouse) { m_whereString = where_clouse; return *this; } SqlUpdate &SqlUpdate::where(const where_clause::Exp &exp) { return where(exp.str()); } std::string SqlUpdate::generate() { std::stringstream buffer; //UPDATE TABLE_NAME SET KEY = VALUE WHERE (WHERE_CLOUSE) std::stringstream set_value_buf; std::list<std::string> set_result; // std::transform(m_kvList.begin(), m_kvList.end(), set_result.begin(), [](const KVPair& kvPair)->std::string { // return kvPair.first + "='" + kvPair.second + "'"; // }); for (KVPair kv : m_kvList) { set_result.push_back(kv.first + "='" + kv.second + "'"); } std::string set_string = boost::join(set_result, ","); buffer << "UPDATE " << m_tablename << " SET " << set_string; if (!m_whereString.empty()) buffer << " WHERE " << m_whereString; buffer << ";"; return buffer.str(); } SqlInsert::SqlInsert(const std::string &tablename) : m_tablename(tablename) { } SqlInsert &SqlInsert::insertValue(const std::string &key, const std::string &value) { m_kvList.emplace_back(key, value); return *this; } SqlInsert &SqlInsert::insertValue(const std::string &key, int value) { m_kvList.emplace_back(key, std::to_string(value)); return *this; } SqlInsert &SqlInsert::insertValue(const std::string &key, double value) { std::stringstream buf; buf << value; m_kvList.emplace_back(key, buf.str()); return *this; } std::string SqlInsert::generate() { std::stringstream buf; std::list<std::string> columns; std::list<std::string> values; for (KVPair kv : m_kvList) { columns.push_back(kv.first); values.push_back(kv.second); } buf << "INSERT INTO " << m_tablename << " (" << boost::join(columns, ",") << ") VALUES ('" << boost::join(values, "','") << "');"; return buf.str(); } where_clause::And where_clause::Exp::operator&(const Exp &exp) const { return And(*this, exp); } where_clause::Eq::Eq(const std::string &var, const std::string &val) : m_var(var), m_val(val) {}; /* //This implementation requires C++11 which is not yet supported by current build toolchain where_clause::Eq::Eq(const std::string &var, const int val) : m_var(var), m_val(std::to_string((long long) val)) {}; where_clause::Eq::Eq(const std::string &var, const double val) : m_var(var), m_val(std::to_string((long double) val)) {}; */ where_clause::Eq::Eq(const std::string& var, const int val) : m_var(var){ std::stringstream buf; buf << val; m_val = buf.str(); }; where_clause::Eq::Eq(const std::string& var, const double val) : m_var(var){ std::stringstream buf; buf << val; m_val = buf.str(); }; std::string where_clause::Eq::str() const { //trim_copy costs, so m_val.empty() first. if (m_val.empty() || boost::trim_copy(m_val).empty()) { return m_var + " is null"; } else { return m_var + "='" + m_val + "'"; } } where_clause::Like::Like(const std::string &var, const std::string &val) : m_var(var), m_val(val) {}; std::string where_clause::Like::str() const { return m_var + " Like '" + m_val + "'"; } where_clause::And::And(const Exp &lhs, const Exp &rhs) : m_lhs(lhs), m_rhs(rhs) { } std::string where_clause::And::str() const { std::stringstream output; output << m_lhs.str() << " AND " << m_rhs.str(); return output.str(); } SqlQuery &SqlQuery::orderBy(const std::string &column, Order order) { m_orderString = "ORDER BY " + column + (order == ASCENDING ? "" : " DESC"); return *this; } where_clause::Not::Not(const std::string &var, const std::string &val) : m_var(var), m_val(val) { } where_clause::Not::Not(const std::string &var, int val) : m_var(var), m_val(std::to_string(val)) { } where_clause::Not::Not(const std::string &var, double val) : m_var(var) { std::stringstream buf; buf << val; m_val = buf.str(); } std::string where_clause::Not::str() const { //trim_copy costs, so m_val.empty() first. if (m_val.empty() || boost::trim_copy(m_val).empty()) { return m_var + " is not null"; } else { return m_var + "<>'" + m_val + "'"; } } <file_sep>/src/Data/KVSpace.h // // Created by Rayer on 15/08/2017. // #ifndef IRIS_SPACE_H #define IRIS_SPACE_H #include <string> #include <boost/variant.hpp> namespace Iris { /** * Space (Namespace) interface for DPL */ class KVSpace { public: typedef boost::variant<std::string, double, int> ValueType; virtual ValueType get_value(const std::string &key) = 0; virtual void set_value(const std::string &key, const ValueType &value) = 0; virtual bool remove(const std::string &key) = 0; virtual void wipe() = 0; }; } #endif //IRIS_SPACE_H <file_sep>/src/Data/KVDataPersistenceLayer.h // // Created by Rayer on 14/08/2017. // #ifndef IRIS_DATAPERSISTENCELAYER_H #define IRIS_DATAPERSISTENCELAYER_H #include <string> #include <memory> #include "KVSpace.h" namespace Iris { /** * This is data persistance interface. * \author : Rayer */ class KVDataPersistenceLayer { public: KVDataPersistenceLayer() = default; /** * Get Space(namespace) * \param name : Space Name * \return Shared pointer of a single Space */ virtual std::shared_ptr<KVSpace> get_space(const std::string &name) = 0; /** * Wipe all data */ virtual void wipe(bool force) = 0; /** * */ virtual ~KVDataPersistenceLayer() = default; }; } #endif //IRIS_DATAPERSISTENCELAYER_H <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.6) project(Iris) set(CMAKE_CXX_STANDARD 11) enable_testing() # Boost dependency # P.S. std::variant requires C++17, use boost::variant instead FIND_PACKAGE(Boost REQUIRED serialization filesystem system) INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} ) # Not yet implemented option(GRAPHIC_CLIENT "Build graphic client" OFF) if(GRAPHIC_CLIENT) execute_process(COMMAND 'git submodule update cocos2d-x' .) add_subdirectory(deps/cocos2d-x) endif(GRAPHIC_CLIENT) add_subdirectory(deps/googletest) include_directories(deps/googletest/googletest/include) include_directories(deps/googletest/googlemock/include) include_directories(deps/mariadbpp/include) include_directories(src) set(GTEST_SRC_DIR deps/googletest/googletest) add_subdirectory(deps/mariadbpp) add_subdirectory(deps/mariadb-connector-c) set(LIBS src/Data/KVDataPersistenceLayer.h src/Data/SimpleKVDevDB.cpp src/Data/SimpleKVDevDB.h src/Data/KVSpace.h src/Data/SimpleKVDevDBSpace.cpp src/Data/SimpleKVDevDBSpace.h src/Data/DataPersistenceManager.cpp src/Data/DataPersistenceManager.h src/Main/Context.cpp src/Main/Context.h src/Main/GameMain.cpp src/Main/GameMain.h src/Main/Iris_State.h src/Main/MoManager.cpp src/Main/MoManager.h src/Main/MoMLayer.h src/Main/Loopable.h src/Main/IDModule.h src/Data/SqlKVDatabase.cpp src/Data/SqlKVDatabase.h src/Data/SqlKVDatabaseSpace.cpp src/Data/SqlKVDatabaseSpace.h src/Exceptions/DPLException.cpp src/Exceptions/DPLException.h src/Exceptions/SqlException.cpp src/Exceptions/SqlException.h src/Utils/SqlCmd.cpp src/Utils/SqlCmd.h) set(TEST_FILES test/CharacterManagerTest.cpp test/SimpleKVDevDBTest.cpp test/ItemTest.cpp test/LoopSystemTest.cpp test/SqlKVDatabaseTest.cpp test/UtilSqlCmdTest.cpp) # message("${Boost_LIBRARIES} ${Boost_LIBRARY_DIR_RELEASE} ${Boost_LIBRARY_DIR_DEBUG} 123") # add_executable(Iris ${LIBS} main.cpp) add_library(Iris_Libs ${LIBS}) add_executable(Iris_Tests deps/googletest/googletest/src/gtest_main.cc ${TEST_FILES}) target_link_libraries(Iris_Tests gtest Iris_Libs ${Boost_LIBRARIES} mariadbclientpp mariadbclient)<file_sep>/src/Utils/SqlCmd.h // // Created by <NAME> on 2018/7/19. // #ifndef IRIS_SQLCMD_H #define IRIS_SQLCMD_H #pragma once #include <sstream> #include <list> #include <map> //Forward Declaration namespace where_clause { class Eq; class Not; class And; class Or; class Like; class Bracket; class Parentheses; class Exp; } enum Order { ASCENDING, DESCENDING }; //Not intent to be used by user. It is abstract class of all SQL Commands. class SqlCmd { public: /** Generate SQL String. \return Generated SQL String */ virtual std::string generate() = 0; //virtual ADODB::_RecordsetPtr execute(ADODB::_ConnectionPtr ptr) = 0; virtual ~SqlCmd() = default; }; /** This class provides an easier way to access SQL DB. It is a Builder pattern based class. ``` QueryResult result = SqlQuery("TABLE_NAME").addQuery("COLUMN1").addQuery("COLUMN2").where(Eq("c_system_id", "awsrayer") & Eq("c_client_layout", "1272028")).query(m_OraCnn); ``` \sa QueryResult */ class SqlQuery : public SqlCmd { std::string m_tablename; std::list<std::string> m_queryItemList; std::string m_whereString; std::string m_orderString; public: /** Main builder for Query \param table Table Name */ SqlQuery(const std::string &table); ~SqlQuery(void) override = default; /** Add a query column. It works like SELECT "THIS" from "TABLE NAME" \param query Column name added to query list \return Builder pattern self reference */ SqlQuery &addQuery(const std::string &query); /** Where clause. This can consume "text" version of where clause, like "A='01' AND B='02'" as raw stream \param condition Where-clause. \return Builder pattern self reference */ SqlQuery &where(const std::string &condition); /** Where clause, but use where_clause utilities. For example, .where("A='01' AND B='02'") is equal to .where(Eq("A", "01") & EQ("B", "02")) \param exp where_clause utilities classes. \return Builder pattern self reference \sa where_clause */ SqlQuery &where(const where_clause::Exp &exp); /** Sorting Order, it can provide ordering by specified column. \param column Column should be sorted by. \param order ASCENDING(default) and DESCENDING : as literal \return Builder pattern self reference */ SqlQuery &orderBy(const std::string &column, Order order = ASCENDING); /** Generate SQL String. \return Generated SQL String */ std::string generate() override; }; /** SqlUpdate is another helper for executing "UPDATE" command of SQL, it is a Builder Pattern, too. <code> SqlUpdate("TABLE_NAME").setValue("COLUMN1_INT", "123").setValue("COLUMN2_STR", "Hello").execute(m_pOraCnn); </code> */ class SqlUpdate : public SqlCmd { protected: std::string m_tablename; typedef std::pair<std::string, std::string> KVPair; std::list<KVPair> m_kvList; std::string m_whereString; public: /** Main Builder for Update \param tablename Target table name */ SqlUpdate(const std::string &tablename); ~SqlUpdate(void) override = default; /** Set a value to a column. \param key \param value Value use to set to the column. Currently only string is supported because all use cases use string as value. */ SqlUpdate &setValue(const std::string &key, const std::string &value); SqlUpdate &setValue(const std::string &key, int value); SqlUpdate &setValue(const std::string &key, double value); /** Where clause. This can consume "text" version of where clause, like "A='01' AND B='02'" as raw stream \param condition Where-clause. \return Builder pattern self reference */ SqlUpdate &where(const std::string &condition); /** Where clause, but use where_clause utilities. For example, .where("A='01' AND B='02'") is equal to .where(Eq("A", "01") & EQ("B", "02")) \param exp where_clause utilities classes. \return Builder pattern self reference \sa where_clause */ SqlUpdate &where(const where_clause::Exp &exp); /** Generate SQL String. \return Generated SQL String */ std::string generate() override; }; class SqlInsert : public SqlCmd { protected: std::string m_tablename; typedef std::pair<std::string, std::string> KVPair; std::list<KVPair> m_kvList; public: /** Main Builder for Update \param tablename Target table name */ SqlInsert(const std::string &tablename); ~SqlInsert(void) override = default; /** Set a value to a column. \param key \param value Value use to set to the column. Currently only string is supported because all use cases use string as value. */ SqlInsert &insertValue(const std::string &key, const std::string &value); SqlInsert &insertValue(const std::string &key, int value); SqlInsert &insertValue(const std::string &key, double value); /** Generate SQL String. \return Generated SQL String */ std::string generate() override; }; /** This is a helper class for generating where_clause. For example, we usually use this to build a `where-clause` ``` std::stringstream where_clause; where_clause << ORA_A::COLUMN_NAME << "=" << someValue << " AND " << ORA_A::COLUMN_NAME2 << "=" << someValue2 << " AND " << ORA_A::COLUMN_NAME3 << "=" << someValue3; QueryResult result = SqlQuery(ORA_A::TABLE_NAME) .addQuery(ORA_A::COLUMN_OTHER) .where(where_clause.str()) .query(m_pOraCnn); ``` It can be samplify to ``` QueryResult result = SqlQuery(ORA_A::TABLE_NAME) .addQuery(ORA_A::COLUMN_OTHER) .where(And(And(Eq(ORA_A::COLUMN_NAME, someValue), Eq(ORA_A::COLUMN_NAME2, someValue2)), Eq(ORA_A::COLUMN_NAME3, someValue3))) .query(m_pOraCnn); ``` `And` might still be not readable when there is a lot of And clause... Even furthermore... ``` QueryResult result = SqlQuery(ORA_A::TABLE_NAME) .addQuery(ORA_A::COLUMN_OTHER) .where(Eq(ORA_A::COLUMN_NAME, someValue) & Eq(ORA_A::COLUMN_NAME2, someValue2) & Eq(ORA_A::COLUMN_NAME3, someValue3)) .query(m_pOraCnn); ``` where_clause makes adding `where()` much more easier then before. */ namespace where_clause { class Exp { public : virtual ~Exp() = default; virtual std::string str() const { return ""; }; /** This operator uses in two where_clause::Exp. It represent "AND" \sa And */ And operator&(const Exp &exp) const; Or operator|(const Exp &exp) const; Parentheses operator()(const Exp &exp) const; }; /** Express "like", Like */ class Like : public Exp { std::string m_var; std::string m_val; public : ~Like() = default; Like(const std::string &var, const std::string &val); std::string str() const; }; /** Express "=", Equal */ class Eq : public Exp { std::string m_var; std::string m_val; public : ~Eq() override = default; Eq(const std::string &var, const std::string &val); Eq(const std::string &var, int val); Eq(const std::string &var, double val); std::string str() const override; }; /** * Express "<>", NOT */ class Not : public Exp { std::string m_var; std::string m_val; public: ~Not() override = default; Not(const std::string &var, const std::string &val); Not(const std::string &var, int val); Not(const std::string &var, double val); std::string str() const override; }; /** Express "And", usually we can use operator& instead. */ class And : public Exp { const Exp &m_lhs; const Exp &m_rhs; public: And(const Exp &, const Exp &); //And(const std::list<Exp>& exp); std::string str() const override; }; // /** // * Express "Or", usually we can use operator| instead // */ // // class Or : public Exp { // const Exp &m_lhs; // const Exp &m_rhs; // public: // Or(const Exp &, const Exp &); // std::string str() const override; // }; // // /** // * Express "Parentheses", usually we can use operator() instead // */ // // class Parentheses : public Exp { // const Exp &m_lhs; // const Exp &m_rhs; // public: // Parentheses(const Exp&, const Exp&); // std::string str() const override; // }; // } #endif //IRIS_SQLCMD_H <file_sep>/test/UtilSqlCmdTest.cpp // // Created by <NAME> on 2018/7/19. // #include <gtest/gtest.h> #include "Utils/SqlCmd.h" using where_clause::Eq; using where_clause::And; using where_clause::Not; TEST(SqlCmdTest, BaseQuery) { std::string expected = "SELECT c1,c2 FROM table_name;"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, BaseWhere) { std::string expected = "SELECT c1,c2 FROM table_name WHERE a='b';"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where( where_clause::Eq("a", "b")).generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, BaseWhere2) { std::string expected = "SELECT c1,c2 FROM table_name WHERE a='b' AND c='2' AND d='2.55';"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where( Eq("a", "b") & Eq("c", 2) & Eq("d", 2.55)).generate(); std::string generated2 = SqlQuery("table_name").addQuery("c1").addQuery("c2").where( And(And(Eq("a", "b"), Eq("c", 2)), Eq("d", 2.55))).generate(); EXPECT_EQ(generated, expected); EXPECT_EQ(generated2, expected); } TEST(SqlCmdTest, WhereWithNull) { std::string expected = "SELECT c1,c2 FROM table_name WHERE c3 is null;"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where(Eq("c3", "")).generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, WhereWithNot) { std::string expected = "SELECT c1,c2 FROM table_name WHERE c3<>'c4';"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where(Not("c3", "c4")).generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, WhereWithNotNull) { std::string expected = "SELECT c1,c2 FROM table_name WHERE c3 is not null;"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where(Not("c3", "")).generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, QueryWithOrder) { std::string expected = "SELECT c1,c2 FROM table_name WHERE a='b' ORDER BY e;"; std::string generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where(Eq("a", "b")).orderBy( "e").generate(); EXPECT_EQ(generated, expected); expected = "SELECT c1,c2 FROM table_name WHERE a='b' ORDER BY e DESC;"; generated = SqlQuery("table_name").addQuery("c1").addQuery("c2").where(Eq("a", "b")) .orderBy("e", DESCENDING).generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, BaseUpdate) { std::string expected = "UPDATE table_name SET c1='v1',c2='2',c3='3.5' WHERE c4='v4';"; std::string generated = SqlUpdate("table_name").setValue("c1", "v1").setValue("c2", 2).setValue("c3", 3.5) .where(Eq("c4", "v4")).generate(); EXPECT_EQ(generated, expected); } TEST(SqlCmdTest, BaseInsert) { std::string expected = "INSERT INTO table_name (c1,c2,c3,c4) VALUES ('v1','v2','3','2.7');"; std::string generated = SqlInsert("table_name").insertValue("c1", "v1").insertValue("c2", "v2") .insertValue("c3", 3).insertValue("c4", 2.7).generate(); EXPECT_EQ(generated, expected); }<file_sep>/src/Main/Context.cpp /** * Project Iris */ #include "Context.h" using namespace Iris; /** * Context implementation */ bool Context::isRunning() const { return running; } void Context::setRunning(bool running) { Context::running = running; } <file_sep>/src/Data/SimpleKVDevDBSpace.cpp // // Created by Rayer on 15/08/2017. // #include "SimpleKVDevDBSpace.h" #include <sstream> #include <iostream> #include <boost/serialization/variant.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <fstream> using namespace Iris; SimpleKVDevDBSpace::ValueType SimpleKVDevDBSpace::get_value(const std::string &key) { return map.at(key); } void SimpleKVDevDBSpace::set_value(const std::string &key, const ValueType &value) { map.insert({key, value}); } void SimpleKVDevDBSpace::serialize(std::string fullPath) { std::ofstream ofs(fullPath); boost::archive::text_oarchive ar(ofs); ar << map; ofs.close(); } void SimpleKVDevDBSpace::deserialize(std::string fullPath) { std::ifstream ifs(fullPath); boost::archive::text_iarchive ar(ifs); ar >> map; ifs.close(); } std::list<std::string> SimpleKVDevDBSpace::get_keys() { std::list<std::string> ret; for (auto const &pair : map) { ret.push_back(pair.first); } return ret; } bool SimpleKVDevDBSpace::remove(const std::string &key) { return map.erase(key) > 0; } void SimpleKVDevDBSpace::wipe() { } <file_sep>/test/SqlKVDatabaseTest.cpp // // Created by Rayer on 20/06/2018. // #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Data/DataPersistenceManager.h> #include <Data/SqlKVDatabase.h> #include <list> #include <map> using namespace Iris; class SqlKVDatabase_Test : public ::testing::Test { protected: KVDataPersistenceLayer *db = nullptr; //This map stores all record that DB operates, used to verdict correct answer. typedef std::map<std::string, KVSpace::ValueType> SpaceSpec; typedef std::map<std::string, SpaceSpec> DBSpec; DBSpec cache; //This cache is used in stress test case SqlKVDatabase_Test() { db = new SqlKVDatabase("localhost", "iris", "iris", "iris_test"); srand((unsigned int) time(nullptr)); db->wipe(true); } void SetUp() override { } void TearDown() override { //std::cout << "TearDown()" << std::endl; //Don't delete because it is singleton //delete db; } std::string generateRandomString(int min = 1, int max = 10) { static const char *rule = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; size_t rule_length = std::strlen(rule); std::string ret; int length = rand() % (max - min + 1) + min; for (int i = 0; i < length; ++i) ret += rule[rand() % rule_length]; return ret; } void generateStressTestData(KVDataPersistenceLayer* dpl, int space_count = 100, int space_size_min = 1, int space_size_max = 10) { cache.clear(); std::map<std::string, std::shared_ptr<KVSpace> > spaceList; for(int i = 0; i < space_count; ++i) { std::string space_name = generateRandomString(1, 16); spaceList.insert(std::make_pair(space_name, dpl->get_space(space_name))); //cache[space_name] = SpaceSpec{}; for(std::pair<std::string, std::shared_ptr<KVSpace> > pair : spaceList) { int space_size = rand() % (space_size_max - space_size_min) + space_size_min; for(int j = 0; j < space_size; ++j) { std::string column_name = generateRandomString(1, 10); KVSpace::ValueType value = (rand() % 2) ? (KVSpace::ValueType)rand() : (KVSpace::ValueType)generateRandomString(1, 16); cache[pair.first].insert(std::make_pair(column_name, value)); pair.second->set_value(column_name, value); } } } } }; TEST_F(SqlKVDatabase_Test, SpaceAccessTest) { std::string SPACE_NAME = generateRandomString(4, 6); std::string KEY1 = generateRandomString(1, 10); std::string KEY2 = generateRandomString(1, 10); std::string STR_VALUE = generateRandomString(5, 20); int INT_VALUE = rand(); std::shared_ptr<KVSpace> space = db->get_space(SPACE_NAME); space->set_value(KEY1, STR_VALUE); EXPECT_EQ(boost::get<std::string>(space->get_value(KEY1)), STR_VALUE); space->set_value(KEY2, INT_VALUE); EXPECT_EQ(boost::get<int>(space->get_value(KEY2)), INT_VALUE); } TEST_F(SqlKVDatabase_Test, SpaceAccessReferenceTest) { std::string space_name = generateRandomString(); std::shared_ptr<KVSpace> space = db->get_space(space_name); std::string key = generateRandomString(); std::string str_value = generateRandomString(); space->set_value(key, str_value); std::shared_ptr<KVSpace> space2 = db->get_space(space_name); EXPECT_EQ(boost::get<std::string>(space2->get_value(key)), str_value); } TEST_F(SqlKVDatabase_Test, SpaceGetNilValueTest) { std::string space_name = generateRandomString(); std::string key = generateRandomString(); std::shared_ptr<KVSpace> space = db->get_space(space_name); EXPECT_ANY_THROW(space->get_value(key)); } TEST_F(SqlKVDatabase_Test, StressTest) { generateStressTestData(db); } <file_sep>/test/SimpleKVDevDBTest.cpp // // Created by Rayer on 14/08/2017. // #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Data/SimpleKVDevDB.h> #include <Data/DataPersistenceManager.h> using namespace Iris; class SimpleDevDB_Test : public ::testing::Test { protected: KVDataPersistenceLayer *db = nullptr; void SetUp() override { db = DataPersistenceManager::getInstance(); srand((unsigned int) time(nullptr)); db->wipe(true); } void TearDown() override { //std::cout << "TearDown()" << std::endl; //Don't delete because it is singleton //delete db; } std::string generateRandomString(int min = 1, int max = 10) { static const char *rule = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; size_t rule_length = std::strlen(rule); std::string ret; int length = rand() % (max - min + 1) + min; for (int i = 0; i < length; ++i) ret += rule[rand() % rule_length]; return ret; } std::map<std::string, std::shared_ptr<KVSpace>> generateTestData(int space_count = 100, int space_size_min = 1, int space_size_max = 10) { std::map<std::string, std::shared_ptr<KVSpace>> ret; for (int i = 0; i < space_count; i++) { //Generate name std::string name; do { name = generateRandomString(1, 16); if (ret.find(name) != ret.end()) name = ""; } while (name.empty()); std::shared_ptr<KVSpace> space = std::make_shared<SimpleKVDevDBSpace>(); int space_size = rand() % (space_size_max - space_size_min) + space_size_min; for (int i = 0; i < space_size; ++i) { if (rand() % 2) space->set_value(generateRandomString(1, 10), rand()); else space->set_value(generateRandomString(1, 10), generateRandomString(1, 16)); } ret.insert({name, space}); } return ret; } }; TEST_F(SimpleDevDB_Test, SpaceAccessTest) { std::string SPACE_NAME = generateRandomString(4, 6); std::string KEY1 = generateRandomString(1, 10); std::string KEY2 = generateRandomString(1, 10); std::string STR_VALUE = generateRandomString(5, 20); int INT_VALUE = rand(); std::shared_ptr<KVSpace> space = db->get_space(SPACE_NAME); space->set_value(KEY1, STR_VALUE); EXPECT_EQ(boost::get<std::string>(space->get_value(KEY1)), STR_VALUE); space->set_value(KEY2, INT_VALUE); EXPECT_EQ(boost::get<int>(space->get_value(KEY2)), INT_VALUE); } TEST_F(SimpleDevDB_Test, SpaceAccessReferenceTest) { std::string space_name = generateRandomString(); std::shared_ptr<KVSpace> space = db->get_space(space_name); std::string key = generateRandomString(); std::string str_value = generateRandomString(); space->set_value(key, str_value); std::shared_ptr<KVSpace> space2 = db->get_space(space_name); EXPECT_EQ(boost::get<std::string>(space2->get_value(key)), str_value); } TEST_F(SimpleDevDB_Test, SpaceGetNilValueTest) { std::string space_name = generateRandomString(); std::string key = generateRandomString(); std::shared_ptr<KVSpace> space = db->get_space(space_name); EXPECT_ANY_THROW(space->get_value(key)); } TEST_F(SimpleDevDB_Test, SpaceSerializeTest) { std::string space_name = generateRandomString(); std::shared_ptr<KVSpace> space1 = db->get_space(space_name); std::string key1 = generateRandomString(); std::string value1 = generateRandomString(); std::string key2 = generateRandomString(); int value2 = rand(); space1->set_value(key1, value1); space1->set_value(key2, value2); std::static_pointer_cast<SimpleKVDevDBSpace>(space1)->serialize("/tmp/" + space_name + ".test"); std::shared_ptr<KVSpace> space2 = db->get_space(generateRandomString()); std::static_pointer_cast<SimpleKVDevDBSpace>(space2)->deserialize("/tmp/" + space_name + ".test"); EXPECT_EQ(boost::get<std::string>(space1->get_value(key1)), boost::get<std::string>(space2->get_value(key1))); EXPECT_EQ(boost::get<int>(space1->get_value(key2)), boost::get<int>(space2->get_value(key2))); EXPECT_EQ(boost::get<int>(space1->get_value(key2)), value2); } TEST_F(SimpleDevDB_Test, DBSerializeTest) { SimpleKVDevDB *devDb = (SimpleKVDevDB *) db; devDb->wipe(true); std::string space_name1 = generateRandomString(); std::string key1 = generateRandomString(); std::string key2 = generateRandomString(); std::string value1 = generateRandomString(); int value2 = rand(); std::shared_ptr<KVSpace> space1 = db->get_space(space_name1); space1->set_value(key1, value1); space1->set_value(key2, value2); std::string space_name2 = generateRandomString(); std::shared_ptr<KVSpace> space2 = db->get_space(space_name2); std::string key3 = generateRandomString(); std::string key4 = generateRandomString(); std::string value3 = generateRandomString(); int value4 = rand(); space2->set_value(key3, value3); space2->set_value(key4, value4); devDb->serialize("/tmp"); devDb->wipe(true); ASSERT_ANY_THROW(space1->get_value("AAA")); devDb->deserialize("/tmp"); space1 = db->get_space(space_name1); EXPECT_EQ(boost::get<std::string>(space1->get_value(key1)), value1); EXPECT_EQ(boost::get<int>(space1->get_value(key2)), value2); space2 = db->get_space(space_name2); EXPECT_EQ(boost::get<std::string>(space2->get_value(key3)), value3); EXPECT_EQ(boost::get<int>(space2->get_value(key4)), value4); } //TODO: This test case yet have any ASSERT! TEST_F(SimpleDevDB_Test, SimpleDevDBPersistTest) { SimpleKVDevDB *simpleDevDB = new SimpleKVDevDB(); std::map<std::string, std::shared_ptr<KVSpace>> test_data_raw = generateTestData(); for (auto const &pair : test_data_raw) { auto space = std::static_pointer_cast<SimpleKVDevDBSpace>(simpleDevDB->get_space(pair.first)); auto keys = std::static_pointer_cast<SimpleKVDevDBSpace>(pair.second)->get_keys(); for (const std::string &name : keys) { space->set_value(name, pair.second->get_value(name)); } } //std::string folder = "/tmp/" + generateRandomString(5, 6); std::string folder = boost::filesystem::complete(boost::filesystem::temp_directory_path()).generic_string() + "/" + generateRandomString(5, 6); boost::filesystem::remove(folder); simpleDevDB->serialize(folder); delete simpleDevDB; simpleDevDB = new SimpleKVDevDB(); simpleDevDB->deserialize(folder); } <file_sep>/src/Data/SimpleKVDevDBSpace.h // // Created by Rayer on 15/08/2017. // #ifndef IRIS_SIMPLEDEVDBSPACE_H #define IRIS_SIMPLEDEVDBSPACE_H #include "KVSpace.h" #include <map> #include <boost/serialization/access.hpp> #include <boost/serialization/map.hpp> #include <list> namespace Iris { /** * DPL Space for development */ class SimpleKVDevDBSpace : public KVSpace { private: std::map<std::string, ValueType> map; public: void serialize(std::string fullPath); void deserialize(std::string fullPath); ValueType get_value(const std::string &key) override; std::list<std::string> get_keys(); void set_value(const std::string &key, const ValueType &value) override; bool remove(const std::string &key) override; void wipe() override; }; } #endif //IRIS_SIMPLEDEVDBSPACE_H <file_sep>/src/Main/GameMain.cpp /** * Project Iris */ #include "GameMain.h" #include "Context.h" #include "MoMLayer.h" #include <chrono> #include <iostream> using namespace Iris; /** * GameMain implementation */ /** * @param context * @return void */ using namespace Iris; void GameMain::loop(Context *context) { typedef std::chrono::high_resolution_clock time; typedef std::chrono::milliseconds ms; //initialize auto timer = time::now(); while (context->isRunning()) { double delta = std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1>>>( time::now() - timer).count(); mom_layer->update(delta, context); timer = time::now(); } }<file_sep>/src/Main/GameMain.h /** * Project Iris */ #ifndef _GAMEMAIN_H #define _GAMEMAIN_H namespace Iris { class Context; class MoMLayer; class GameMain { private: MoMLayer *mom_layer; public: /** * @param context */ void loop(Context *context); }; } #endif //_GAMEMAIN_H<file_sep>/src/Data/SqlKVDatabaseSpace.h // // Created by <NAME> on 2018/6/5. // #ifndef IRIS_SQLDATABASESPACE_H #define IRIS_SQLDATABASESPACE_H #include "KVSpace.h" #include <mariadb++/connection.hpp> namespace Iris { class SqlKVDatabaseSpace : public KVSpace { private: std::map<std::string, ValueType> map; std::string space_name; mariadb::connection_ref sql_connect; public: SqlKVDatabaseSpace(const std::string &name, mariadb::connection_ref conn); ValueType get_value(const std::string &key) override; void set_value(const std::string &key, const ValueType &value) override; bool remove(const std::string &key) override; void wipe() override; void refresh(); }; } #endif //IRIS_SQLDATABASESPACE_H <file_sep>/src/Main/MoManager.cpp /** * Project Iris */ #include <string> #include "Iris_State.h" #include "Context.h" #include "Loopable.h" #include "MoManager.h" #include <boost/uuid/uuid_generators.hpp> /** * MoManager implementation */ Iris_State Iris::MoManager::update(double delta, Context *context) { std::for_each(this->module_list.begin(), this->module_list.end(), [&](Loopable* loopable){ loopable->update(delta, context); }); return context->isRunning() ? Iris_State::RUNNING : Iris_State::STOP; } boost::uuids::uuid Iris::MoManager::register_module(Loopable *module) { boost::uuids::random_generator gen; boost::uuids::uuid tag = gen(); module->set_tag(tag); module_list.push_back(module); return tag; } bool Iris::MoManager::remove_module(boost::uuids::uuid id) { for (Loopable *loopable : module_list) { if (loopable->tag() == id) { module_list.remove(loopable); return true; } } return false; } <file_sep>/src/Data/SimpleKVDevDB.cpp // // Created by Rayer on 15/08/2017. // #include <sstream> #include <boost/filesystem.hpp> #include "SimpleKVDevDB.h" using namespace boost::filesystem; using namespace Iris; std::shared_ptr<KVSpace> SimpleKVDevDB::get_space(const std::string &name) { auto iter = space_map.find(name); if (iter != space_map.end()) return iter->second; std::shared_ptr<SimpleKVDevDBSpace> space = std::make_shared<SimpleKVDevDBSpace>(); space_map.insert({name, space}); return space; } void SimpleKVDevDB::serialize(std::string folder) { //Create folder if not exist boost::filesystem::create_directory(folder); for (auto iter : space_map) { const std::string &space_name = iter.first; std::ostringstream ss; ss << folder << "/" << space_name << ".sel"; std::static_pointer_cast<SimpleKVDevDBSpace>(iter.second)->serialize(ss.str()); } } void SimpleKVDevDB::deserialize(std::string folder) { path p(folder); if (!is_directory(p)) throw ("Illegal deserialize folder name"); std::list<path> list; std::copy(directory_iterator(p), directory_iterator(), std::back_inserter(list)); for (auto &file : list) { if (file.extension().generic_string() != ".sel") continue; std::shared_ptr<SimpleKVDevDBSpace> space = std::make_shared<SimpleKVDevDBSpace>(); space->deserialize(complete(file).generic_string()); space_map.insert(std::make_pair(file.stem().generic_string(), space)); } } void SimpleKVDevDB::wipe(bool force) { space_map.clear(); }
52b5e5724f4704b66cd26ffe7233209a700d6b60
[ "Markdown", "C", "CMake", "C++" ]
36
C++
Rayer/Iris
c0cbee912fd5292779932ebc77ba761eb7a3f18a
6e53c1486f4c12c44d2b6437f2d5291cfe39a0d0
refs/heads/master
<repo_name>PeachIceTea/nigroni-mgo-session<file_sep>/nms.go package nigronimgosession import "github.com/globalsign/mgo" type contextKey int // Define keys that support equality. const KEY contextKey = 0 type NMS struct { DB *mgo.Database Session *mgo.Session } <file_sep>/database_accessor.go package nigronimgosession import ( "context" "net/http" mgo "github.com/globalsign/mgo" ) type DatabaseAccessor struct { *mgo.Session url string name string coll string } func NewDatabaseAccessor(url, name, coll string) (*DatabaseAccessor, error) { session, err := mgo.Dial(url) if err == nil { return &DatabaseAccessor{session, url, name, coll}, nil } else { return &DatabaseAccessor{}, err } } func (da *DatabaseAccessor) Set(ctx context.Context, request *http.Request, session *mgo.Session) context.Context { db := session.DB(da.name) nms := &NMS{db, session} return context.WithValue(ctx, KEY, nms) }
48caca52c252d1f5b4cb1bd49bad20333c437d97
[ "Go" ]
2
Go
PeachIceTea/nigroni-mgo-session
28198888d8c61787a92204265d2e58e0236222fb
5f94fe2612ca9ddf52e9a96140600af4a6612007
refs/heads/master
<file_sep>#include <iostream> using namespace std; typedef int larik[100]; void moveZeroToEnd(larik& arr, int n){ for(int i=0; i<n; i++){ if(arr[0]==0){ swap(arr[0],arr[n]); } else if(arr[1]==0){ swap(arr[1], arr[n-1]); } else if(arr[2]==0){ swap(arr[2], arr[n-2]); } } } void input(larik& arr, int& n){ cout<<"Masukan panjang data : "; cin>>n; for (int i=0; i<n; i++){ cout<<"Data : "; cin>>arr[i]; } } void output (larik& arr, int n){ for(int i=0; i<n; i++){ cout<<arr[i]<<" "; }cout<<endl; } int main(){ larik arr; int n; input(arr, n); moveZeroToEnd(arr, n); output(arr, n); }
f1a09068f9f6386cec6ac2ed9d2d27e543d4feed
[ "C++" ]
1
C++
Dhik/strukturdata-01
b698aa67c80a805143a540ee2b0f0190696c30e9
65940d359d9346769b9c61cb6aa157eed8ad6b0f
refs/heads/master
<file_sep>package com.example.ba_polizei import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
7bafdc06987b732ec9faff4b8b9df789e36c0093
[ "Kotlin" ]
1
Kotlin
Young-Slim-Jim/ba_polizei
bc0bb93adfccf1787446cc95b15c394764ccee42
58bc66cf5ad4d0b89e3a9c0c388ba7cbd2d0b783
refs/heads/master
<file_sep>package com.reportbuilder.repositories; import com.reportbuilder.domains.Rule; import org.springframework.data.jpa.repository.JpaRepository; public interface RuleRepository extends JpaRepository<Rule, Integer> { } <file_sep>var gulp = require('gulp'); gulp.task('copy', function () { gulp.src(['./node_modules/angular/angular.min.js', './node_modules/angular-route/angular-route.min.js', './node_modules/angular-material/angular-material.min.js', './node_modules/angular-aria/angular-aria.min.js', './node_modules/angular-animate/angular-animate.min.js', './node_modules/lodash/lodash.min.js']) .pipe(gulp.dest('./src/main/resources/static/vendor/js')); gulp.src(['./node_modules/angular-material/angular-material.min.css']) .pipe(gulp.dest('./src/main/resources/static/vendor/css')); // gulp.src([//'./node_modules/ux-navigation/dist/fonts/**/*', // './node_modules/uxicon/fonts/**/*']) // .pipe(gulp.dest('./src/main/resources/static/vendor/css/fonts')); // // gulp.src(['./styleguide/images/**/*',]) // .pipe(gulp.dest('./src/main/resources/static/vendor/images')); }); gulp.task('default', ['copy']);<file_sep>var app = angular.module('ReportBuilder', ['ngRoute', 'ngMaterial']); app.config(function($routeProvider, $httpProvider) { $httpProvider.defaults.withCredentials = true; $routeProvider .when('/reportBuilder', { controller: 'reportBuilderCtrl as reportBuilder', templateUrl: 'reportBuilder.html' }) .when('/reportViewer', { controller: 'reportViewerCtrl as reportViewer', templateUrl: 'reportViewer.html' }) .otherwise({ redirectTo: '/reportBuilder' }) });<file_sep>(function() { 'use strict'; app.controller('reportViewerCtrl', reportViewerCtrl); function reportViewerCtrl(ReportService){ var reportViewer = this; reportViewer.report = ReportService.getReport() } })();<file_sep>(function() { 'use strict'; app.controller('reportBuilderCtrl', reportBuilderCtrl); function reportBuilderCtrl($http, ReportService){ var reportBuilder = this; reportBuilder.rules = [] reportBuilder.currentItem = {} reportBuilder.currentItem.rule = {} reportBuilder.currentRule = 0 reportBuilder.companyName = "" reportBuilder.reportItems = [] reportBuilder.myDate = new Date(); reportBuilder.isOpen = false; reportBuilder.showReport = false; reportBuilder.report = {companyName: null, date: null, introduction: null, reportItems: [], closing: null}; $http.get('/getAllRules') .then(function(data) { reportBuilder.rules = data.data },function(err) { console.error("Error ", err); }); reportBuilder.addItem = function(){ var rule = _.findIndex(reportBuilder.rules, ['id', parseInt(reportBuilder.currentItem.currentRule)]); reportBuilder.currentItem.rule = reportBuilder.rules[rule] reportBuilder.reportItems.push(reportBuilder.currentItem) reportBuilder.currentItem = {} } reportBuilder.generateReport = function() { reportBuilder.showReport = !reportBuilder.showReport; reportBuilder.report.companyName = reportBuilder.companyName; reportBuilder.report.date = reportBuilder.myDate; reportBuilder.report.introduction = reportBuilder.introduction; reportBuilder.report.closing = reportBuilder.closing; reportBuilder.report.reportItems = reportBuilder.reportItems; ReportService.setReport(reportBuilder.report) // reportBuilder.report = ReportService.getReport() location.assign('/#!/reportViewer') } } })();<file_sep>reportbuilder.datasource.url=jdbc:mysql://localhost:3306/reportbuilder?useSSL=false reportbuilder.datasource.username=root reportbuilder.datasource.password= reportbuilder.datasource.driverClassName=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect <file_sep>app.factory("ReportService", function() { var report = {}; return { getReport: function() { return report; }, setReport: function(providedReport) { report = providedReport; } }; });
2f444043525d5d2f2c37b68008a3eb615f8c3d7c
[ "JavaScript", "Java", "INI" ]
7
Java
craigtb/ReportBuilder
609fc98cf06185e4e29073baa25ef671f5051642
4690f1c1ccfee0bbd098b7a2ade14a1a3997e80b
refs/heads/master
<repo_name>PolluxTechnologies/QPMtool<file_sep>/QueuePerformanceMeasures/src/frame/Wireframe2.java package frame; import java.awt.*; import java.awt.event.*; import java.util.HashMap; import java.util.Map; import javax.swing.*; //Wireframe2 public class Wireframe2 extends JPanel implements ActionListener{ static String buttonCalcString = "Calculate"; static String lambdaString = "Lambda"; //Objetos dentro del panel Wireframe2 JPanel titlePanel, labelPanel, textFieldPanel, centralPanel, lambdaPanel, muPanel; JTextArea textf; JButton buttonCalc; JLabel lambdaLabel, muLabel, serversLabel, capacityLabel, varianceLabel, cvarrivalsLabel, cvserviceLabel; JTextField lambdaTf, muTf, varianceTf, cvarrivalsTf, cvserviceTf; JSpinner serverSpinner, capacitySpinner; public static JComponent getTwoColumnLayout( JLabel[] labels, JComponent[] fields, boolean addMnemonics) { if (labels.length != fields.length) { String s = labels.length + " labels supplied for " + fields.length + " fields!"; throw new IllegalArgumentException(s); } JComponent panel = new JPanel(); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); // Turn on automatically adding gaps between components layout.setAutoCreateGaps(true); // Create a sequential group for the horizontal axis. GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); GroupLayout.Group yLabelGroup = layout.createParallelGroup(GroupLayout.Alignment.TRAILING); hGroup.addGroup(yLabelGroup); GroupLayout.Group yFieldGroup = layout.createParallelGroup(); hGroup.addGroup(yFieldGroup); layout.setHorizontalGroup(hGroup); // Create a sequential group for the vertical axis. GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); layout.setVerticalGroup(vGroup); int p = GroupLayout.PREFERRED_SIZE; // add the components to the groups for (JLabel label : labels) { yLabelGroup.addComponent(label); } for (Component field : fields) { yFieldGroup.addComponent(field, p, p, p); } for (int ii = 0; ii < labels.length; ii++) { vGroup.addGroup(layout.createParallelGroup(). addComponent(labels[ii]). addComponent(fields[ii], p, p, p)); } if (addMnemonics) { addMnemonics(labels, fields); } return panel; } private final static void addMnemonics( JLabel[] labels, JComponent[] fields) { Map<Character, Object> m = new HashMap<Character, Object>(); for (int ii = 0; ii < labels.length; ii++) { labels[ii].setLabelFor(fields[ii]); String lwr = labels[ii].getText().toLowerCase(); for (int jj = 0; jj < lwr.length(); jj++) { char ch = lwr.charAt(jj); if (m.get(ch) == null && Character.isLetterOrDigit(ch)) { m.put(ch, ch); labels[ii].setDisplayedMnemonic(ch); break; } } } } public static JComponent getTwoColumnLayout( String[] labelStrings, JComponent[] fields) { JLabel[] labels = new JLabel[labelStrings.length]; for (int ii = 0; ii < labels.length; ii++) { labels[ii] = new JLabel(labelStrings[ii]); } return getTwoColumnLayout(labels, fields); } public static JComponent getTwoColumnLayout( JLabel[] labels, JComponent[] fields) { return getTwoColumnLayout(labels, fields, true); } private Wireframe2(){ //Crea la ventana JFrame jfrme = new JFrame("Queue Performance Measures"); //Opciones por defecto de la ventana jfrme.setLayout(new FlowLayout()); jfrme.setSize(380, 390); jfrme.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrme.getContentPane().setBackground(Color.WHITE); //Panel con el título titlePanel = new JPanel(); titlePanel.setBorder(BorderFactory.createLineBorder(Color.black)); titlePanel.setPreferredSize(new Dimension(340, 80)); titlePanel.setLayout(new GridBagLayout()); titlePanel.setBackground(Color.WHITE); textf= new JTextArea("Insert Parameters"); textf.setEditable(false); textf.setFont(new Font("Arial", Font.PLAIN, 24)); titlePanel.add(textf); JComponent[] components = { new JTextField(5), new JTextField(5), new JSpinner(new SpinnerNumberModel(1,1,20,1)), new JSpinner(new SpinnerNumberModel(1,1,20,1)), new JTextField(5), new JTextField(5), new JTextField(5) }; String[] labels = { "Lambda:", "Mu:", "Number of servers:", "Capacity:", "Variance:", "CV for interarrival times:", "CV for service times:" }; JComponent labelsAndFields = getTwoColumnLayout(labels,components); labelsAndFields.setBackground(Color.WHITE); labelsAndFields.setPreferredSize(new Dimension(240, 190)); labelPanel=new JPanel(); labelPanel.setPreferredSize(new Dimension(25, 180)); labelPanel.setBackground(Color.WHITE); centralPanel = new JPanel(); buttonCalc = new JButton(buttonCalcString); jfrme.add(titlePanel); centralPanel.add(labelPanel); centralPanel.add(labelsAndFields, BorderLayout.CENTER); centralPanel.setBackground(Color.WHITE); jfrme.add(centralPanel); jfrme.add(buttonCalc); jfrme.setResizable(false); jfrme.setVisible(true); } public void actionPerformed(ActionEvent ae){ } public static void main(String[] args) { // TODO Auto-generated method stub new Wireframe2(); } } <file_sep>/QueuePerformanceMeasures/src/QPM.java //Clase abstracta que contiene tanto los parámetros de entrada como las medidas de desempeño class Queue { //Parámetros de entrada double arrivalRate; //Tasa de entrada de los clientes al sistema //boolean arrivalM; //1 si el proceso de entradas es Markoviano, 0 de lo contrario double serviceRate; //Tasa de servicio de los servidores //boolean serviceM; //1 si el proceso de servicio es Markoviano, 0 de lo contrario //int numServers; //Número de servidores en paralelo //int capacity; //Máximo número de clientes que admite el sistema en un instante cualquiera //double varService; //Varianza en el tiempo de servicio //double cvArrival; //Coeficiente de variación al cuadrado de los tiempos entre arribos //double cvService; //Coeficiente de variación al cuadrado de los tiempos de servicio //Medidas de desempeño //double eeL; //Número promedio de entidades en el sistema en estado estable //double eeLq; //Número promedio de entidades esperando en el sistema en estado estable //double eeLs; //Número promedio de entidades siendo atendidas en el sistema en estado estable //double eeW; //Tiempo promedio que demora un cliente en el sistema en estado estable //double eeWq; //Tiempo promedio que demora un cliente esperando en el sistema en estado estable //double eeWs; //Tiempo promedio que demora un cliente siendo atendido en el sistema en estado estable //double exitRate; //Tasa de salida efectiva de los clientes //double util; //Utilización del servidor //double pij; //Probabilidades en estado estable de que hayan j clientes en el sistema //double cvDeparture; //Coeficiente de variación al cuadrado de los tiempos entre salidas //Métodos void setArrivalRate(double lambda){arrivalRate=lambda;} void setServiceRate(double mu){serviceRate=mu;} } //Clase que define las propiedades de modelo de cola M/M/1 class mmOne extends Queue { //Constructor mmOne(double l, double m){//l Lambda: tasa de arribos, m Mu: tasa de servicios if(l/m >=1){//Verifico estabilidad throw new ArithmeticException(); } else {//Si el sistema es estable realizo la asignación de parámetros setArrivalRate(l); //Tasa de arribos=lambda setServiceRate(m); //Tasa de servicios=mu } } //Método cálculo de ocupación double util(){ return arrivalRate/serviceRate; } //Método cálculo de L double eeL(){ return util()/(1-util()); } //Método cálculo de Lq double eeLq(){ return Math.pow(util(), 2)/(1-util()); } //Método cálculo de Ls double eeLs(){ return eeL()-eeLq(); } //Método cálculo de W double eeW(){ return eeL()/arrivalRate; } //Método cálculo de Wq double eeWq(){ return eeLq()/arrivalRate; } //Método cálculo de Ws double eeWs(){ return eeLs()/arrivalRate; } double pij(int j){ return Math.pow(util(),j)*(1-util()); } } class QPM{ public static void main(String[] args) { try{//Se verifica estabilidad del sistema mmOne line = new mmOne(4,4); System.out.println("La ocupación del servidor es " + line.util()); System.out.println("Ws es " + line.eeWs()); System.out.println("Ls prob en e.e. de 3 clientes en la línea es " + line.pij(3)); } catch(ArithmeticException exc){//Si el sistema no estable devuelve un mensaje de error System.out.println("El sistema no es estable. Por favor verifique los parámetros ingresados."); } } }<file_sep>/QueuePerformanceMeasures/src/frame/Wireframe3.java package frame; import java.awt.*; import java.awt.event.*; import javax.swing.*; //Wireframe1 public class Wireframe3 extends Frame implements ActionListener{ //Elementos dentro del panel Wireframe1 JPanel titlePanel, dataPanel, pmPanel, probPanel, buttonPanel; JTextArea titleTextArea, dataTextArea, pmTextArea, probTextArea; JButton buttonChange, buttonSelect; //Textos estáticos static String dataString = "Data summary"; static String pmString = "Performance measures"; static String probString = "Probability distribution chart"; static String buttonChangeString = "Change parameters"; static String buttonSelectString = "Select another model"; private Wireframe3() { //Crea la ventana JFrame jfrm = new JFrame("Queue Performance Measures"); //Opciones por defecto de la ventana jfrm.setLayout(new FlowLayout()); jfrm.setSize(380, 790); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrm.getContentPane().setBackground(Color.WHITE); //Panel con el título titlePanel = new JPanel(); titlePanel.setBorder(BorderFactory.createLineBorder(Color.black)); titlePanel.setPreferredSize(new Dimension(340, 80)); titlePanel.setLayout(new GridBagLayout()); titlePanel.setBackground(Color.WHITE); titleTextArea = new JTextArea("Performance Measures"); titleTextArea.setEditable(false); titleTextArea.setFont(new Font("Arial", Font.PLAIN, 24)); titlePanel.add(titleTextArea); //Panel de resumen de información dataPanel = new JPanel(); dataPanel.setPreferredSize(new Dimension(240, 180)); dataPanel.setBackground(Color.WHITE); dataPanel.setBorder(BorderFactory.createTitledBorder(dataString)); pmPanel = new JPanel(); pmPanel.setPreferredSize(new Dimension(240, 180)); pmPanel.setBackground(Color.WHITE); pmPanel.setBorder(BorderFactory.createTitledBorder(pmString)); probPanel = new JPanel(); probPanel.setPreferredSize(new Dimension(240, 180)); probPanel.setBackground(Color.WHITE); probPanel.setBorder(BorderFactory.createTitledBorder(probString)); //Botón Change; buttonChange = new JButton(buttonChangeString); buttonChange.setPreferredSize(new Dimension(160, 30)); buttonChange.addActionListener(this); //Botón Select; buttonSelect = new JButton(buttonSelectString); buttonSelect.setPreferredSize(new Dimension(160, 30)); buttonSelect.addActionListener(this); //Panel para el botón buttonPanel = new JPanel(); buttonPanel.setLayout(new GridBagLayout()); buttonPanel.setBackground(Color.WHITE); buttonPanel.setPreferredSize(new Dimension(340, 50)); buttonPanel.add(buttonChange); buttonPanel.add(buttonSelect); //Añade elementos al Frame jfrm.add(titlePanel); jfrm.add(dataPanel); jfrm.add(pmPanel); jfrm.add(probPanel); jfrm.add(buttonPanel); jfrm.setResizable(false); //Hace visible el Frame jfrm.setVisible(true); } public void actionPerformed(ActionEvent ae){ } public static void main(String[] args) { // TODO Auto-generated method stub new Wireframe3(); } }
16af341ed4268d30b47851f55087e5995d553271
[ "Java" ]
3
Java
PolluxTechnologies/QPMtool
59196e92574eefecd96d27a8804988c775caa7c2
e6d9e6ec275f8785385c113e9149a8a119f241bc
refs/heads/main
<file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTblTongquan extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tbl_tongquan', function (Blueprint $table) { $table->increments('tongquan_id'); $table->integer('doanhso'); $table->integer('loinhuan'); $table->date('time'); $table->integer('tongdon'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tbl_tongquan'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class HoaDonCafeDetail extends Model { public $timestamps = false; protected $fillable = [ 'hoadoncafeDetail_id','sanpham_id','hoadoncafe_id','hoadoncafeDetail_nums','hoadoncafeDetail_price' ]; protected $primaryKey = 'hoadoncafeDetail_id'; protected $table = 'tbl_hoadoncafeDetail'; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use Session; use App\Http\Requests; use Illuminate\Support\Facades\Redirect; session_start(); class ThietBiController extends Controller { public function AuthLogin() { $admin_id = Session::get('admin_id'); if($admin_id){ return Redirect::to('dashboard'); }else{ return Redirect::to('admin')->send(); } } public function add_thietbi() { $this->AuthLogin(); return view('admin.add_thietbi'); } public function all_thietbi() { $this->AuthLogin(); $all_thietbi= DB::table('tbl_thietbi')->get(); $quanly_thietbi = view('admin.all_thietbi')->with('all_thietbi',$all_thietbi); return view('Admin_Layout')->with('admin.all_thietbi',$quanly_thietbi); } public function save_thietbi(Request $request) { $this->AuthLogin(); $time=Carbon::now('Asia/Ho_Chi_Minh'); $data = array(); $data['thietbi_name'] = $request->thietbi_name; $data['thietbi_price'] = $request->thietbi_price; $get_image = $request->file('thietbi_image'); if($get_image){ $get_name_image = $get_image->getClientOriginalName(); //lấy tên ảnh $name_image = current(explode('.',$get_name_image));//phân tách tên ảnh $new_image = $name_image.rand(0,99).'.'.$get_image->getClientOriginalExtension();//lấy tên + random + đuôi ảnh $get_image->move('public/uploads/nguyenlieu',$new_image); $data['thietbi_image'] = $new_image; DB::table('tbl_thietbi')->insert($data); Session::put('message','Thêm nguyên liệu thành công'); return Redirect::to('add_thietbi'); } $data['thietbi_image'] = ''; DB::table('tbl_thietbi')->insert($data); Session::put('message','Thêm nguyên liệu thành công'); return Redirect::to('all_thietbi'); } public function edit_thietbi($thietbi_id) { $this->AuthLogin(); $edit_thietbi = DB::table('tbl_thietbi')->where('thietbi_id',$thietbi_id)->get(); $manager_thietbi = view('admin.edit_thietbi')->with('edit_thietbi',$edit_thietbi); return view('Admin_Layout')->with('admin.edit_thietbi',$manager_thietbi); } public function update_thietbi(Request $request, $thietbi_id) { $this->AuthLogin(); $time=Carbon::now('Asia/Ho_Chi_Minh'); $data['thietbi_name'] = $request->thietbi_name; $data['thietbi_price'] = $request->thietbi_price; $get_image = $request->file('thietbi_image'); if($get_image){ $get_name_image = $get_image->getClientOriginalName(); //lấy tên ảnh $name_image = current(explode('.',$get_name_image));//phân tách tên ảnh $new_image = $name_image.rand(0,99).'.'.$get_image->getClientOriginalExtension();//lấy tên + random + đuôi ảnh $get_image->move('public/uploads/nguyenlieu',$new_image); $data['thietbi_image'] = $new_image; DB::table('tbl_thietbi')->insert($data); Session::put('message','Thêm nguyên liệu thành công'); return Redirect::to('add_thietbi'); } DB::table('tbl_thietbi')->where('thietbi_id',$thietbi_id)->update($data); Session::put('message','Cập nhật thiết bị thành công!'); return Redirect::to('all_thietbi'); } public function delete_thietbi($thietbi_id) { $this->AuthLogin(); DB::table('tbl_thietbi')->where('thietbi_id',$thietbi_id)->delete(); Session::put('message','Xóa thiết bị thành công!'); return Redirect::to('all_thietbi'); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTblPhieuxuat extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tbl_phieuxuat', function (Blueprint $table) { $table->increments('phieuxuat_id'); $table->text('phieuxuat_nguoi'); $table->date('phieuxuat_time'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tbl_phieuxuat'); } }
7878016e5ed396fdb73c2c6d1ba7a398372101be
[ "PHP" ]
4
PHP
hoangvm1312/doan
485ce8ab16885175a4645182589cecd0f1d735d6
c6f6ba8e50ddfd6e93d96caec15d3209ca46b877
refs/heads/main
<repo_name>rodrygo262/devBook<file_sep>/api/sql/dados.sql insert into usuarios ( nome, nick, email, senha ) values ( "usuario 1", "usuario_1", "<EMAIL>", "$2a$10$m5DY80/oWGEl9VwE9ifZY.YrzriXrsWCbP40lBV/msAU0zroXmzCm" ), ( "usuario 2", "usuario_2", "<EMAIL>", "$2a$10$m5DY80/oWGEl9VwE9ifZY.YrzriXrsWCbP40lBV/msAU0zroXmzCm" ), ( "usuario 3", "usuario_3", "<EMAIL>", "$2a$10$m5DY80/oWGEl9VwE9ifZY.YrzriXrsWCbP40lBV/msAU0zroXmzCm" ); insert into seguidores ( usuario_id, seguidor_id ) values ( 1, 2 ), ( 3, 1 ), ( 1, 3 );<file_sep>/api/src/controllers/usuarios.go package controllers import ( "api/src/autenticacao" "api/src/db" "api/src/model" "api/src/repositorios" "api/src/respostas" "encoding/json" "errors" "io/ioutil" "net/http" "strconv" "strings" "github.com/gorilla/mux" ) // CriarUsuario Insere um usuário no banco de dados func CriarUsuario(w http.ResponseWriter, r *http.Request) { corpoRequest, erro := ioutil.ReadAll(r.Body) if erro != nil { respostas.Erro(w, http.StatusUnprocessableEntity, erro) return } var usuario model.Usuario if erro = json.Unmarshal(corpoRequest, &usuario); erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } if erro = usuario.Preparar("cadastro"); erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) usuario.ID, erro = repositorio.Criar(usuario) if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusCreated, usuario) } // BuscarUsuarios busca todos usuários no banco de dados func BuscarUsuarios(w http.ResponseWriter, r *http.Request) { nomeOuNick := strings.ToLower(r.URL.Query().Get("usuario")) db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) usuarios, erro := repositorio.Buscar(nomeOuNick) if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusOK, usuarios) } // BuscarUsuario busca um usuário no banco de dados func BuscarUsuario(w http.ResponseWriter, r *http.Request) { parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) usuario, erro := repositorio.BuscarPorId(usuarioId) if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusOK, usuario) } // AtualizarUsuario Atualiza um usuário no banco de dados func AtualizarUsuario(w http.ResponseWriter, r *http.Request) { parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } usuarioToken, erro := autenticacao.ExtrairUsuarioID(r) if erro != nil { respostas.Erro(w, http.StatusUnauthorized, erro) return } if usuarioId != usuarioToken { respostas.Erro(w, http.StatusForbidden, errors.New("não é possível atualizar um usuário que não seja o seu")) return } corpoRequest, erro := ioutil.ReadAll(r.Body) if erro != nil { respostas.Erro(w, http.StatusUnprocessableEntity, erro) return } var usuario model.Usuario if erro = json.Unmarshal(corpoRequest, &usuario); erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } if erro = usuario.Preparar("edicao"); erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) if erro = repositorio.Atualizar(usuarioId, usuario); erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusNoContent, nil) } // DeletarUsuario Deleta um usuário no banco de dados func DeletarUsuario(w http.ResponseWriter, r *http.Request) { parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) } usuarioToken, erro := autenticacao.ExtrairUsuarioID(r) if erro != nil { respostas.Erro(w, http.StatusUnauthorized, erro) return } if usuarioId != usuarioToken { respostas.Erro(w, http.StatusForbidden, errors.New("não é possível deletar um usuário que não seja o seu")) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) if erro = repositorio.Deletar(usuarioId); erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusNoContent, nil) } // SeguirUsuario permite que um usuário siga outro func SeguirUsuario(w http.ResponseWriter, r *http.Request) { seguidor_id, erro := autenticacao.ExtrairUsuarioID(r) if erro != nil { respostas.Erro(w, http.StatusUnauthorized, erro) return } parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } if seguidor_id == usuarioId { respostas.Erro(w, http.StatusForbidden, errors.New("não é possível seguir você mesmo")) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) if erro = repositorio.Seguir(usuarioId, seguidor_id); erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusNoContent, nil) } // PararDeSeguirUsuario permite que um usuário pare de seguir outro func PararDeSeguirUsuario(w http.ResponseWriter, r *http.Request) { seguidor_id, erro := autenticacao.ExtrairUsuarioID(r) if erro != nil { respostas.Erro(w, http.StatusUnauthorized, erro) return } parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } if seguidor_id == usuarioId { respostas.Erro(w, http.StatusForbidden, errors.New("não é possível parar de seguir você mesmo")) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) if erro = repositorio.PararDeSeguir(usuarioId, seguidor_id); erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusNoContent, nil) } // BuscarSeguidores busca todos seguidores do usuário func BuscarSeguidores(w http.ResponseWriter, r *http.Request) { parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) seguidores, erro := repositorio.BuscarSeguidores(usuarioId) if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusOK, seguidores) } // BuscarSeguido busca todos os usuários que o usuário esta seguindo func BuscarSeguido(w http.ResponseWriter, r *http.Request) { parametros := mux.Vars(r) usuarioId, erro := strconv.ParseUint(parametros["usuarioId"], 10, 64) if erro != nil { respostas.Erro(w, http.StatusBadRequest, erro) return } db, erro := db.Conectar() if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } defer db.Close() repositorio := repositorios.NovoRepositorioDeUsuarios(db) seguindo, erro := repositorio.BuscarSeguido(usuarioId) if erro != nil { respostas.Erro(w, http.StatusInternalServerError, erro) return } respostas.JSON(w, http.StatusOK, seguindo) } <file_sep>/api/sql/sql.sql CREATE DATABASE IF NOT EXISTS devbook; USE devbook; DROP TABLE IF EXISTS usuarios; DROP TABLE IF EXISTS seguidores; CREATE TABLE usuarios( id int auto_increment primary key, nome varchar(50) not null, nick varchar(50) not null unique, email varchar(50) not null unique, senha varchar(100) not null, criadoem timestamp default current_timestamp() ) ENGINE=INNODB; CREATE TABLE seguidores ( usuario_id int not null, foreign key ( usuario_id ) references usuarios(id) on delete cascade, seguidor_id int not null, foreign key ( seguidor_id ) references usuarios(id) on delete cascade, primary key(usuario_id, seguidor_id) ) ENGINE=INNODB ;<file_sep>/README.md # devBook Criando aplicação de estudo
d385933c4c2d3c524669cb7b27d24f907b0414cc
[ "Markdown", "SQL", "Go" ]
4
SQL
rodrygo262/devBook
e170b3fccfeb373452125544e27053227102bb52
db5d3d47a8c09e2cb10b217967316cbad17925c0
refs/heads/main
<file_sep>// JavaScript source code /*Un utente può iscriversi alla Newsletter inserendo il proprio nome nella pagina News e cliccando Subscribe. Se l’utente non ha inserito alcun testo, il pulsante Subscribe deve essere disabilitato. Se l’utente ha effettuato la sottoscrizione alla newsletter, allora nella pagina News sarà visibile solo un pulsante “Unsubscribe”. Se l’utente ha effettuato la sottoscrizione alla newsletter, allora ogni qual volta che l’utente entra nella pagina Home sarà inviata un alert con scritto “Benvenuto” con il nome dell’utente, Se l’utente clicca Unsubscribe, la sua sottoscrizione viene annullata. */ function subscribe() { let check; let form = document.querySelectorAll("input.subs"); for (let i = 0; i < form.length; i++) { if (!form[i].value.length == 0) { check = true; continue; } else { check = false; break; } } alert("sei iscritto!"); save(); } function unsubscribe() { let button = document.querySelector("button.subscrib"); if (save()) { button.innerText = "unsubscribe"; } } function save() { let storage = getStorage(); let key = document.getElementById("nome").value; let value = document.getElementById("email").value; try { storage.setItem(key, value); } catch (e) { alert("impossibile salvare i dati richiesti"); } } function getStorage() { let storageName = "sessionStorage"; try { return (storageName in window && window[storageName] != null) ? window[storageName] : null; //se è diverso da null } catch (e) { return null; } } function welcome() { let storage = getStorage(); let key = document.getElementById("nome").value; let value = storage.getItem(key); alert("benvenuto " + key); }
6bdbb0da972b1488260e467b2b6a177692092117
[ "JavaScript" ]
1
JavaScript
isa100fanti/Week7.Esercitazione
9813214dd266fa82126ab917b4b5ac2c71386053
2ad019dd7428f3246dd9e2b77cdc6f14ae0dd008
refs/heads/master
<repo_name>duyleomessi/LearnAngularjsCourse<file_sep>/week1/Source/footballer/app/scripts/main.js angular.module('conFusion',[]) .controller('FooballCtr', ['$scope', function($scope) { $scope.footballers = [ { name: 'Messi', birdth: '1987', team: 'barcelona', image: 'images/messi.jpg', alt: 'messi picture', discription: 'best in the world', comment: '' }, { name: 'Neymar', birdth: '1992', team: 'barcelona', image: 'images/neymar.jpg', alt: 'neymar picture', discription: 'best young in the world', comment: '' }, { name: 'ronaldinho', birdth: '1980', team:'barcelona', image: 'images/ronaldinho.jpg', alt: 'ronaldinho picture', discription: 'formal best in the world', comment: '' } ]; }]);
de60059e9e3119f34b442547539ecb2603f724d3
[ "JavaScript" ]
1
JavaScript
duyleomessi/LearnAngularjsCourse
41d670f655582c05737b155a7403f72a3e7707ef
f3d740ef123f3109b5070168426dcce7248f093b
refs/heads/master
<file_sep>'use strict'; const Tweet = require('./../models').tweet; class StartsController { /** * @apiUrl {get} /stars/ Get stared * * @apiResult {Boolean} success * @apiResult {Array<Tweet>} items Array of items */ getStarred(req, res, next) { Tweet .findAll({order: ['stared']}) .then(tweets => { res.send({ success: true, items: tweets }) }) .catch(err => next(err)) } /** * @apiUrl {get} /stars/add Add tweet to stared * * @apiParam {Object} Raw tweet object * * @apiResult {Boolean} success */ starTweet(req, res, next) { if (!req.body || !req.body.id) { return next('Bad params'); } req.body.stared = new Date(); Tweet .create(req.body) .then(() => { res.send({ success: true }) }) .catch(err => next(err)) } /** * @apiUrl {get} /stars/remove/:id Remove tweet by id * * @apiParam {Number} id Tweet id * * @apiResult {Boolean} success */ unstarTweet(req, res, next) { if (!req.params || !req.params.id) { return next('Bad params. Id not specified'); } Tweet .findById(req.params.id) .then((tweet) => { return tweet.destroy() }) .then(() => { res.send({ success: true }) }) .catch(err => next(err)) } } module.exports = StartsController;<file_sep># Twitter Test This project contain two parts: Backend and frontend. It's search tweets by keywords from config. For check how this work you should start both parts. ### Requirements - Node.js 6.2+ - PostgreSQL server - Angular Cli Tool ### Installation Please check `server/config.js` before start, for make sure you have configuration for database and twitter account - `git clone https://github.com/YaphetS1/tweet-test.git` - `cd tweet-test` - `npm i` - `npm start` - Now follow to `http://localhost:4000` in your browser ![alt text](./scr.png) <file_sep>'use strict'; function Schema(sequelize, DataTypes) { let Schema = { id: { type: DataTypes.BIGINT, primaryKey: true }, idStr: DataTypes.STRING, text: DataTypes.STRING, source: DataTypes.STRING, user: DataTypes.JSON, media: DataTypes.JSON, createdAt: DataTypes.DATE, timestampMs: DataTypes.BIGINT, stared: DataTypes.DATE }; let Model = sequelize.define('tweet', Schema); /** * Convert raw twitter to model style * @param tweetObject * @return {{id, idStr: string, text, source, user, media: string, createdAt: string, timestampMs: string}} */ Model.normalizeTweet = (tweetObject) => { let media = tweetObject.extended_entities && tweetObject.extended_entities.media || null; return { id: tweetObject.id, idStr: tweetObject.id_str, text: tweetObject.text, source: tweetObject.source, user: tweetObject.user, media: media, createdAt: typeof tweetObject.created_at === 'string' ? new Date(tweetObject.created_at) : tweetObject.created_at, timestampMs: tweetObject.timestamp_ms } }; return Model; } module.exports = Schema;<file_sep>export const environment = { production: true, apiUrl: 'https://twitter-test-project.yaphets.com/api' }; <file_sep>'use strict'; const express = require('express') , router = express.Router() , StartsController = require('./../controllers/stars') , startsCtrl = new StartsController(); router.get('/', startsCtrl.getStarred.bind(startsCtrl)); router.post('/add', startsCtrl.starTweet.bind(startsCtrl)); router.get('/remove/:id', startsCtrl.unstarTweet.bind(startsCtrl)); module.exports = router;<file_sep>const express = require('express') , router = express.Router() , TwitterController = require('./../controllers/twitter') , twitterCtrl = new TwitterController(); router.get('/', twitterCtrl.getTweets.bind(twitterCtrl)); module.exports = router;<file_sep># Frontend To run this do following steps: - npm i - ng serve - follow to `http://localhost:4000` <file_sep># Server To run this do following steps: - npm i - node app.js <file_sep>import { Component } from '@angular/core'; import { TweetService } from './services/tweet'; import { StaredService } from './services/stared'; import Tweet from './models/tweet'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { tweets: Array<Tweet> = []; staredTweets: Array<Tweet> = []; constructor(private tweetService: TweetService, private staredService: StaredService) { } ngOnInit(){ this.updateTweets(); this.updateStared(); } updateTweets() { return this .tweetService .getTweets() .subscribe(items => { this.tweets = items; }, err => { console.error(err); }) } updateStared() { return this .staredService .getStared() .subscribe(items => { this.staredTweets = items; }, err => { console.error(err); }) } onTweetChanged(tweet) { if (tweet.stared) { this.staredTweets.push(tweet); } else { this.staredTweets.splice(this.staredTweets.indexOf(tweet), 1); } } } <file_sep>'use strict'; const Twit = require('twit') , appConfig = require('../config') , Tweet = require('./../models').tweet; class TwitterService { constructor() { this.twitter = new Twit(appConfig.twitter); if (!appConfig.keywords || !appConfig.keywords.length) { throw 'Config error! Keywords not set'; } } getTweets(count) { return new Promise((resolve, reject) => { this.twitter.get('search/tweets', {q: appConfig.keywords, count: count || 50}, (err, data) => { if (err) { return reject(err); } let items = []; if (data.statuses && data.statuses.length) { items = data .statuses .map(tweet => Tweet.normalizeTweet(tweet)); } resolve(items); }); }) } } module.exports = new TwitterService();<file_sep>module.exports = { server: { port: 4000, // database: 'postgres://postgres:postgres@localhost:5432/tweet' database: 'postgres://localhost:5432/tweet' }, twitter: { consumer_key: '0uJ9168FNKyo5pPEOaZWgvDgF', consumer_secret: '<KEY>', access_token: '<KEY>', access_token_secret: '<KEY>' }, keywords: 'eCommerce video' }<file_sep>'use strict'; const tweets = require('./tweets') , stars = require('./starts'); module.exports = function (app) { app.use('/api/tweets', tweets); app.use('/api/stars', stars); // Catch 404 and forward to error handler app.use((req, res, next) => { next('Route not found'); }); // Catch other errors app.use((err, req, res, next) => { console.error(err); res.send({ success: false, error: err }); }); return app; };<file_sep>export default class Tweet { "created_at": string; "id": number; "id_str": string; "text": string; "source": string; "user": { "id": number; "id_str": string; "name": string; "screen_name": string; "profile_image_url": string; "profile_image_url_https": string; }; "media": [ { "id": number; "id_str": string; "media_url": string; "media_url_https": string; "url": string; "display_url": string; "expanded_url": string; "type": string; "sizes": any; } ]; "timestamp_ms": string; "stared": Date; constructor(tweetObj) { Object.assign(this, tweetObj); this.stared = tweetObj.stared ? new Date(tweetObj.stared) : null; } } <file_sep>import {Component, Input, OnInit} from '@angular/core'; import Tweet from '../../models/tweet'; import {StaredService} from '../../services/stared'; @Component({ selector: 'tweet', templateUrl: './tweet.component.html', styleUrls: ['./tweet.component.css'] }) export class TweetComponent implements OnInit { @Input() tweet: Tweet; @Input() onChange: Function; constructor(private staredService: StaredService) { } ngOnInit() { } star() { // Check if tweet already stared if (this.tweet.stared) { return; } this .staredService .starTweet(this.tweet) .subscribe(() => { this.tweet.stared = new Date(); this.onChange(this.tweet); }) } unstar() { // Check if tweet already stared if (!this.tweet.stared) { return; } this .staredService .unstarTweet(this.tweet.id) .subscribe(() => { delete this.tweet.stared; this.onChange(this.tweet); }) } } <file_sep>import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import {environment as env} from '../../environments/environment'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import Tweet from '../models/tweet'; @Injectable() export class StaredService { constructor(private http: Http) { } /** * Return stared tweets * @return {Observable<Array<Tweet>>} */ getStared(): Observable<Array<Tweet>> { return this.http .get(env.apiUrl + '/stars') .map((res: Response) => { let body = res.json(); let result: any = body || {}; if (!result.success && result.error) { throw {type: 'api', error: result.error || null}; } return result.items.map(item => new Tweet(item)); }) } /** * Star tweet * @param tweetObject Tweet full object * @return {Observable<Boolean>} */ starTweet(tweetObject: Tweet) { return this.http .post(env.apiUrl + '/stars/add', tweetObject) .map((res: Response) => { let body = res.json(); let result: any = body || {}; if (!result.success && result.error) { throw {type: 'api', error: result.error || null}; } return true; }) } /** * Remove stared tweet * @param tweetId Tweet id * @return {Observable<Boolean>} */ unstarTweet(tweetId: number) { return this.http .get(env.apiUrl + '/stars/remove/' + tweetId) .map((res: Response) => { let body = res.json(); let result: any = body || {}; if (!result.success && result.error) { throw {type: 'api', error: result.error || null}; } return true; }) } } <file_sep>import { Injectable } from '@angular/core'; import {Http, Response} from '@angular/http'; import { environment as env } from '../../environments/environment'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import Tweet from '../models/tweet'; @Injectable() export class TweetService { constructor(private http: Http) { } /** * Return tweets * @param count * @return {Observable<Array<Tweet>>} */ getTweets(count: number = 20): Observable<Array<Tweet>> { return this.http .get(env.apiUrl + '/tweets/?count=' + count) .map((res: Response) => { let body = res.json(); let result: any = body || {}; if (!result.success && result.error) { throw {type: 'api', error: result.error || null}; } return result.items.map(item => new Tweet(item)); }) } }
4e144cbb02560c4005f39aecad0d7ac1fe360cbb
[ "JavaScript", "TypeScript", "Markdown" ]
16
JavaScript
YaphetS1/tweet-test
52ba10a184c5a5654632046776e5914459612a6a
4b9342e68124d3ffaceec0f34d65a3c8d6de3b74
refs/heads/master
<file_sep>class TriCount { count(minLength, maxLength) { if (minLength < 1 || 1000000 < minLength) { throw new Error("minLength must be between 1 and 1,000,000"); } else if (maxLength < minLength || 1000000 < maxLength) { throw new Error("maxLength must be between minLength and 1,000,000"); } let triangles = 0; for (let shortest = minLength; shortest <= maxLength; shortest++) { const numberOfMediums = 1 + maxLength - shortest; const numberOfMediumsThatResultInSumBelowMaxLength = Math.max( 0, 1 + maxLength - 2 * shortest ); const numberOfMediumsThatResultInSumAboveMaxLength = numberOfMediums - numberOfMediumsThatResultInSumBelowMaxLength; triangles += shortest * numberOfMediumsThatResultInSumBelowMaxLength; triangles += (1 + numberOfMediumsThatResultInSumAboveMaxLength) * numberOfMediumsThatResultInSumAboveMaxLength / 2; if (triangles > 1000000000) { return -1; } } return triangles; } } module.exports = TriCount;
c93c07ecda486f5d8dd12b40592f6710ec55bf91
[ "JavaScript" ]
1
JavaScript
caugner/ttafs3
6afcf9da5192d7f085b943ea27a0cb25b774720f
3045cc2ddfc42bfe28870a11c875badaa5531cc8
refs/heads/main
<file_sep>// <NAME> // Date: 06.12.2019 // Development Environment: Code Blocks #include <iostream> #include<math.h> using namespace std; int main() { int secim; cout<<"Program seciniz:"; cout << "\n"; cout<<"1- program1"; cout << "\n"; cout<<"2- pragram2"; cout << "\n"; cout<<"3- pragram3"; cout << "\n"; cout<<"4- pragram4"; cout << "\n"; cout<<"5- pragram5"; cout << "\n"; cout<<"6- cikis"; cin>>secim; if(secim==1) { int i, j, n; cout << "Basamak sayisini giriniz: "; cin >> n; for(i = 1; i <= n; i++) { for(j = 1; j <= i; j++) { cout << "* "; } cout << "\n"; } return 0; } if(secim==2) { int i, j, n; cout << "Basamak sayisini giriniz: "; cin >> n; for(i = n; i >= 1; i--) { for(j = 1; j <= i; j++) { cout << "* "; } cout << "\n"; } return 0; } if(secim==3) { int n,i,j,k; cout<<"Basamak sayisini giriniz: "; cin>>n; for (int j = 1; j <= n; j++) { for(int i = n-j; i>0; i--) { cout<<" "; } for(int k = 1; k <= j; k++) { cout<< "* "; } cout << endl; } return 0; } if(secim==4) { int n, s, i, j; cout << "Basamak sayisini giriniz: "; cin >> n; for(i = 1; i <= n; i++) { for(s = i; s < n; s++) { cout << " "; } for(j = 1; j <= (2 * i - 1); j++) { cout << "*"; } cout << "\n"; } } if(secim==5) { int n, s, i, j; cout << "Basamak sayisini giriniz: "; cin >> n; for(i = 0; i <= n; i++) { for(s = n; s > i; s--) cout << " "; for(j=0; j<i; j++) cout << "* "; cout << "\n"; } for(i = 1; i < n; i++) { for(s = 0; s < i; s++) cout << " "; for(j = n; j > i; j--) cout << "* "; cout << "\n"; } return 0; } if (secim == 6) { cout<<"program kapatiliyor"; return(0); } } <file_sep> /* <NAME> 17.01.2021 */ #include <iostream> using namespace std; int main() { cout<< "WELCOME TO CALCULATOR"; cout << "\n"; cout<<"Please choose the challange number"; cout << "\n"; int secim; cout << "1-Challange1(Integer Addition )"; //transaction to be calculated: int addition cout << "\n"; cout << "2-Challange2(Double Addition )"; //transaction to be calculated: double addition cout << "\n"; cout << "3-Challange3(Integer Division)"; //transaction to be calculated: int division cout << "\n"; cout << "4-program4(Double Division)"; //transaction to be calculated: double division cout << "\n"; cout << "5-Challange5(Operator Precedence)"; //transaction to be calculated: number1*number2 + number2*(number1+number2) cout << "\n"; cout << "6-program6(Operator Precedence with Parentheses)"; //transaction to be calculated: (number1+number2) * (number1+number2)+number2 cout << "\n"; cout << "7-program7(Using IF THEN ELSE statement)"; //transaction to be calculated: big one is the answer cout << "\n"; cout << "8-program8(Combine IF clause with operations)"; //transaction to be calculated: if num1+num2=<3, answer is:num1 ; else answer is:num2 cout << "\n"; cout << "9-program9(Combine IF clause with operations )"; //transaction to be calculated: if num1+num2=<3, answer is:num1 ; else answer is:num2 cout << "\n"; cout << "10- QUIT"; cout << "\n"; cin>>secim; { if(secim==1) { cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; int a,b,c; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a+b; cout<<"Answer is:"; cout<<c; cout << "\n"; return 0; } if(secim==2) { cout<<"!!!!!please give double numbers!!!!!"; cout << "\n"; double a,b,c; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a+b; cout<<"Answer is:"; cout<<c; cout << "\n"; return 0; } if(secim==3) { int a,b,c; cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a/b; cout<<"Answer is:"; cout<<c; cout << "\n"; return 0; } if(secim==4) { cout<<"!!!!!please give double numbers!!!!!"; cout << "\n"; double a,b,c; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a/b; cout<<"Answer is:"; cout<<c; cout << "\n"; return 0; } if(secim==5) { cout<<"transaction to be calculated: number1*number2 + number2*(number1+number2)"; cout << "\n"; cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; int a,b,c,d; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a+b; d=b*a+b*c; cout<<"Answer is:"; cout<<d; cout << "\n"; return 0; } if(secim==6) { cout<<"transaction to be calculated: (number1+number2) * (number1+number2)+number2"; cout << "\n"; cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; int a,b,c,d; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a+b; d=(a+b)*c+b; cout<<"Answer is:"; cout<<d; cout << "\n"; return 0; } if(secim==7) { cout<<"transaction to be calculated: big one is the answer"; cout << "\n"; cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; int a1,b1,a2; cout << "First number:"; cout << "\n"; cin>>a1; cout << "Second number:"; cout << "\n"; cin>>b1; { if(a1>b1) { cout<<"Answer is:"; cout<<a1; } else { cout<<"Answer is:"; cout<<b1; } return 0; } } if(secim==8) { cout<<"transaction to be calculated: if num1+num2=<3, answer is:num1 ; else answer is:num2"; cout << "\n"; cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; int a,b,c; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; c=a+b; { if(c<=3) { cout<<"Answer is:"; cout<<a; } else { cout<<"Answer is:"; cout<<b; } return 0; } } if(secim==9) { cout<<"transaction to be calculated: if num1+num2=<3, answer is:num1 ; else answer is:num2"; cout << "\n"; cout<<"!!!!!please give integer numbers!!!!!"; cout << "\n"; int a,b; cout << "First number:"; cout << "\n"; cin>>a; cout << "Second number:"; cout << "\n"; cin>>b; return 0; } if(secim==10) { cout << "Exiting the program."; cout << "\n"; return 0; } } }
c12f266840fb271533678d0df071a73282545e0e
[ "C++" ]
2
C++
aysunurterzi/cpp
60b9fb2cb4ac561fe0eea0ebe3c529fa2971067d
7d3acda0b6799b065e70d37f412f8eac4a6871bf
refs/heads/master
<file_sep>function displayResults(rAWR) { var htmlOpen = '<p>'; var content = ''; var htmlClose = '</p>'; $("#results").empty(); $("#results").addClass('well'); for (var i=0;i<rAWR[1].length;i++) { var title=rAWR[1][i]; var description=rAWR[2][i]; var wikiURL=rAWR[3][i]; content=htmlOpen+'<em><a href="'+wikiURL+'" target="_blank">'+title+'</a></em> '+description; $("#results").append(htmlOpen+content+htmlClose); } } var fetchWiki = function(query) { var roar; $.ajax({ url: '//en.wikipedia.org/w/api.php?action=opensearch&format=json&prop=revisions&search='+query+'&rvprop=content&rvlimit=10&rvsection=0', method: "GET", data: roar, dataType: "jsonp", //headers: { 'Api-User-Agent': 'Example/1.0' }, success: function(roar) { displayResults(roar);} }); }; function sanitizeInput(string) { var resStr = string.split(""); var repl={ "&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","\'":"&#x27","/":"&#x2F"}; resStr=resStr.map(function(a){return (repl.hasOwnProperty(a)) ? repl[a] : a; }); return resStr.join(""); } $("#search").submit(function( event ) { event.preventDefault(); var query=sanitizeInput($("input").val()); fetchWiki(query); });
e4e0409b7df6b272f2d4d5900bf7d14098d43305
[ "JavaScript" ]
1
JavaScript
thmsdnnr/wikirepeatia
d658c0cb5c52e949805407147bf1c576b73a99c1
95e614ac9baeb8da0b9163fb384d7ee3c57e23cc