branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import fs from 'fs' import path from 'path' export function findFile(filename, dirname) { if (!dirname) dirname = process.cwd() if (fs.existsSync(path.join(dirname, filename))) return path.join(dirname, filename) if (dirname !== '/') return findFile(filename, path.resolve(dirname, '..')) else return null } <file_sep>import fs from 'async-file' import path from 'path' import yaml from 'yamljs' import username from 'username' import 'colors' import {Chroot, exec} from './chroot' import {findFile} from './util' export class Box extends Chroot { constructor(name) { super(`/var/lib/machines/${name}`) const configFilename = findFile('box.yml') this.sourceDir = path.dirname(configFilename) this.config = yaml.load(configFilename) this.root = '' exec('xhost +local: > /dev/null') this.mount('/tmp/.X11-unix') this.mount('/dev/shm') this.mount('/run/user/1000', '/run/user/host') this.setenv('DISPLAY', ':0') this.setenv('XDG_RUNTIME_DIR', '/run/user/host') } print(text, color, { bold = true, secondary } = {}) { const bgColor = `bg${color[0].toUpperCase()}${color.slice(1)}` text = ` ${text} ` if (bold) text = text.bold if (color === 'grey') text = text.grey.bgWhite.inverse else text = text[bgColor] text += ''[color] if (secondary) text += ` ${secondary}` console.log(text) } getModule(name) { const config = this.config['modules'][name] return new Module(this, name, config) } async installDependencies() { this.print('Installing dependencies', 'magenta') await this.installPackages(this.config['dependencies']) } async perModule(moduleName, callback) { if (moduleName) { await callback(this.getModule(moduleName)) } else { for (const [name, config] of Object.entries(this.config['modules'])) { const module = new Module(this, name, config) await callback(module) } } } async execTarget(moduleName, target, {printSuccess = true} = {}) { try { await this.perModule(moduleName, (module) => module[target]()) if (printSuccess) this.print('Success', 'green') } catch (error) { this.print(error ? `Failure: ${error}` : 'Failure!', 'red') } } async pull(moduleName) { await this.execTarget(moduleName, 'pull') } async status(moduleName) { if (moduleName) { if (await this.getModule(moduleName).hasUncommitedChanges()) { this.print('Uncommitted changes', 'yellow', { secondary: moduleName }) } } else { const modules = [] for (const [name, config] of Object.entries(this.config['modules'])) { const module = new Module(this, name, config) if (await module.hasUncommitedChanges()) modules.push(name) } if (modules.length > 0) { this.print('Uncommitted changes', 'yellow') for (const module of modules) { console.log(` - ${module}`) } } } } async configure(moduleName) { await this.execTarget(moduleName, 'configure') } async build(moduleName) { await this.execTarget(moduleName, 'build') } async test(moduleName) { await this.execTarget(moduleName, 'test') } async run(moduleName) { await this.execTarget(moduleName, 'run') } async shell() { await this.exec('bash') } } class Module { constructor(chroot, name, config) { this.chroot = chroot this.name = name this.config = config this.local_workdir = path.resolve(chroot.sourceDir, `${name}/build`) this.workdir = path.join(chroot.root, `${name}/build`) } hasTarget(target) { return this.config[target] != null } async buildDirExists() { return await fs.exists(this.local_workdir) } async pull() { this.chroot.print(`Pulling updates for ${this.name}`, 'magenta') await exec('git pull', { workdir: module.local_workdir }) } async hasUncommitedChanges() { try { await exec('git diff-index --quiet HEAD --', { workdir: this.local_workdir }) return false } catch (error) { return true } } async configure() { this.chroot.print(`Configuring ${this.name}`, 'blue') if (!(await this.buildDirExists())) { await fs.mkdir(this.local_workdir) } await this.execTarget('configure') } async build() { if (!(await this.buildDirExists())) { this.chroot.print(`Configuring ${this.name}`, 'blue') await fs.mkdir(this.local_workdir) await this.execTarget('configure') } this.chroot.print(`Building ${this.name}`, 'blue') await this.execTarget('build') } async test() { if (!this.hasTarget('test')) return await this.build() this.chroot.print(`Testing ${this.name}`, 'blue') await this.execTarget('test', {prefix: 'xvfb-run -a -s "-screen 0 800x600x24"'}) } async run() { if (!this.hasTarget('run')) return const user = await username() await this.build() this.chroot.print(`Running ${this.name}`, 'blue') await this.execTarget('run', {user: user}) } async execTarget(target, { prefix, user } = {}) { if (!this.hasTarget(target)) return const steps = this.config[target] instanceof Array ? this.config[target] : [this.config[target]] for (let step of steps) { this.chroot.print(`+ ${step}`, 'grey', {bold: false}) step = step.replace('${srcdir}', '..') if (prefix) step = `${prefix} ${step}` await this.chroot.exec(step, { workdir: this.workdir, user: user }) } } } <file_sep>#! /usr/bin/env node require('colors') var Box = require('../lib').Box var args = require('yargs') .usage('Usage: $0 command [args]') .demand(1) .help('h') .alias('h', 'help') .argv var box = new Box('papyros') .mount('/home/mspencer/Developer', '/developer') box.root = '/developer/hawaiios' var command = args._[0] var arg = args._.length > 1 ? args._[1] : undefined if (command == 'install') box.installDependencies() else if (command == 'pull') box.pull(arg) else if (command == 'status') box.status(arg) else if (command == 'build') box.build(arg) else if (command == 'test') box.test(arg) else if (command == 'run') box.run(arg) else if (command == 'configure') box.configure(arg) else if (command == 'shell') box.shell() <file_sep>import {spawn} from 'child_process' export class Chroot { constructor(workdir) { this.workdir = workdir || process.cwd() this.binds = [] this.setenvs = [] } mount(source, dest) { const bind = dest ? `${source}:${dest}` : source this.binds.push(bind) return this } setenv(name, value) { const env = value ? `${name}=${value}` : name this.setenvs.push(env) return this } async create(packages) { await pacstrap(this.workdir, packages) } async installPackages(packages) { if (packages.join) packages = packages.join(' ') await this.exec(`pacman -S --noconfirm ${packages}`) } async exec(command, { workdir, user } = {}) { await systemd_nspawn(this.workdir, command, { workdir: workdir, user: user, binds: this.binds, setenvs: this.setenvs }) } } async function pacstrap(workdir, packages) { await exec(['pacstrap', '-cd', workdir, 'base', 'base-devel'] + packages) } async function systemd_nspawn(chrootPath, command, { workdir, user, binds = [], setenvs = [] } = {}) { let args = [] if (workdir) args.push(`--chdir=${workdir}`) if (user) args.push(`--user=${user}`) args = args.concat(binds.map(bind => `--bind=${bind}`)) args = args.concat(setenvs.map(setenv => `--setenv=${setenv}`)) await exec(`sudo systemd-nspawn -D ${chrootPath} --quiet --as-pid2 ${args.join(' ')} ${command}`) } export async function exec(command, { workdir } = {}) { return new Promise((resolve, reject) => { const child = spawn(command, { cwd: workdir, stdio: 'inherit', shell: true }) child.on('exit', (code) => { if (code === 0) resolve() else reject() }) child.on('error', (error) => { reject(error) }) }) }
4c67fd286982fc36e14415228e173e2507a2411a
[ "JavaScript" ]
4
JavaScript
iBelieve/box
6d5d4d885d048c19e9bbf94cbf230694a215bf38
345d8705385c193fc807adeb6821c27a3458fa4b
refs/heads/master
<repo_name>sammath/pachyderm<file_sep>/src/pps/pipelineserver/pipelineserver.go package pipelineserver import ( "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pps" "github.com/pachyderm/pachyderm/src/pps/persist" ) type APIServer interface { pps.PipelineAPIServer Start() error } func NewAPIServer( pfsAPIClient pfs.APIClient, jobAPIClient pps.JobAPIClient, persistAPIServer persist.APIServer, ) APIServer { return newAPIServer( pfsAPIClient, jobAPIClient, persistAPIServer, ) } <file_sep>/src/cmd/pfs-roler/main.go package main import ( "errors" "fmt" "os" "go.pedge.io/env" "github.com/pachyderm/pachyderm/src/pkg/discovery" "github.com/pachyderm/pachyderm/src/pkg/shard" ) type appEnv struct { NumShards uint64 `env:"PFS_NUM_SHARDS,default=16"` NumReplicas uint64 `env:"PFS_NUM_REPLICAS"` } func main() { env.Main(do, &appEnv{}) } func do(appEnvObj interface{}) error { appEnv := appEnvObj.(*appEnv) discoveryClient, err := getEtcdClient() if err != nil { return err } sharder := shard.NewSharder( discoveryClient, appEnv.NumShards, appEnv.NumReplicas, "namespace", ) return sharder.AssignRoles(nil) } func getEtcdClient() (discovery.Client, error) { etcdAddress, err := getEtcdAddress() if err != nil { return nil, err } return discovery.NewEtcdClient(etcdAddress), nil } func getEtcdAddress() (string, error) { etcdAddr := os.Getenv("ETCD_PORT_2379_TCP_ADDR") if etcdAddr == "" { return "", errors.New("ETCD_PORT_2379_TCP_ADDR not set") } return fmt.Sprintf("http://%s:2379", etcdAddr), nil } <file_sep>/src/pfs/route/sharder.go package route import ( "hash/adler32" "path" "github.com/pachyderm/pachyderm/src/pfs" ) type sharder struct { fileModulus uint64 blockModulus uint64 } func newSharder(fileModulus uint64, blockModulus uint64) *sharder { return &sharder{ fileModulus: fileModulus, blockModulus: blockModulus, } } func (s *sharder) FileModulus() uint64 { return s.fileModulus } func (s *sharder) BlockModulus() uint64 { return s.blockModulus } func (s *sharder) GetShard(file *pfs.File) uint64 { return uint64(adler32.Checksum([]byte(path.Clean(file.Path)))) % s.fileModulus } func (s *sharder) GetBlockShard(block *pfs.Block) uint64 { return uint64(adler32.Checksum([]byte(block.Hash))) % s.blockModulus } func FileInShard(shard *pfs.Shard, file *pfs.File) bool { if shard == nil { // this lets us default to no filtering return true } sharder := &sharder{fileModulus: shard.FileModulus} return sharder.GetShard(file) == shard.FileNumber } func BlockInShard(shard *pfs.Shard, block *pfs.Block) bool { if shard == nil { // this lets us default to no filtering return true } sharder := &sharder{blockModulus: shard.BlockModulus} return sharder.GetBlockShard(block) == shard.BlockNumber } <file_sep>/src/cmd/pfsd/main.go package main import ( "errors" "fmt" "os" "github.com/gengo/grpc-gateway/runtime" "github.com/pachyderm/pachyderm" "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pfs/drive" "github.com/pachyderm/pachyderm/src/pfs/route" "github.com/pachyderm/pachyderm/src/pfs/server" "github.com/pachyderm/pachyderm/src/pkg/discovery" "github.com/pachyderm/pachyderm/src/pkg/grpcutil" "github.com/pachyderm/pachyderm/src/pkg/netutil" "github.com/pachyderm/pachyderm/src/pkg/shard" "go.pedge.io/env" "go.pedge.io/lion/proto" "go.pedge.io/pkg/http" "go.pedge.io/proto/server" "golang.org/x/net/context" "google.golang.org/grpc" ) type appEnv struct { NumShards uint64 `env:"PFS_NUM_SHARDS,default=16"` Address string `env:"PFS_ADDRESS"` Port uint16 `env:"PFS_PORT,default=650"` HTTPPort uint16 `env:"PFS_HTTP_PORT,default=750"` EtcdAddress string `env:"ETCD_PORT_2379_TCP_ADDR"` ObjdAddress string `env:"OBJD_PORT_652_TCP_ADDR"` } func main() { env.Main(do, &appEnv{}) } func do(appEnvObj interface{}) error { appEnv := appEnvObj.(*appEnv) discoveryClient, err := getEtcdClient(appEnv) if err != nil { return err } address := appEnv.Address if address == "" { address, err = netutil.ExternalIP() if err != nil { return err } } address = fmt.Sprintf("%s:%d", address, appEnv.Port) sharder := shard.NewSharder( discoveryClient, appEnv.NumShards, 0, "namespace", ) objdAddress, err := getObjdAddress(appEnv) if err != nil { return err } clientConn, err := grpc.Dial(objdAddress, grpc.WithInsecure()) if err != nil { return err } objAPIClient := pfs.NewBlockAPIClient(clientConn) driver, err := drive.NewDriver(objAPIClient) if err != nil { return err } apiServer := server.NewAPIServer( route.NewSharder( appEnv.NumShards, 1, ), route.NewRouter( sharder, grpcutil.NewDialer( grpc.WithInsecure(), ), address, ), ) go func() { if err := sharder.RegisterFrontend(nil, address, apiServer); err != nil { protolion.Printf("Error from sharder.RegisterFrontend %s", err.Error()) } }() internalAPIServer := server.NewInternalAPIServer( route.NewSharder( appEnv.NumShards, 1, ), route.NewRouter( sharder, grpcutil.NewDialer( grpc.WithInsecure(), ), address, ), driver, ) go func() { if err := sharder.Register(nil, address, internalAPIServer); err != nil { protolion.Printf("Error from sharder.Register %s", err.Error()) } }() return protoserver.ServeWithHTTP( func(s *grpc.Server) { pfs.RegisterAPIServer(s, apiServer) pfs.RegisterInternalAPIServer(s, internalAPIServer) }, func(ctx context.Context, mux *runtime.ServeMux, clientConn *grpc.ClientConn) error { return pfs.RegisterAPIHandler(ctx, mux, clientConn) }, protoserver.ServeWithHTTPOptions{ ServeOptions: protoserver.ServeOptions{ Version: pachyderm.Version, }, }, protoserver.ServeEnv{ GRPCPort: appEnv.Port, }, pkghttp.HandlerEnv{ Port: appEnv.HTTPPort, }, ) } func getEtcdClient(env *appEnv) (discovery.Client, error) { etcdAddress, err := getEtcdAddress(env) if err != nil { return nil, err } return discovery.NewEtcdClient(etcdAddress), nil } func getEtcdAddress(env *appEnv) (string, error) { if env.EtcdAddress == "" { return "", errors.New("ETCD_PORT_2379_TCP_ADDR not set") } return fmt.Sprintf("http://%s:2379", env.EtcdAddress), nil } func getObjdAddress(env *appEnv) (string, error) { objdAddr := os.Getenv("OBJD_PORT_652_TCP_ADDR") if objdAddr == "" { return "", errors.New("OBJD_PORT_652_TCP_ADDR not set") } return fmt.Sprintf("%s:652", objdAddr), nil } <file_sep>/src/cmd/ppsd/main.go package main import ( "fmt" "github.com/pachyderm/pachyderm" "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pps" "github.com/pachyderm/pachyderm/src/pps/jobserver" "github.com/pachyderm/pachyderm/src/pps/persist" persistserver "github.com/pachyderm/pachyderm/src/pps/persist/server" "github.com/pachyderm/pachyderm/src/pps/pipelineserver" "go.pedge.io/env" "go.pedge.io/lion/proto" "go.pedge.io/proto/server" "google.golang.org/grpc" kube "k8s.io/kubernetes/pkg/client/unversioned" ) type appEnv struct { Port uint16 `env:"PPS_PORT,default=651"` DatabaseAddress string `env:"RETHINK_PORT_28015_TCP_ADDR,required"` DatabaseName string `env:"PPS_DATABASE_NAME,default=pachyderm"` PfsdAddress string `env:"PFSD_PORT_650_TCP_ADDR,required"` KubeAddress string `env:"KUBERNETES_PORT_443_TCP_ADDR,required"` } func main() { env.Main(do, &appEnv{}) } func do(appEnvObj interface{}) error { appEnv := appEnvObj.(*appEnv) rethinkAPIServer, err := getRethinkAPIServer(appEnv) if err != nil { return err } pfsdAddress := getPfsdAddress(appEnv) clientConn, err := grpc.Dial(pfsdAddress, grpc.WithInsecure()) if err != nil { return err } pfsAPIClient := pfs.NewAPIClient(clientConn) kubeClient, err := getKubeClient(appEnv) if err != nil { return err } jobAPIServer := jobserver.NewAPIServer( pfsAPIClient, rethinkAPIServer, kubeClient, ) jobAPIClient := pps.NewLocalJobAPIClient(jobAPIServer) pipelineAPIServer := pipelineserver.NewAPIServer(pfsAPIClient, jobAPIClient, rethinkAPIServer) if err := pipelineAPIServer.Start(); err != nil { return err } return protoserver.Serve( func(s *grpc.Server) { pps.RegisterJobAPIServer(s, jobAPIServer) pps.RegisterInternalJobAPIServer(s, jobAPIServer) pps.RegisterPipelineAPIServer(s, pipelineAPIServer) }, protoserver.ServeOptions{ Version: pachyderm.Version, }, protoserver.ServeEnv{ GRPCPort: appEnv.Port, }, ) } func getRethinkAPIServer(env *appEnv) (persist.APIServer, error) { if err := persistserver.InitDBs(getRethinkAddress(env), env.DatabaseName); err != nil { return nil, err } return persistserver.NewRethinkAPIServer(getRethinkAddress(env), env.DatabaseName) } func getRethinkAddress(env *appEnv) string { return fmt.Sprintf("%s:28015", env.DatabaseAddress) } func getPfsdAddress(env *appEnv) string { return fmt.Sprintf("%s:650", env.PfsdAddress) } func getKubeAddress(env *appEnv) string { return fmt.Sprintf("%s:443", env.KubeAddress) } func getKubeClient(env *appEnv) (*kube.Client, error) { kubeClient, err := kube.NewInCluster() if err != nil { protolion.Errorf("Falling back to insecure kube client due to error from NewInCluster: %s", err.Error()) } else { return kubeClient, err } config := &kube.Config{ Host: getKubeAddress(env), Insecure: true, } return kube.New(config) } <file_sep>/src/cmd/pachctl/main.go package main import ( "fmt" "os" "github.com/pachyderm/pachyderm/src/cmd/pachctl/cmd" "go.pedge.io/env" ) type appEnv struct { PfsAddress string `env:"PFS_ADDRESS,default=0.0.0.0:650"` PpsAddress string `env:"PPS_ADDRESS,default=0.0.0.0:651"` } func main() { env.Main(do, &appEnv{}) } func do(appEnvObj interface{}) error { appEnv := appEnvObj.(*appEnv) pfsdAddress := getPfsdAddress(appEnv) ppsdAddress := getPpsdAddress(appEnv) rootCmd, err := cmd.PachctlCmd(pfsdAddress, ppsdAddress) if err != nil { return err } return rootCmd.Execute() } func getPfsdAddress(appEnv *appEnv) string { if pfsdAddr := os.Getenv("PFSD_PORT_650_TCP_ADDR"); pfsdAddr != "" { return fmt.Sprintf("%s:650", pfsdAddr) } return appEnv.PfsAddress } func getPpsdAddress(appEnv *appEnv) string { if ppsdAddr := os.Getenv("PPSD_PORT_651_TCP_ADDR"); ppsdAddr != "" { return fmt.Sprintf("%s:651", ppsdAddr) } return appEnv.PpsAddress } <file_sep>/src/pps/pps.go package pps import ( "google.golang.org/grpc" ) func NewLocalJobAPIClient(jobAPIServer JobAPIServer) JobAPIClient { return newLocalJobAPIClient(jobAPIServer) } func NewLocalPipelineAPIClient(pipelineAPIServer PipelineAPIServer) PipelineAPIClient { return newLocalPipelineAPIClient(pipelineAPIServer) } type APIClient interface { JobAPIClient InternalJobAPIClient PipelineAPIClient } func NewAPIClient(clientConn *grpc.ClientConn) APIClient { return newAPIClient(clientConn) } <file_sep>/src/cmd/job-shim/main.go package main import ( "fmt" "os" "strings" "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pfs/fuse" "github.com/pachyderm/pachyderm/src/pps" "github.com/spf13/cobra" "go.pedge.io/env" "go.pedge.io/lion" "go.pedge.io/pkg/exec" "golang.org/x/net/context" "google.golang.org/grpc" ) type appEnv struct { PachydermPfsd1Port string `env:"PACHYDERM_PFSD_1_PORT"` PfsAddress string `env:"PFS_ADDRESS,default=0.0.0.0:650"` PachydermPpsd1Port string `env:"PACHYDERM_PPSD_1_PORT"` PpsAddress string `env:"PPS_ADDRESS,default=0.0.0.0:651"` } func main() { env.Main(do, &appEnv{}) } func do(appEnvObj interface{}) error { lion.SetLevel(lion.LevelDebug) appEnv := appEnvObj.(*appEnv) rootCmd := &cobra.Command{ Use: os.Args[0] + " job-id", Short: `Pachyderm job-shim, coordinates with ppsd to create an output commit and run user work.`, Long: `Pachyderm job-shim, coordinates with ppsd to create an output commit and run user work.`, Run: func(cmd *cobra.Command, args []string) { pfsAPIClient, err := getPfsAPIClient(getPfsdAddress(appEnv)) if err != nil { errorAndExit(err.Error()) } ppsAPIClient, err := getPpsAPIClient(getPpsdAddress(appEnv)) if err != nil { errorAndExit(err.Error()) } response, err := ppsAPIClient.StartJob( context.Background(), &pps.StartJobRequest{ Job: &pps.Job{ Id: args[0], }}) if err != nil { fmt.Fprintf(os.Stderr, "%s\n", err.Error()) os.Exit(0) } mounter := fuse.NewMounter(getPfsdAddress(appEnv), pfsAPIClient) ready := make(chan bool) go func() { if err := mounter.Mount( "/pfs", nil, response.CommitMounts, ready, ); err != nil { errorAndExit(err.Error()) } }() <-ready defer func() { if err := mounter.Unmount("/pfs"); err != nil { errorAndExit(err.Error()) } }() io := pkgexec.IO{ Stdin: strings.NewReader(response.Transform.Stdin), Stdout: os.Stdout, Stderr: os.Stderr, } success := true if err := pkgexec.RunIO(io, response.Transform.Cmd...); err != nil { fmt.Fprintf(os.Stderr, "%s\n", err.Error()) success = false } if _, err := ppsAPIClient.FinishJob( context.Background(), &pps.FinishJobRequest{ Job: &pps.Job{ Id: args[0], }, Index: response.Index, Success: success, }, ); err != nil { errorAndExit(err.Error()) } }, } return rootCmd.Execute() } func getPfsdAddress(appEnv *appEnv) string { if pfsdAddr := os.Getenv("PFSD_PORT_650_TCP_ADDR"); pfsdAddr != "" { return fmt.Sprintf("%s:650", pfsdAddr) } if appEnv.PachydermPfsd1Port != "" { return strings.Replace(appEnv.PachydermPfsd1Port, "tcp://", "", -1) } return appEnv.PfsAddress } func getPpsdAddress(appEnv *appEnv) string { if ppsdAddr := os.Getenv("PPSD_PORT_651_TCP_ADDR"); ppsdAddr != "" { return fmt.Sprintf("%s:651", ppsdAddr) } if appEnv.PachydermPpsd1Port != "" { return strings.Replace(appEnv.PachydermPpsd1Port, "tcp://", "", -1) } return appEnv.PpsAddress } func getPfsAPIClient(address string) (pfs.APIClient, error) { clientConn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { return nil, err } return pfs.NewAPIClient(clientConn), nil } func getPpsAPIClient(address string) (pps.APIClient, error) { clientConn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { return nil, err } return pps.NewAPIClient(clientConn), nil } func errorAndExit(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, "%s\n", fmt.Sprintf(format, args...)) os.Exit(1) } <file_sep>/src/pfs/server/server.go package server import ( "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pfs/drive" "github.com/pachyderm/pachyderm/src/pfs/route" "github.com/pachyderm/pachyderm/src/pkg/obj" "github.com/pachyderm/pachyderm/src/pkg/shard" ) var ( blockSize = 8 * 1024 * 1024 // 8 Megabytes ) type APIServer interface { pfs.APIServer shard.Frontend } type InternalAPIServer interface { pfs.InternalAPIServer shard.Server } // NewAPIServer returns a new APIServer. func NewAPIServer( sharder route.Sharder, router route.Router, ) APIServer { return newAPIServer( sharder, router, ) } // NewInternalAPIServer returns a new InternalAPIServer. func NewInternalAPIServer( sharder route.Sharder, router route.Router, driver drive.Driver, ) InternalAPIServer { return newInternalAPIServer( sharder, router, driver, ) } func NewLocalBlockAPIServer(dir string) (pfs.BlockAPIServer, error) { return newLocalBlockAPIServer(dir) } func NewObjBlockAPIServer(dir string, objClient obj.Client) (pfs.BlockAPIServer, error) { return newObjBlockAPIServer(dir, objClient) } <file_sep>/src/pkg/shard/shard.go package shard import ( "github.com/pachyderm/pachyderm/src/pkg/discovery" ) // Sharder distributes shards between a set of servers. type Sharder interface { GetMasterAddress(shard uint64, version int64) (string, bool, error) GetReplicaAddresses(shard uint64, version int64) (map[string]bool, error) GetShardToMasterAddress(version int64) (map[uint64]string, error) GetShardToReplicaAddresses(version int64) (map[uint64]map[string]bool, error) Register(cancel chan bool, address string, server Server) error RegisterFrontend(cancel chan bool, address string, frontend Frontend) error AssignRoles(chan bool) error } type TestSharder interface { Sharder WaitForAvailability(frontendIds []string, serverIds []string) error } func NewSharder(discoveryClient discovery.Client, numShards uint64, numReplicas uint64, namespace string) Sharder { return newSharder(discoveryClient, numShards, numReplicas, namespace) } func NewTestSharder(discoveryClient discovery.Client, numShards uint64, numReplicas uint64, namespace string) TestSharder { return newSharder(discoveryClient, numShards, numReplicas, namespace) } type Server interface { // AddShard tells the server it now has a role for a shard. AddShard(shard uint64, version int64) error // RemoveShard tells the server it no longer has a role for a shard. RemoveShard(shard uint64, version int64) error // LocalRoles asks the server which shards it has on disk and how many commits each shard has. LocalShards() (map[uint64]bool, error) } type Frontend interface { // Version tells the Frontend a new version exists. // Version should block until the Frontend is done using the previous version. Version(version int64) error } <file_sep>/Makefile #### VARIABLES # RUNARGS: arguments for run # DOCKER_OPTS: docker-compose options for run, test, launch-* # TESTPKGS: packages for test, default ./src/... # TESTFLAGS: flags for test # VENDOR_ALL: do not ignore some vendors when updating vendor directory # VENDOR_IGNORE_DIRS: ignore vendor dirs # KUBECTLFLAGS: flags for kubectl #### ifndef TESTPKGS TESTPKGS = ./src/... endif ifndef VENDOR_IGNORE_DIRS VENDOR_IGNORE_DIRS = go.pedge.io endif ifdef VENDOR_ALL VENDOR_IGNORE_DIRS = endif all: build version: @echo 'package main; import "fmt"; import "github.com/pachyderm/pachyderm"; func main() { fmt.Println(pachyderm.Version.VersionString()) }' > /tmp/pachyderm_version.go @go run /tmp/pachyderm_version.go deps: GO15VENDOREXPERIMENT=0 go get -d -v ./src/... ./. update-deps: GO15VENDOREXPERIMENT=0 go get -d -v -u -f ./src/... ./. test-deps: GO15VENDOREXPERIMENT=0 go get -d -v -t ./src/... ./. update-test-deps: GO15VENDOREXPERIMENT=0 go get -d -v -t -u -f ./src/... ./. vendor-update: CGO_ENABLED=1 GOOS=linux GOARCH=amd64 GO15VENDOREXPERIMENT=0 go get -d -v -t -u -f ./src/... ./. vendor-without-update: go get -v github.com/kardianos/govendor rm -rf vendor govendor init CGO_ENABLED=1 GOOS=linux GOARCH=amd64 govendor add +external CGO_ENABLED=1 GOOS=linux GOARCH=amd64 govendor update +vendor $(foreach vendor_dir, $(VENDOR_IGNORE_DIRS), rm -rf vendor/$(vendor_dir) || exit; git checkout vendor/$(vendor_dir) || exit;) vendor: vendor-update vendor-without-update build: GO15VENDOREXPERIMENT=1 go build ./src/... ./. install: GO15VENDOREXPERIMENT=1 go install ./src/cmd/pachctl ./src/cmd/pachctl-doc docker-build-test: docker-compose build test docker tag -f pachyderm_test:latest pachyderm/test:latest mkdir -p /tmp/pachyderm-test docker-build-compile: docker-compose build compile docker-build-pfs-roler: docker-build-compile docker-compose run --rm compile sh etc/compile/compile.sh pfs-roler docker-build-pfsd: docker-build-compile docker-compose run --rm compile sh etc/compile/compile.sh pfsd docker-build-ppsd: docker-build-compile docker-compose run --rm compile sh etc/compile/compile.sh ppsd docker-build-objd: docker-build-compile docker-compose run --rm compile sh etc/compile/compile.sh objd docker-build-job-shim: docker-build-compile docker-compose run --rm compile sh etc/compile/compile.sh job-shim docker-build: docker-build-test docker-build-pfs-roler docker-build-pfsd docker-build-ppsd docker-build-objd docker-build-job-shim docker-push-test: docker-build-test docker push pachyderm/test docker-push-pfs-roler: docker-build-pfs-roler docker push pachyderm/pfs-roler docker-push-pfsd: docker-build-pfsd docker push pachyderm/pfsd docker-push-ppsd: docker-build-ppsd docker push pachyderm/ppsd docker-push-objd: docker-build-objd docker push pachyderm/objd docker-push-job-shim: docker-build-job-shim docker push pachyderm/job-shim docker-push: docker-push-pfs-roler docker-push-ppsd docker-push-objd docker-push-pfsd docker-push-job-shim run: docker-build-test docker-compose run --rm $(DOCKER_OPTS) test $(RUNARGS) launch-kube: etc/kube/start-kube-docker.sh clean-launch-kube: docker kill $$(docker ps -q) kube-cluster-assets: install pachctl manifest -s 32 >etc/kube/pachyderm.json launch: install kubectl $(KUBECTLFLAGS) create -f etc/kube/pachyderm.json until pachctl version 2>/dev/null >/dev/null; do sleep 5; done launch-dev: launch-kube launch clean-job: clean-launch: kubectl $(KUBECTLFLAGS) delete --ignore-not-found job -l suite=pachyderm kubectl $(KUBECTLFLAGS) delete --ignore-not-found all -l suite=pachyderm kubectl $(KUBECTLFLAGS) delete --ignore-not-found serviceaccount -l suite=pachyderm kubectl $(KUBECTLFLAGS) delete --ignore-not-found secret -l suite=pachyderm run-integration-test: kubectl $(KUBECTLFLAGS) delete --ignore-not-found -f etc/kube/test-pod.yml kubectl $(KUBECTLFLAGS) create -f etc/kube/test-pod.yml integration-test: launch run-integration-test proto: go get -v go.pedge.io/protoeasy/cmd/protoeasy protoeasy --grpc --grpc-gateway --go --go-import-path github.com/pachyderm/pachyderm/src src pretest: go get -v github.com/kisielk/errcheck go get -v github.com/golang/lint/golint for file in $$(find "./src" -name '*.go' | grep -v '\.pb\.go' | grep -v '\.pb\.gw\.go'); do \ golint $$file | grep -v unexported; \ if [ -n "$$(golint $$file | grep -v unexported)" ]; then \ exit 1; \ fi; \ done; go vet -n ./src/... | while read line; do \ modified=$$(echo $$line | sed "s/ [a-z0-9_/]*\.pb\.gw\.go//g"); \ $$modified; \ if [ -n "$$($$modified)" ]; then \ exit 1; \ fi; \ done #errcheck $$(go list ./src/... | grep -v src/cmd/ppsd | grep -v src/pfs$$ | grep -v src/pps$$) docker-clean-test: docker-compose kill rethink docker-compose rm -f rethink docker-compose kill etcd docker-compose rm -f etcd docker-clean-launch: docker-clean-test docker-compose kill pfs-roler docker-compose rm -f pfs-roler docker-compose kill pfsd docker-compose rm -f pfsd docker-compose kill ppsd docker-compose rm -f ppsd go-test: docker-clean-test docker-build-test docker-compose run --rm $(DOCKER_OPTS) test sh -c "go test -test.short $(TESTFLAGS) $(TESTPKGS)" go-test-long: docker-clean-test docker-build-test docker-compose run --rm $(DOCKER_OPTS) test sh -c "go test $(TESTFLAGS) $(TESTPKGS)" test: pretest go-test docker-clean-test test-long: pretest go-test-long docker-clean-test clean: docker-clean-launch clean-launch clean-launch-kube go clean ./src/... ./. rm -f src/cmd/pfs/pfs-roler rm -f src/cmd/pfsd/pfsd rm -f src/cmd/ppsd/ppsd rm -f src/cmd/objd/objd doc: install # we rename to pachctl because the program name is used in generating docs cp $(GOPATH)/bin/pachctl-doc ./pachctl rm -rf doc/pachctl && mkdir doc/pachctl ./pachctl rm ./pachctl .PHONY: \ doc \ all \ version \ deps \ update-deps \ test-deps \ update-test-deps \ vendor-update \ vendor-without-update \ vendor \ build \ install \ docker-build-test \ docker-build-compile \ docker-build-pfs-roler \ docker-build-pfsd \ docker-build-ppsd \ docker-build \ docker-push-pfs-roler \ docker-push-pfsd \ docker-push-ppsd \ docker-push \ run \ launch \ proto \ pretest \ docker-clean-test \ docker-clean-launch \ go-test \ go-test-long \ test \ test-long \ clean <file_sep>/src/pfs/route/route_test.go package route import ( "errors" "fmt" "os" "sync" "testing" "time" "github.com/pachyderm/pachyderm/src/pkg/discovery" "github.com/pachyderm/pachyderm/src/pkg/require" "github.com/pachyderm/pachyderm/src/pkg/shard" ) const ( testNumShards = 64 testNumServers = 8 testNumReplicas = 3 ) func TestMasterOnly(t *testing.T) { client, err := getEtcdClient() require.NoError(t, err) runMasterOnlyTest(t, client) } func TestMasterReplica(t *testing.T) { client, err := getEtcdClient() require.NoError(t, err) runMasterReplicaTest(t, client) } type server struct { shards map[uint64]bool lock sync.Mutex t *testing.T } func (s *server) AddShard(shard uint64, version int64) error { s.lock.Lock() defer s.lock.Unlock() s.shards[shard] = true return nil } func (s *server) RemoveShard(shard uint64, version int64) error { s.lock.Lock() defer s.lock.Unlock() delete(s.shards, shard) return nil } func (s *server) LocalShards() (map[uint64]bool, error) { return nil, nil } func newServer(t *testing.T) *server { return &server{make(map[uint64]bool), sync.Mutex{}, t} } type frontend struct { version int64 } func (f *frontend) Version(version int64) error { f.version = version return nil } func newFrontend(t *testing.T) *frontend { return &frontend{shard.InvalidVersion} } type serverGroup struct { servers []*server frontends []*frontend cancel chan bool sharder shard.Sharder offset int } func NewServerGroup(t *testing.T, sharder shard.Sharder, numServers int, offset int) *serverGroup { serverGroup := serverGroup{cancel: make(chan bool), sharder: sharder, offset: offset} for i := 0; i < numServers; i++ { serverGroup.servers = append(serverGroup.servers, newServer(t)) } return &serverGroup } func (s *serverGroup) run(t *testing.T) { var wg sync.WaitGroup defer wg.Wait() for i, server := range s.servers { wg.Add(1) i := i server := server go func() { defer wg.Done() require.Equal( t, shard.ErrCancelled, s.sharder.Register(s.cancel, fmt.Sprintf("address-%d", i+s.offset), server), ) }() } for i, frontend := range s.frontends { wg.Add(1) i := i frontend := frontend go func() { defer wg.Done() require.Equal( t, shard.ErrCancelled, s.sharder.RegisterFrontend(s.cancel, fmt.Sprintf("address-%d", i+s.offset), frontend), ) }() } } func (s *serverGroup) satisfied(shardsLen int) bool { result := true for _, server := range s.servers { if len(server.shards) != shardsLen { result = false } } return result } func runMasterOnlyTest(t *testing.T, client discovery.Client) { sharder := shard.NewSharder(client, testNumShards, 0, "TestMasterOnly") cancel := make(chan bool) go func() { require.Equal(t, shard.ErrCancelled, sharder.AssignRoles(cancel)) }() defer func() { close(cancel) }() serverGroup1 := NewServerGroup(t, sharder, testNumServers/2, 0) go serverGroup1.run(t) start := time.Now() for !serverGroup1.satisfied(testNumShards / (testNumServers / 2)) { time.Sleep(500 * time.Millisecond) if time.Since(start) > time.Second*time.Duration(30) { t.Fatal("test timed out") } } serverGroup2 := NewServerGroup(t, sharder, testNumServers/2, testNumServers/2) go serverGroup2.run(t) start = time.Now() for !serverGroup1.satisfied(testNumShards/testNumServers) || !serverGroup2.satisfied(testNumShards/testNumServers) { time.Sleep(500 * time.Millisecond) if time.Since(start) > time.Second*time.Duration(30) { t.Fatal("test timed out") } } close(serverGroup1.cancel) start = time.Now() for !serverGroup2.satisfied(testNumShards / (testNumServers / 2)) { time.Sleep(500 * time.Millisecond) if time.Since(start) > time.Second*time.Duration(60) { t.Fatal("test timed out") } } } func runMasterReplicaTest(t *testing.T, client discovery.Client) { sharder := shard.NewSharder(client, testNumShards, testNumReplicas, "TestMasterReplica") cancel := make(chan bool) go func() { require.Equal(t, shard.ErrCancelled, sharder.AssignRoles(cancel)) }() defer func() { close(cancel) }() serverGroup1 := NewServerGroup(t, sharder, testNumServers/2, 0) go serverGroup1.run(t) start := time.Now() for !serverGroup1.satisfied((testNumShards * (testNumReplicas + 1)) / (testNumServers / 2)) { time.Sleep(500 * time.Millisecond) if time.Since(start) > time.Second*time.Duration(30) { t.Fatal("test timed out") } } serverGroup2 := NewServerGroup(t, sharder, testNumServers/2, testNumServers/2) go serverGroup2.run(t) start = time.Now() for !serverGroup1.satisfied((testNumShards*(testNumReplicas+1))/testNumServers) || !serverGroup2.satisfied((testNumShards*(testNumReplicas+1))/testNumServers) { time.Sleep(time.Second) if time.Since(start) > time.Second*time.Duration(60) { t.Fatal("test timed out") } } close(serverGroup1.cancel) for !serverGroup2.satisfied((testNumShards * (testNumReplicas + 1)) / (testNumServers / 2)) { time.Sleep(500 * time.Millisecond) if time.Since(start) > time.Second*time.Duration(60) { t.Fatal("test timed out") } } } func getEtcdClient() (discovery.Client, error) { etcdAddress, err := getEtcdAddress() if err != nil { return nil, err } return discovery.NewEtcdClient(etcdAddress), nil } func getEtcdAddress() (string, error) { etcdAddr := os.Getenv("ETCD_PORT_2379_TCP_ADDR") if etcdAddr == "" { return "", errors.New("ETCD_PORT_2379_TCP_ADDR not set") } return fmt.Sprintf("http://%s:2379", etcdAddr), nil } <file_sep>/src/pfs/route/route.go package route import ( "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pkg/grpcutil" "github.com/pachyderm/pachyderm/src/pkg/shard" "google.golang.org/grpc" ) type Sharder interface { FileModulus() uint64 BlockModulus() uint64 GetShard(file *pfs.File) uint64 GetBlockShard(block *pfs.Block) uint64 } func NewSharder(fileModulus uint64, blockModulus uint64) Sharder { return newSharder(fileModulus, blockModulus) } type Router interface { GetMasterShards(version int64) (map[uint64]bool, error) GetReplicaShards(version int64) (map[uint64]bool, error) GetAllShards(version int64) (map[uint64]bool, error) GetMasterClientConn(shard uint64, version int64) (*grpc.ClientConn, error) GetMasterOrReplicaClientConn(shard uint64, version int64) (*grpc.ClientConn, error) GetReplicaClientConns(shard uint64, version int64) ([]*grpc.ClientConn, error) GetAllClientConns(version int64) ([]*grpc.ClientConn, error) } func NewRouter( sharder shard.Sharder, dialer grpcutil.Dialer, localAddress string, ) Router { return newRouter( sharder, dialer, localAddress, ) } <file_sep>/src/pfs/route/router.go package route import ( "fmt" "github.com/pachyderm/pachyderm/src/pkg/grpcutil" "github.com/pachyderm/pachyderm/src/pkg/shard" "google.golang.org/grpc" ) type router struct { sharder shard.Sharder dialer grpcutil.Dialer localAddress string } func newRouter( sharder shard.Sharder, dialer grpcutil.Dialer, localAddress string, ) *router { return &router{ sharder, dialer, localAddress, } } func (r *router) GetMasterShards(version int64) (map[uint64]bool, error) { shardToMasterAddress, err := r.sharder.GetShardToMasterAddress(version) if err != nil { return nil, err } result := make(map[uint64]bool) for shard, address := range shardToMasterAddress { if address == r.localAddress { result[shard] = true } } return result, nil } func (r *router) GetReplicaShards(version int64) (map[uint64]bool, error) { shardToReplicaAddresses, err := r.sharder.GetShardToReplicaAddresses(version) if err != nil { return nil, err } result := make(map[uint64]bool) for shard, addresses := range shardToReplicaAddresses { for address := range addresses { if address == r.localAddress { result[shard] = true } } } return result, nil } func (r *router) GetAllShards(version int64) (map[uint64]bool, error) { shardToMasterAddress, err := r.sharder.GetShardToMasterAddress(version) if err != nil { return nil, err } shardToReplicaAddresses, err := r.sharder.GetShardToReplicaAddresses(version) if err != nil { return nil, err } result := make(map[uint64]bool) for shard, address := range shardToMasterAddress { if address == r.localAddress { result[shard] = true } } for shard, addresses := range shardToReplicaAddresses { for address := range addresses { if address == r.localAddress { result[shard] = true } } } return result, nil } func (r *router) GetMasterClientConn(shard uint64, version int64) (*grpc.ClientConn, error) { address, ok, err := r.sharder.GetMasterAddress(shard, version) if err != nil { return nil, err } if !ok { return nil, fmt.Errorf("no master found for %d", shard) } return r.dialer.Dial(address) } func (r *router) GetMasterOrReplicaClientConn(shard uint64, version int64) (*grpc.ClientConn, error) { addresses, err := r.sharder.GetReplicaAddresses(shard, version) if err != nil { return nil, err } for address := range addresses { return r.dialer.Dial(address) } return r.GetMasterClientConn(shard, version) } func (r *router) GetReplicaClientConns(shard uint64, version int64) ([]*grpc.ClientConn, error) { addresses, err := r.sharder.GetReplicaAddresses(shard, version) if err != nil { return nil, err } var result []*grpc.ClientConn for address := range addresses { conn, err := r.dialer.Dial(address) if err != nil { return nil, err } result = append(result, conn) } return result, nil } func (r *router) GetAllClientConns(version int64) ([]*grpc.ClientConn, error) { addresses, err := r.getAllAddresses(version) if err != nil { return nil, err } var clientConns []*grpc.ClientConn for address := range addresses { // TODO: huge race, this whole thing is bad clientConn, err := r.dialer.Dial(address) if err != nil { return nil, err } clientConns = append(clientConns, clientConn) } return clientConns, nil } func (r *router) getAllAddresses(version int64) (map[string]bool, error) { result := make(map[string]bool) shardToMasterAddress, err := r.sharder.GetShardToMasterAddress(version) if err != nil { return nil, err } for _, address := range shardToMasterAddress { result[address] = true } shardToReplicaAddresses, err := r.sharder.GetShardToReplicaAddresses(version) if err != nil { return nil, err } for _, addresses := range shardToReplicaAddresses { for address := range addresses { result[address] = true } } return result, nil } <file_sep>/src/cmd/objd/main.go package main import ( "io/ioutil" "github.com/pachyderm/pachyderm" "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pfs/server" "github.com/pachyderm/pachyderm/src/pkg/obj" "go.pedge.io/env" "go.pedge.io/lion/proto" "go.pedge.io/proto/server" "google.golang.org/grpc" ) type appEnv struct { StorageRoot string `env:"OBJ_ROOT,required"` Port uint16 `env:"OBJ_PORT,default=652"` } func main() { env.Main(do, &appEnv{}) } func do(appEnvObj interface{}) error { appEnv := appEnvObj.(*appEnv) var blockAPIServer pfs.BlockAPIServer if err := func() error { bucket, err := ioutil.ReadFile("/amazon-secret/bucket") if err != nil { return err } id, err := ioutil.ReadFile("/amazon-secret/id") if err != nil { return err } secret, err := ioutil.ReadFile("/amazon-secret/secret") if err != nil { return err } token, err := ioutil.ReadFile("/amazon-secret/token") if err != nil { return err } region, err := ioutil.ReadFile("/amazon-secret/region") if err != nil { return err } objClient, err := obj.NewAmazonClient(string(bucket), string(id), string(secret), string(token), string(region)) if err != nil { return err } blockAPIServer, err = server.NewObjBlockAPIServer(appEnv.StorageRoot, objClient) if err != nil { return err } return nil }(); err != nil { protolion.Errorf("failed to create obj backend, falling back to local") blockAPIServer, err = server.NewLocalBlockAPIServer(appEnv.StorageRoot) if err != nil { return err } } return protoserver.Serve( func(s *grpc.Server) { pfs.RegisterBlockAPIServer(s, blockAPIServer) }, protoserver.ServeOptions{ Version: pachyderm.Version, }, protoserver.ServeEnv{ GRPCPort: appEnv.Port, }, ) } <file_sep>/src/pps/api_client.go package pps import ( "google.golang.org/grpc" ) type apiClient struct { JobAPIClient InternalJobAPIClient PipelineAPIClient } func newAPIClient(clientConn *grpc.ClientConn) apiClient { return apiClient{ NewJobAPIClient(clientConn), NewInternalJobAPIClient(clientConn), NewPipelineAPIClient(clientConn), } }
bd5e7e23c06bc78eeee25d6fafea2eb4cc095708
[ "Makefile", "Go" ]
16
Go
sammath/pachyderm
a6e234607e5ac4ab5aa1d0c2e4d55e608cc0207e
fc7f27d3a9ce83bfed9e785de5b14cf0defdf76e
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Product; use App\Category; use App\SubCategory; use DB; use Session; use Excel; use File; use App\Http\Resources\ProductListResource; use Illuminate\Http\Request; class ProductController extends Controller { public function index() { ProductListResource::withoutWrapping(); return ProductListResource::collection(Product::all()); } public function import(Request $request){ $this->validate($request, array( 'file' => 'required' )); if($request->hasFile('file')){ $extension = File::extension($request->file->getClientOriginalName()); if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") { $path = $request->file->getRealPath(); $data = Excel::load($path, function($reader) { })->get(); if(!empty($data) && $data->count()){ foreach ($data as $key => $value) { $category = [ 'name' => $value->category, ]; $cat = Category::updateOrCreate($category); $subCategory = [ 'category_id' => $cat->id, 'name' => $value->sub_category, ]; $subcat = SubCategory::updateOrCreate($subCategory); $product[] = [ 'category_id' => $cat->id, 'sub_category_id' => $subcat->id, 'part_number' => $value->part_number, 'description' => $value->description, ]; } if(!empty($product)){ $insertData = DB::table('products')->insert($product); if ($insertData) { Session::flash('success', 'Your Data has successfully imported'); }else { Session::flash('error', 'Error inserting the data..'); return back(); } } } return back(); }else { Session::flash('error', 'File is a '.$extension.' file.!! Please upload a valid xls/csv file..!!'); return back(); } } } } <file_sep><?php namespace App\Http\Resources; use App\Category; use App\SubCategory; use Illuminate\Http\Resources\Json\JsonResource; class ProductListResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'part_number' => $this->part_number, 'description' => $this->description, 'category' => Category::find($this->category_id), 'sub_category' => SubCategory::find($this->sub_category_id), ]; } }
743060e90bee647502d08dae2fbcf9c52485b37b
[ "PHP" ]
2
PHP
pcollinsTech/api-rla
66ad56de2f590b4535d8819e996c180d6955a718
502e0c844e77f669c23b9ba116870b7c8d168607
refs/heads/master
<repo_name>josepazjunior/josepazjunior<file_sep>/README.md "# josepazjunior" <file_sep>/index.php <?php echo "teste 5 junior!"; ?>
20746a89b78f371ee6d4cfc512fa4ca0b8b5230b
[ "Markdown", "PHP" ]
2
Markdown
josepazjunior/josepazjunior
94b2adcaf8b36c9a74e2cb47cc08c116e87dfbea
87d9d750364b268d1d9b276ebbd3113603b6ba4d
refs/heads/main
<file_sep># Copyright (c) 2021, <NAME>. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from torch import Tensor from transformer_transducer.audio_encoder import AudioEncoder from transformer_transducer.label_encoder import LabelEncoder import torch import torch.nn as nn import torch.nn.functional as F class JointNet(nn.Module): def __init__( self, num_vocabs: int, output_size: int = 1024, inner_size: int = 512, ) -> None: super(JointNet, self).__init__() self.fc1 = nn.Linear(output_size, inner_size) self.tanh = nn.Tanh() self.fc2 = nn.Linear(inner_size, num_vocabs) def forward( self, audio_encoder: Tensor, label_encoder: Tensor, ) -> Tensor: if audio_encoder.dim() == 3 and label_encoder.dim() == 3: # Train seq_lens = audio_encoder.size(1) target_lens = label_encoder.size(1) audio_encoder = audio_encoder.unsqueeze(2) label_encoder = label_encoder.unsqueeze(1) audio_encoder = audio_encoder.repeat(1, 1, target_lens, 1) label_encoder = label_encoder.repeat(1, seq_lens, 1, 1) output = torch.cat((audio_encoder, label_encoder), dim=-1) output = self.fc1(output) output = self.tanh(output) output = self.fc2(output) output = F.log_softmax(output, dim=-1) return output class TransformerTransducer(nn.Module): def __init__( self, audio_encoder: AudioEncoder, label_encoder: LabelEncoder, num_vocabs: int, output_size: int = 1024, inner_size: int = 512, ) -> None: super(TransformerTransducer, self).__init__() self.audio_encoder = audio_encoder self.label_encoder = label_encoder self.joint = JointNet(num_vocabs, output_size, inner_size) def forward( self, inputs: Tensor, input_lens: Tensor, targets: Tensor, targets_lens: Tensor, ) -> Tensor: audio_output, audio_output_lens = self.audio_encoder(inputs, input_lens) label_output, label_output_lens = self.label_encoder(targets, targets_lens) output = self.joint(audio_output, label_output) return output @torch.no_grad() def decode(self, audio_outputs: Tensor, max_lens: int) -> Tensor: batch = audio_outputs.size(0) y_hats = list() targets = torch.LongTensor([self.label_encoder.sos_id] * batch) if torch.cuda.is_available(): targets = targets.cuda() for i in range(max_lens): label_output, _ = self.label_encoder(targets, None) label_output = label_output.squeeze(1) audio_output = audio_outputs[:, i, :] output = self.joint(audio_output, label_output) inputs = output.max(1)[1] y_hats.append(inputs) y_hats = torch.stack(y_hats, dim=1) return y_hats # (B, T) @torch.no_grad() def recognize(self, inputs: Tensor, inputs_lens: Tensor) -> Tensor: audio_outputs, audio_output_lens = self.audio_encoder(inputs, inputs_lens) max_lens = audio_outputs.size(1) return self.decode(audio_outputs, max_lens) <file_sep># Transformer-Transducer PyTorch Implementation of [Transformer Transducer](https://arxiv.org/abs/2002.02562) ![b](https://user-images.githubusercontent.com/54731898/108169684-6156ff80-713c-11eb-9469-80820d91c365.PNG) It is an Audio encoder and a Label encoder structure. I appreciate any feedback or contribution. ## Reference - [Transformer Transducer: A Streamable Speech Recognition Model with Transformer Encoders and RNN-T Loss](https://arxiv.org/abs/2002.02562) ## Author - <EMAIL>
e591b4bd1102db8d64b66b8c52d72c7215143509
[ "Markdown", "Python" ]
2
Python
jinggaizi/Transformer-Transducer
a160f14bedcc2cb12cdacbfd7689b26b3909c451
c302a6394c45e411bd6e4a3ac6f135fa60dfc91d
refs/heads/master
<repo_name>PSteinhaus/Liquid-Game<file_sep>/src/HeightMap.cpp #include "main.hpp" #include <stdlib.h> /* rand */ #include <algorithm> // fill #include <iostream> HeightMap::HeightMap(char initialHeight) { for (int i=0; i<engine.WIDTH*engine.HEIGHT; ++i) { heights[i] = initialHeight; } } void HeightMap::clear() { std::fill(heights, heights+(Engine::WIDTH*Engine::HEIGHT), 0); } void HeightMap::setHeight(int x, int y, char height) { heights[x+y*engine.WIDTH] = height; } void HeightMap::changeHeight(int x, int y, char change) { heights[x+y*engine.WIDTH] += change; if( heights[x+y*engine.WIDTH] < 0 ) heights[x+y*engine.WIDTH] = 0; else if( heights[x+y*engine.WIDTH] > Engine::DEPTH ) heights[x+y*engine.WIDTH] = Engine::DEPTH; } char HeightMap::changeHeightConserving(int x, int y, char change) { heights[x+y*engine.WIDTH] += change; char amountChanged = change; if( heights[x+y*engine.WIDTH] < 0 ) { amountChanged = (-1)*(heights[x+y*engine.WIDTH] - change); heights[x+y*engine.WIDTH] = 0; } else if( heights[x+y*engine.WIDTH] > Engine::DEPTH ) { amountChanged = heights[x+y*engine.WIDTH] - Engine::DEPTH; heights[x+y*engine.WIDTH] = Engine::DEPTH; } return amountChanged; } void HeightMap::moveHeight(int x0, int y0, int x_dest, int y_dest, char amount) { changeHeight(x0, y0, -amount); changeHeight(x_dest, y_dest, amount); } void HeightMap::moveHeightConserving(int x0, int y0, int x_dest, int y_dest, char amount) { char amountTaken = -1 * changeHeightConserving(x0, y0, -amount); char amountAdded = changeHeightConserving(x_dest, y_dest, amountTaken); changeHeight(x0, y0, amountTaken-amountAdded); } char HeightMap::getHeight(int x, int y) const { return heights[x+y*engine.WIDTH]; } void HeightMap::render() const { for (int x=1; x<engine.WIDTH-1; ++x) for (int y=1; y<engine.HEIGHT-1; ++y) { TCODConsole::root->setCharBackground(x,y, TCODColor::white * ( (float)getHeight(x,y)/((float)engine.DEPTH) )*0.5 ); } } ColorMap::ColorMap() : HeightMap(0) { for (int i=0; i<engine.WIDTH*engine.HEIGHT; ++i) { players[i] = NULL; } } void ColorMap::clear() { HeightMap::clear(); std::fill(players, &players[(Engine::WIDTH-1)*(Engine::HEIGHT-1)], nullptr); } void ColorMap::setPlayer(int x, int y, Player* player) { players[x+y*engine.WIDTH] = player; } Player* ColorMap::getPlayer(int x, int y) const { return players[x+y*engine.WIDTH]; } void ColorMap::moveColor(int x0, int y0, int x_dest, int y_dest, char amount) { Player* player = getPlayer(x0,y0); moveHeight(x0,y0, x_dest,y_dest, amount); // move the color if ( getHeight(x0,y0) == 0 ) // reset old field if player is now gone setPlayer(x0,y0,NULL); setPlayer(x_dest,y_dest,player); // set ownership of new field } void ColorMap::moveColorConserving(int x0, int y0, int x_dest, int y_dest, char amount) { Player* player = getPlayer(x0,y0); moveHeightConserving(x0,y0, x_dest,y_dest, amount); // move the color if ( getHeight(x0,y0) == 0 ) // reset old field if player is now gone setPlayer(x0,y0,NULL); if ( getHeight(x_dest,y_dest) != 0 ) setPlayer(x_dest,y_dest,player); // set ownership of new field } void ColorMap::render() const { for (int x=0; x<engine.WIDTH; ++x) for (int y=0; y<engine.HEIGHT; ++y) { Player* playerHere = getPlayer(x,y); if( playerHere ) { TCOD_console_set_char_background( NULL , x, y, TCOD_color_multiply_scalar(playerHere->col, ((float)getHeight(x,y)/(float)Engine::DEPTH) ), TCOD_BKGND_ADD); //TCOD_console_set_char( NULL, x, y, playerHere==engine.players[0] ? 'G' : 'R'); //TCOD_console_set_char_foreground( NULL , x, y, {10,10,10} ); } } } void ColorMap::update() { // create all the liquid-like dynamics bool clk = engine.turn%2; int x0; int y0; if( clk ) { x0 = 0; y0 = 0; } else { x0 = engine.WIDTH-1; y0 = engine.HEIGHT-1; } for (int x=x0 ; clk ? x<engine.WIDTH : x>-1 ; clk ? ++x : --x ) for (int y=y0 ; clk ? y<engine.HEIGHT : y>-1 ; clk ? ++y : --y ) { Player* player = getPlayer(x,y); if (player) { // if there is someone there bool moved = false; // remember that you haven't moved the color yet char localHeight = engine.getHeight(x,y); // get the height of the color char localTotalHeight = engine.totalHeight(x,y,player); // and the height of the color + other factors (HeightMap of player and global one) Direction direction = player->getDirection(x,y); // check for a forced direction if( direction != NEUTRAL ) // if true try to move there { int dx=0; int dy=0; DirectionMap::calcDxDy(&dx, &dy, direction); // calculate your destination coordinates based on the given direction int x_dest = x + dx; // int y_dest = y + dy; Player* player_dest = getPlayer(x_dest,y_dest); // check for a player on the field you want to move to if ( player_dest && player_dest!=player ) { // if it's a different player engine.fightBetween(x,y, x_dest,y_dest); // fight } // else try to move there else if ( localHeight>1 && engine.totalGroundHeight(x_dest,y_dest,player) < localTotalHeight && engine.totalHeight(x_dest,y_dest,player) < Engine::DEPTH ) // settle for an "equal" ground-height or better (if it's not full already anyway) moveColorConserving(x,y,x_dest,y_dest, localHeight/2); // (this means color can't flow up-hill, but it can get more concentrated when "pumped" this way) } else // if there is no forced direction try to move randomly { // check a random neighbour for lower height for (int i=0; i<4; ++i) { int x_dest = x + rand() % 3 -1; int y_dest = y + rand() % 3 -1; Player* player_dest = getPlayer(x_dest,y_dest); if ( player_dest && player_dest!=player ) { engine.fightBetween(x,y, x_dest,y_dest); moved = true; break; } if ( engine.totalHeight(x_dest,y_dest,player)+1 < localTotalHeight ) // check the neighbour for lower height { moveColor(x,y,x_dest,y_dest); // and move a unit of color there if true moved = true; break; } } if( !moved ) { // try settling for an "equal" one but try to stick to the rest of the fluid int max_x_dest = -1; int max_y_dest = -1; char max_neighbours = 1; for (int i=0; i<9; ++i) { int x_dest = x + rand() % 3 -1; int y_dest = y + rand() % 3 -1; Player* player_dest = getPlayer(x_dest,y_dest); if ( player_dest && player_dest!=player ) { engine.fightBetween(x,y, x_dest,y_dest); moved = true; break; } if ( localHeight>1 && engine.totalHeight(x_dest,y_dest,player) < localTotalHeight ) // if the field is about as high as you { // count the neighbours char neighbours = 0; for( int dx=-1; dx<=1; ++dx ) for( int dy=-1; dy<=1; ++dy ) if (engine.totalHeight(x_dest+dx,y_dest+dy, player) == localTotalHeight) ++neighbours; if( neighbours > max_neighbours ) { max_neighbours = neighbours; max_x_dest = x_dest; max_y_dest = y_dest; } } } // if you found a suitable field if( max_x_dest >= 0 && max_y_dest >= 0 && !moved ) { moveColor(x,y,max_x_dest,max_y_dest); // move there moved = true; } } // just try settling for an "equal" one if( !moved ) { int x_dest = x + rand() % 3 -1; int y_dest = y + rand() % 3 -1; Player* player_dest = getPlayer(x_dest,y_dest); if ( player_dest && player_dest!=player ) { engine.fightBetween(x,y, x_dest,y_dest); } else if ( localHeight>1 && engine.totalHeight(x_dest,y_dest,player) < localTotalHeight ) // try settling for an "equal" one moveColor(x,y,x_dest,y_dest); } } } } } char ColorMap::pumpAt(int x, int y, char amount, Player* pumpingPlayer) { const char startingAmount = amount; // clear the boolArray std::fill(boolArray, boolArray+(Engine::WIDTH*Engine::HEIGHT), 0); // include the first field lastIndex = 0; indexArray[0] = y*Engine::WIDTH+x; boolArray[y*Engine::WIDTH+x] = true; // find fields to pump to for(unsigned int i=0; i<=lastIndex; ++i) { if (pumpFromIndex(indexArray[i],amount,pumpingPlayer)) break; } return startingAmount - amount; // return how much color has been successfully pumped } bool ColorMap::pumpFromIndex(unsigned int i, char& amount, Player* pumpingPlayer) { int x = i%Engine::WIDTH; int y = i/Engine::WIDTH; Player* player = getPlayer(x,y); if( player!=NULL && player!=pumpingPlayer ) return false; // don't pump your enemy's field // first check the given field char freeSpace = Engine::DEPTH - engine.totalHeight(x,y,pumpingPlayer); if( freeSpace>0 ) // if there is free space on that field { setPlayer(x,y,pumpingPlayer); changeHeight(x,y,freeSpace); // pump it full amount -=freeSpace; if(amount <= 0) { // you're done changeHeight(x,y,amount); // make sure you didn't pump too much amount = 0; // and set amount to 0 to indicate that all has been pumped return true; } } // if you're not done yet add its neighbours to the list to be checked Direction direction = pumpingPlayer->getDirection(x,y); // check if there is a forced direction if( direction == NEUTRAL ) // if not add all neighbours to the list { for( int dx = -1; dx <=1; ++dx ) for( int dy = -1; dy <=1; ++dy ) { if( !dx && !dy ) continue; // your own field is, of course, not worth checking if( !engine.inMap(x+dx,y+dy) ) continue; unsigned int index = (y+dy)*Engine::WIDTH + (x+dx); Player* otherPlayer = getPlayer(x+dx,y+dy); if( boolArray[ index ]==false && (!otherPlayer || otherPlayer==pumpingPlayer) && engine.totalGroundHeight(x+dx,y+dy,pumpingPlayer)<Engine::DEPTH ) { // if the field hasn't been checked/added yet and belongs to you indexArray[++lastIndex] = index; // add it to the list boolArray[index] = true; // and mark it as added } } } else // if true add only the one correct neighbour to the list { int dx=0; int dy=0; DirectionMap::calcDxDy(&dx,&dy,direction); if( !engine.inMap(x+dx,y+dy) ) return false; unsigned int index = (y+dy)*Engine::WIDTH + (x+dx); Player* otherPlayer = getPlayer(x+dx,y+dy); if( boolArray[ index ]==false && (!otherPlayer || otherPlayer==pumpingPlayer) && engine.totalGroundHeight(x+dx,y+dy,pumpingPlayer)<Engine::DEPTH ) { // if the field hasn't been checked/added yet and belongs to you indexArray[++lastIndex] = index; // add it to the list boolArray[index] = true; // and mark it as added } } return false; } void DirectionMap::setDirection(int x, int y, Direction direction) { heights[x+y*engine.WIDTH] = (char)direction; } Direction DirectionMap::getDirection(int x, int y) const { return static_cast<Direction>(getHeight(x,y)); } const Direction DirectionMap::calcDirectionInverted(char dx, char dy) { switch(dx) { case -1: switch(dy) { case -1: return DOWN_LEFT; case 0: return LEFT; case 1: return UP_LEFT; default: return NEUTRAL; } case 0: switch(dy) { case -1: return DOWN; case 0: return NEUTRAL; case 1: return UP; default: return NEUTRAL; } case 1: switch(dy) { case -1: return DOWN_RIGHT; case 0: return RIGHT; case 1: return UP_RIGHT; default: return NEUTRAL; } } return NEUTRAL; } const Direction DirectionMap::calcDirection(char dx, char dy) { switch(dx) { case -1: switch(dy) { case 1: return DOWN_LEFT; case 0: return LEFT; case -1: return UP_LEFT; default: return NEUTRAL; } case 0: switch(dy) { case 1: return DOWN; case 0: return NEUTRAL; case -1: return UP; default: return NEUTRAL; } case 1: switch(dy) { case 1: return DOWN_RIGHT; case 0: return RIGHT; case -1: return UP_RIGHT; default: return NEUTRAL; } } return NEUTRAL; } const Direction DirectionMap::opposingDirection(Direction direction) { switch(direction) { case UP: return DOWN; case DOWN: return UP; case RIGHT: return LEFT; case LEFT: return RIGHT; case DOWN_RIGHT: return UP_LEFT; case DOWN_LEFT: return UP_RIGHT; case UP_LEFT: return DOWN_RIGHT; case UP_RIGHT: return DOWN_LEFT; default: return NEUTRAL; } } void DirectionMap::calcDxDy(int* dx, int* dy, Direction direction) { switch(direction) { case UP: *dx = 0; *dy = -1; break; case DOWN: *dx = 0; *dy = 1; break; case RIGHT: *dx = 1; *dy = 0; break; case LEFT: *dx = -1; *dy = 0; break; case DOWN_RIGHT: *dx = 1; *dy = 1; break; case DOWN_LEFT: *dx = -1; *dy = 1; break; case UP_LEFT: *dx = -1; *dy = -1; break; case UP_RIGHT: *dx = 1; *dy = -1; break; default: break; } } const int DirectionMap::getTilePosition(Direction direction) { switch(direction) { case UP: return 24; case DOWN: return 25; case RIGHT: return 26; case LEFT: return 27; case DOWN_RIGHT: return 208; case DOWN_LEFT: return 209; case UP_LEFT: return 210; case UP_RIGHT: return 211; default: return 0; } return 0; } <file_sep>/src/Brush.hpp class Brush { private: static constexpr float MAX_BRUSH_RADIUS = 10; // must be an even number static constexpr int BRUSH_CENTER_INDEX = (int)MAX_BRUSH_RADIUS; float radius; char height; char brushArray[(int)MAX_BRUSH_RADIUS*2+1][(int)MAX_BRUSH_RADIUS*2+1]; void calcBrush(); public: Brush(); void changeSize(float amount); void changeHeight(char amount); void digAt(int xCenter, int yCenter, Player* player); void fillAt(int xCenter, int yCenter, Player* player); void setDirection(int xCenter, int yCenter, Player* player, Direction direction); void render( int xCenter, int yCenter, bool decreaseCursorOpacity ) const; void renderHeightMap( int xCenter, int yCenter, const HeightMap* heightMap, const Player* player ) const; void renderDirectionMap( int xCenter, int yCenter, const DirectionMap* directionMap, const Player* player ) const; double radiusCondition() const; };<file_sep>/src/HeightMap.hpp class HeightMap { protected: char heights [Engine::WIDTH*Engine::HEIGHT]; public: HeightMap(char initialHeight = Engine::DEPTH); void render() const; void setHeight(int x, int y, char height); void changeHeight(int x, int y, char change); char changeHeightConserving(int x, int y, char change); void moveHeight(int x0, int y0, int x_dest, int y_dest, char amount=1); void moveHeightConserving(int x0, int y0, int x_dest, int y_dest, char amount); char getHeight(int x, int y) const; void clear(); }; class ColorMap : public HeightMap { private: Player* players[Engine::WIDTH*Engine::HEIGHT]; // stuff for the pump-algorithm unsigned int lastIndex; // the last index to check within indexArray unsigned int indexArray [Engine::WIDTH*Engine::HEIGHT]; // holds the indices of fields to be checked bool boolArray [Engine::WIDTH*Engine::HEIGHT]; // tells whether a field has been checked already bool pumpFromIndex(unsigned int i, char& amount, Player* pumpingPlayer); public: ColorMap(); void setPlayer(int x, int y, Player* player); Player* getPlayer(int x, int y) const; void render() const; void update(); void moveColor(int x0, int y0, int x_dest, int y_dest, char amount=1); void moveColorConserving(int x0, int y0, int x_dest, int y_dest, char amount); char pumpAt(int x, int y, char amount, Player* pumpingPlayer); void clear(); }; class DirectionMap : public HeightMap { public: DirectionMap() : HeightMap(0) {} void setDirection(int x, int y, Direction direction); Direction getDirection(int x, int y) const; static const Direction calcDirection(char dx, char dy); static const Direction opposingDirection(Direction direction); static const Direction calcDirectionInverted(char dx, char dy); static void calcDxDy(int* dx, int* dy, Direction direction); // set *dx and *dy to the correct values based on the given direction (WARNING: y is inverted) static const int getTilePosition(Direction direction); };<file_sep>/src/Structure.hpp class Structure { protected: int x,y; Player* owner; public: Structure(int x, int y, Player* owner); virtual ~Structure() = default; virtual void update() = 0; virtual void render() const = 0; }; class Spawner : public Structure { private: float production; // of fluid per second float producedAmount; // ready to be given out static constexpr float STANDARD_PRODUCTION = 0.2; static constexpr int ROLLOUT_SIZE = 4; public: Spawner(int x, int y, Player* owner, float production=STANDARD_PRODUCTION); void update(); void render() const; };<file_sep>/src/Structure.cpp #include "main.hpp" #include <cmath> Structure::Structure(int x, int y, Player* owner) : x(x), y(y), owner(owner) {} Spawner::Spawner(int x, int y, Player* owner, float production) : Structure(x,y,owner), production(production), producedAmount(0) {} void Spawner::update() { // if there is someone new at your position, make him the new owner Player* player = engine.getPlayer(x,y); if( player!=NULL && player!=owner ) owner = player; if(owner) { // produce fluid producedAmount += production; int output = (int)producedAmount; if( output >= ROLLOUT_SIZE ) { producedAmount -= output; engine.setPlayer(x,y,owner); engine.pumpAt(x,y,output,owner); } } } void Spawner::render() const { if( owner ) { TCOD_console_set_char( NULL, x, y, engine.turn%(int)Engine::FPS >= Engine::FPS/2 ? '+' : 'x'); TCOD_console_set_char_foreground( NULL , x, y, owner->col ); } else { TCOD_console_set_char( NULL, x, y, '+' ); TCOD_console_set_char_foreground( NULL , x, y, TCOD_color_t{127,127,127} ); } }<file_sep>/src/Player.cpp #include "main.hpp" Player::Player(TCOD_color_t col, int cId) : heightMap(0), directionMap(), gamepad(cId,0.1f,0.07f), cursorX(1), cursorY(1), col(col) { } void Player::update() { if( gamepad.Refresh() ) { // Actions action = NONE; if (gamepad.leftTrigger) action = SHOW_HEIGHTMAP; else if (gamepad.rightTrigger) action = SHOW_DIRECTIONMAP; // cursor movement cursorX += gamepad.leftStickX/2; cursorY -= gamepad.leftStickY/2; if( cursorX < 1 ) cursorX = 1; else if( cursorX >= Engine::WIDTH-1 ) cursorX = Engine::WIDTH-2; if( cursorY < 1 ) cursorY = 1; else if( cursorY >= Engine::HEIGHT-1 ) cursorY = Engine::HEIGHT-2; // selection radius if( action != SHOW_DIRECTIONMAP ) changeBrushSize( gamepad.rightStickX/2 ); // Shoulder buttons control brush height if( gamepad.IsPressed(XINPUT_GAMEPAD_RIGHT_SHOULDER) ) { if( gamepad.IsPressed(XINPUT_GAMEPAD_RIGHT_SHOULDER,0.15) || wasPressedRB == false ) brush.changeHeight(1); wasPressedRB = true; } else wasPressedRB = false; if( gamepad.IsPressed(XINPUT_GAMEPAD_LEFT_SHOULDER) ) { if( gamepad.IsPressed(XINPUT_GAMEPAD_LEFT_SHOULDER,0.15) || wasPressedLB == false ) brush.changeHeight(-1); wasPressedLB = true; } else wasPressedLB = false; if (action == SHOW_DIRECTIONMAP) { char dx=0; char dy=0; if(gamepad.rightStickX > 0.1) dx = 1; else if(gamepad.rightStickX < -0.1) dx = -1; if(gamepad.rightStickY > 0.1) dy = 1; else if(gamepad.rightStickY < -0.1) dy = -1; if( gamepad.IsPressed(XINPUT_GAMEPAD_B) ) useDirectionBrush(0,0); else if( dx != 0 || dy != 0 ) useDirectionBrush(dx,dy); } else { decreaseCursorOpacity = true; if (gamepad.IsPressed(XINPUT_GAMEPAD_A)) useDigBrush(); else if (gamepad.IsPressed(XINPUT_GAMEPAD_B)) useFillBrush(); else decreaseCursorOpacity = false; } } } void Player::render() const { //heightMap.render(); // render cursor //TCOD_console_set_char_background( NULL , cursorX, cursorY, TCOD_color_multiply_scalar( {255,255,255}, 0.3 ), TCOD_BKGND_ADD); if( action == SHOW_HEIGHTMAP ) brush.renderHeightMap( (int)cursorX, (int)cursorY, &heightMap, this ); else if( action == SHOW_DIRECTIONMAP ) brush.renderDirectionMap( (int)cursorX, (int)cursorY, &directionMap, this ); else brush.render( (int)cursorX, (int)cursorY, decreaseCursorOpacity ); //DEBUG if(this==engine.players[0])TCOD_console_put_char( NULL, Engine::WIDTH-1, 0, engine.getHeight((int)cursorX, (int)cursorY)+48 , TCOD_BKGND_SET); } char Player::getHeight(int x, int y) const { return heightMap.getHeight(x,y); } void Player::setHeight(int x, int y, char height) { heightMap.setHeight(x,y,height); } void Player::setDirection(int x, int y, Direction direction) { directionMap.setDirection(x,y, direction); } Direction Player::getDirection(int x, int y) const { return directionMap.getDirection(x,y); } // brush stuff void Player::changeBrushSize(float amount) { brush.changeSize(amount); } void Player::changeBrushHeight(char amount) { brush.changeHeight(amount); } void Player::useDigBrush() { brush.digAt((int)cursorX,(int)cursorY, this); } void Player::useFillBrush() { brush.fillAt((int)cursorX,(int)cursorY, this); } void Player::useDirectionBrush(char dx, char dy) { brush.setDirection((int)cursorX,(int)cursorY, this, DirectionMap::calcDirectionInverted(dx,dy) ); } <file_sep>/src/XInput.cpp #include "main.hpp" #include <iostream> #include <math.h> using std::cout; using std::endl; int Gamepad::GetPort() { return cId + 1; } XINPUT_GAMEPAD *Gamepad::GetState() { return &state.Gamepad; } bool Gamepad::CheckConnection() { XINPUT_STATE state; ZeroMemory(&state, sizeof(XINPUT_STATE)); return (XInputGetState(cId, &state) == ERROR_SUCCESS); } // Returns false if the controller has been disconnected bool Gamepad::Refresh() { ZeroMemory(&state, sizeof(XINPUT_STATE)); if (XInputGetState(cId, &state) != ERROR_SUCCESS) { return false; } else { float normLX = fmaxf(-1, (float) state.Gamepad.sThumbLX / 32767); float normLY = fmaxf(-1, (float) state.Gamepad.sThumbLY / 32767); leftStickX = (abs(normLX) < deadzoneX ? 0 : (abs(normLX) - deadzoneX) * (normLX / abs(normLX))); leftStickY = (abs(normLY) < deadzoneY ? 0 : (abs(normLY) - deadzoneY) * (normLY / abs(normLY))); if (deadzoneX > 0) leftStickX *= 1 / (1 - deadzoneX); if (deadzoneY > 0) leftStickY *= 1 / (1 - deadzoneY); float normRX = fmaxf(-1, (float) state.Gamepad.sThumbRX / 32767); float normRY = fmaxf(-1, (float) state.Gamepad.sThumbRY / 32767); rightStickX = (abs(normRX) < deadzoneX ? 0 : (abs(normRX) - deadzoneX) * (normRX / abs(normRX))); rightStickY = (abs(normRY) < deadzoneY ? 0 : (abs(normRY) - deadzoneY) * (normRY / abs(normRY))); if (deadzoneX > 0) rightStickX *= 1 / (1 - deadzoneX); if (deadzoneY > 0) rightStickY *= 1 / (1 - deadzoneY); leftTrigger = (float) state.Gamepad.bLeftTrigger / 255; rightTrigger = (float) state.Gamepad.bRightTrigger / 255; return true; } return false; } bool Gamepad::IsPressed(WORD button) { return (state.Gamepad.wButtons & button) != 0; } bool Gamepad::IsPressed(WORD button, double cooldown) { int index; switch(button) { case XINPUT_GAMEPAD_DPAD_UP: index = 0; break; case XINPUT_GAMEPAD_DPAD_DOWN: index = 1; break; case XINPUT_GAMEPAD_DPAD_LEFT: index = 2; break; case XINPUT_GAMEPAD_DPAD_RIGHT: index = 3; break; case XINPUT_GAMEPAD_LEFT_SHOULDER: index = 4; break; case XINPUT_GAMEPAD_RIGHT_SHOULDER: index = 5; break; case XINPUT_GAMEPAD_A: index = 6; break; case XINPUT_GAMEPAD_B: index = 7; break; case XINPUT_GAMEPAD_X: index = 8; break; case XINPUT_GAMEPAD_Y: index = 9; break; default : return false; } using namespace std::chrono; if( IsPressed(button) ) { steady_clock::time_point now = steady_clock::now(); // calculate the time span between now and the last time this buttons was acknowledged as "pressed" steady_clock::duration time_span = now - lastPressed[index]; double nseconds = double(time_span.count()) * steady_clock::period::num / steady_clock::period::den; if( nseconds >= cooldown ) { // if the time span reaches or surpasses the desired cooldown acknowledge the button press lastPressed[index] = now; return true; } } return false; } <file_sep>/README.md # Liquid-Game ![](https://media.giphy.com/media/RbCl4aD3LPgzXnmXJ1/giphy.gif) A primitive liquid simulation, controlled through up to 4 gamepads. It's basically a cellular automaton where liquid tries to space itself out somewhat evenly over multiple cells while the flow of liquid is being manipulated. The original idea was to turn it into a local multiplayer strategy game. It is playable as such, but there's little strategy to winning as of now. <file_sep>/src/Creature.cpp #include "main.hpp" #include <stdlib.h> #include <iostream> Creature::Creature(int x, int y) : x(x), y(y) {} Tree::Tree(int x, int y) : Creature(x,y) { source = new Source(x,y); } Tree::~Tree() { delete source; } void Tree::growRoot() { if( !engine.rootMutex.try_lock() ) return; // if you would have to wait for access to the rootSources-system give up right away //std::cout << "rootMutex aquired in growRoot\n"; // find the edges of your root-network and add a root at a random edge-point static std::vector<unsigned int> edgeIndexes; static std::vector<unsigned int> outerEdgeIndexes; edgeIndexes.clear(); outerEdgeIndexes.clear(); int xPos=x, yPos=y; int rootsChecked = 0; // find the edges for( engine.rootIterationBegin(&xPos,&yPos); xPos!=engine.rootIterationEnd(); engine.rootIterationNext(&xPos,&yPos) ) { if( rootsChecked >= maxRootAmount ) goto done; // if you've already found enough roots inside of your reach stop completely, because you already have enough if( *source->myDistanceAt(xPos,yPos) > maxRootLength ) break; // if you're starting to look outside of your reach stop searching for new free spots int i = 0; bool fieldAdded = false; bool fieldAddedOuter = false; Direction currentDirection = engine.rootIndexToDirection(i); while( currentDirection != NEUTRAL && !(fieldAdded && fieldAddedOuter) ) { // go through all directions Direction opposingDirection = DirectionMap::opposingDirection(currentDirection); int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, currentDirection); // check whether the fluid concentration lures you into that direction if( engine.getHeight(xPos,yPos)>=fluidNeededForGrowth && engine.getHeight(xPos+dx,yPos+dy)>=fluidNeededForAttraction ) { if( !engine.checkRootDirection( xPos, yPos, currentDirection) ) { if( !fieldAdded && engine.rootAllowed(xPos,yPos,currentDirection) ) // if this field is missing an allowed root add it to the list { edgeIndexes.push_back( xPos + yPos*Engine::WIDTH ); fieldAdded = true; } } else { // if you already have a root in that direction search for a free spot facing you in your neighbours if( !engine.checkRootDirection( xPos+dx, yPos+dy, opposingDirection ) && engine.rootAllowed(xPos+dx, yPos+dy, opposingDirection) ) { outerEdgeIndexes.push_back( xPos + yPos*Engine::WIDTH ); fieldAddedOuter = true; } } } currentDirection = engine.rootIndexToDirection(++i); } rootsChecked++; } // grow the root from a random position { int edgeCount = edgeIndexes.size(); int outerEdgeCount = outerEdgeIndexes.size(); if( edgeCount == 0 && outerEdgeCount == 0 ) goto done; //std::cout << "free places for roots found\n"; unsigned int chosenIndex; int chosenX; int chosenY; if( rand() % (edgeCount+outerEdgeCount) < edgeCount ) { // decide randomly whether to pick an edge-field or an outer-edge-field chosenIndex = edgeIndexes[rand() % edgeCount]; // choose a random edge-field chosenX = chosenIndex % Engine::WIDTH; chosenY = chosenIndex / Engine::WIDTH; while( true ) { Direction randomDirection = engine.rootIndexToDirection( rand() % engine.ROOT_DIRECTIONS ); // choose a random direction int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, randomDirection); if( engine.getHeight(chosenX,chosenY)>=fluidNeededForGrowth && engine.getHeight(chosenX+dx,chosenY+dy)>=fluidNeededForAttraction ) // check for attractive fluid if( !engine.checkRootDirection( chosenX, chosenY, randomDirection ) && engine.rootAllowed(chosenX, chosenY, randomDirection) ) // check for a missing root { engine.addRootDirection( chosenX, chosenY, randomDirection ); // add it if you find it missing engine.changeHeight(chosenX, chosenY, -fluidNeededForGrowth); // decrease the fluid level as a cost for the player edgeCount--; //std::cout << "root grown\n"; break; } } } else { chosenIndex = outerEdgeIndexes[rand() % outerEdgeCount]; // choose a random outer-edge-field chosenX = chosenIndex % Engine::WIDTH; chosenY = chosenIndex / Engine::WIDTH; while( true ) { Direction randomDirection = engine.rootIndexToDirection( rand() % engine.ROOT_DIRECTIONS ); // choose a random direction int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, randomDirection); Direction opposingDirection = DirectionMap::opposingDirection(randomDirection); // check for an existing root on your side and a missing root on the other if( engine.getHeight(chosenX,chosenY)>=fluidNeededForGrowth && engine.getHeight(chosenX+dx,chosenY+dy)>=fluidNeededForAttraction ) // check for attractive fluid if( engine.checkRootDirection( chosenX, chosenY, randomDirection ) && !engine.checkRootDirection( chosenX+dx, chosenY+dy, opposingDirection ) && engine.rootAllowed(chosenX+dx, chosenY+dy, opposingDirection) ) { engine.addRootDirection( chosenX+dx, chosenY+dy, opposingDirection ); // add it if you find it missing engine.changeHeight(chosenX+dx, chosenY+dy, -fluidNeededForGrowth); // decrease the fluid level as a cost for the player outerEdgeCount--; //std::cout << "root grown\n"; break; } } } } done: engine.rootMutex.unlock(); //std::cout << "rootMutex released in growRoot\n"; } SolarTree::SolarTree(int x, int y, float chargeProduction) : Tree(x,y), chargeProduction(chargeProduction) {} SolarTree::~SolarTree() {} void SolarTree::update() { source->increaseCharge( chargeProduction / Engine::CREATURE_UPDATES_PER_SECOND ); if( rand() % (int)(Engine::CREATURE_UPDATES_PER_SECOND) != 0 ) growRoot(); } void SolarTree::render() const { TCOD_console_set_char( NULL, x, y, 'o' ); //TCOD_console_set_char_foreground( NULL , x, y, {255,255,255} ); }<file_sep>/src/Source.hpp class Source { private: int x,y; float charge; static unsigned int lastIndex; // the last index to check within indexArray static unsigned int indexArray[Engine::WIDTH*Engine::HEIGHT]; // holds the indices of fields to be checked static bool boolArray [Engine::WIDTH*Engine::HEIGHT]; // tells whether a field has been checked already void spread(); public: Source(int x, int y); void increaseCharge(float amount); void decreaseCharge(float amount); void resetCharge(); float getCharge() const; void setToPosition(int* x_ptr, int* y_ptr); void spreadFrom(int x, int y); void killFrom(int x, int y); void deleteMyPairAt(int x, int y); void addMyPairTo(int x, int y, int distance); int* myDistanceAt(int x, int y); };<file_sep>/src/main.hpp // Dependency-management-model: "one to rule them all" enum Direction : char { NEUTRAL, DOWN_LEFT, DOWN, DOWN_RIGHT, RIGHT, UP_RIGHT, UP, UP_LEFT, LEFT }; class ColorMap; class HeightMap; class FourDirectionMap; class DirectionMap; class Player; class Source; class Creature; #include <vector> #include <utility> #include <map> #include <mutex> //#include <shared_mutex> #include "libtcod.hpp" #include <chrono> #include "XInput.hpp" #include "Structure.hpp" #include "Engine.hpp" #include "HeightMap.hpp" #include "MultiDirectionMap.hpp" #include "Brush.hpp" #include "Player.hpp" #include "Source.hpp" #include "Creature.hpp"<file_sep>/src/Engine.hpp class Engine { public: static const int WIDTH = 1920/16; static const int HEIGHT = 1080/16; static const char DEPTH = 5; static constexpr float FPS = 60.0; static constexpr float CREATURE_UPDATES_PER_SECOND = 20; static constexpr int ROOT_DIRECTIONS = 4; private: ColorMap* colorMap; HeightMap* globalHeightMap; // roots FourDirectionMap* rootDirections; std::map<Source*,int> rootSources [WIDTH*HEIGHT]; std::mutex rootSourceMutex [WIDTH*HEIGHT]; float rootCharges [WIDTH*HEIGHT]; std::vector<Creature*> creatures; // stuff for the pump/pathfinding-algorithm unsigned int currentIndex; // the current index to check within indexArray unsigned int lastIndex; // the last index to check within indexArray unsigned int indexArray [Engine::WIDTH*Engine::HEIGHT]; // holds the indices of fields to be checked bool boolArray [Engine::WIDTH*Engine::HEIGHT]; // tells whether a field has been checked already public : Player* players [4]; unsigned long turn; TCOD_key_t lastKey; enum GameStatus { RUNNING, EXIT } gameStatus; std::vector<Structure*> structures; std::mutex rootMutex; // if aquired this mutex gives a thread the right to alter/or read the root-system Engine(); ~Engine(); void update(); void render(); Player* getPlayer(int x, int y) const; char getHeight(int x, int y) const; char getGlobalHeight(int x, int y) const; char totalGroundHeight(int x, int y, const Player* player) const; char totalHeight(int x, int y, Player* player) const; void setField (int x, int y, Player* player, char height); void setPlayer(int x, int y, Player* player); void setHeight(int x, int y, char height); void setGlobalHeight(int x, int y, char height); void moveColor(int x0, int y0, int x_dest, int y_dest, char amount=1); void changeHeight(int x, int y, char change); char pumpAt(int x, int y, char amount, Player* pumpingPlayer); void fightBetween(int x1, int y1, int x2, int y2); bool inMap(int x, int y) const; bool perSecond(float repetitions) const; // returns true "repetitions" times per second void addCreature(Creature* creature); void removeCreature(Creature* creature); void addStructure(Structure* structure); void removeStructure(Structure* structure); void clearLevel(); void loadBitmap(const char* filename); // roots bool checkRootConnection(int x, int y, Direction direction); bool checkRootDirection(int x, int y, Direction direction); void addRootDirectionThread(int x, int y, Direction direction); void addRootDirection(int x, int y, Direction direction); void removeRootDirectionThread(int x, int y, Direction direction); void removeRootDirection(int x, int y, Direction direction); void clearRootField(int x, int y); Direction rootIndexToDirection(int i) const; std::map<Source*,int>* getRootSources(int x, int y); float getRootCharge(int x, int y); float getLastRootCharge(int x, int y) const; void rootIterationBegin(int* x_ptr, int* y_ptr); // starts a search for connected roots at *x_ptr,*y_ptr void rootIterationNext(int* x_ptr, int* y_ptr); // sets *x_ptr,*y_ptr to the next field in the search for connected roots int rootIterationEnd() const; // returns -1 Direction findRootNeighbour(int x, int y) const; bool rootAllowed(int x, int y, Direction direction); // whether a root starting from x,y in the specified direction would not create a circle (circles are forbidden) void lockRootSource(int x, int y); void unlockRootSource(int x, int y); }; extern Engine engine;<file_sep>/src/MultiDirectionMap.hpp class MultiDirectionMap { public: virtual bool checkDirection(int x, int y, Direction direction) = 0; virtual void addDirection(int x, int y, Direction direction) = 0; virtual void removeDirection(int x, int y, Direction direction) = 0; virtual void clear() = 0; virtual void render() = 0; }; class FourDirectionMap : MultiDirectionMap { private: bool directions [Engine::WIDTH*Engine::HEIGHT][4]; std::mutex directionMutexes [Engine::WIDTH*Engine::HEIGHT]; const int getTilePosition(int x, int y); public: FourDirectionMap(); virtual ~FourDirectionMap() = default; static const int directionToIndex(Direction direction); static const Direction indexToDirection(int index); bool checkDirection(int x, int y, Direction direction); void addDirection(int x, int y, Direction direction); void removeDirection(int x, int y, Direction direction); void clearField(int x, int y); void clear(); void render(); }; class EightDirectionMap : MultiDirectionMap { private: bool directions [Engine::WIDTH*Engine::HEIGHT][8]; public: EightDirectionMap(); static const int directionToIndex(Direction direction); bool checkDirection(int x, int y, Direction direction); void addDirection(int x, int y, Direction direction); void removeDirection(int x, int y, Direction direction); void clear(); //void clearField(); //void render(); }; <file_sep>/src/MultiDirectionMap.cpp #include "main.hpp" #include <algorithm> // fill FourDirectionMap::FourDirectionMap() { clear(); } void FourDirectionMap::clear(){ for(int i=0; i<Engine::WIDTH*Engine::HEIGHT; i++) { for(int j=0; j<4; j++) { std::lock_guard<std::mutex> lockGuard(directionMutexes[i]); directions[i][j] = false; } } //std::fill(directions, directions+(Engine::WIDTH*Engine::HEIGHT)*4, false); } const int FourDirectionMap::directionToIndex(Direction direction) { switch(direction) { case UP: return 0; case LEFT: return 1; case DOWN: return 2; case RIGHT: return 3; default: return -1; } return -1; } const Direction FourDirectionMap::indexToDirection(int index) { switch(index) { case 0: return UP; case 1: return LEFT; case 2: return DOWN; case 3: return RIGHT; default: return NEUTRAL; } return NEUTRAL; } bool FourDirectionMap::checkDirection(int x, int y, Direction direction) { int index = directionToIndex(direction); if( index == -1 ) return false; std::lock_guard<std::mutex> lockGuard(directionMutexes[x+y*Engine::WIDTH]); return directions[x+y*Engine::WIDTH][directionToIndex(direction)]; } void FourDirectionMap::addDirection(int x, int y, Direction direction) { int index = directionToIndex(direction); if( index == -1 ) return; std::lock_guard<std::mutex> lockGuard(directionMutexes[x+y*Engine::WIDTH]); directions[x+y*Engine::WIDTH][directionToIndex(direction)] = true; } void FourDirectionMap::removeDirection(int x, int y, Direction direction) { int index = directionToIndex(direction); if( index == -1 ) return; std::lock_guard<std::mutex> lockGuard(directionMutexes[x+y*Engine::WIDTH]); directions[x+y*Engine::WIDTH][directionToIndex(direction)] = false; } void FourDirectionMap::clearField(int x, int y) { for( int i=0; i<4; i++ ) directions[x+y*Engine::WIDTH][i] = false; } const int FourDirectionMap::getTilePosition(int x, int y) { bool left = checkDirection(x,y,LEFT); bool up = checkDirection(x,y,UP); bool down = checkDirection(x,y,DOWN); bool right = checkDirection(x,y,RIGHT); switch( left ) { case true: switch( up ) { case true: switch( down ) { case true: switch( right ) { case true: return 197; case false: return 180; } case false: switch( right ) { case true: return 193; case false: return 217; } } case false: switch( down ) { case true: switch ( right ) { case true: return 194; case false: return 191; } case false: switch( right ) { case true: return 196; case false: return 181; } } } case false: switch( up ) { case true: switch( down ) { case true: switch( right ) { case true: return 195; case false: return 179; } case false: switch( right ) { case true: return 192; case false: return 184; } } case false: switch( down ) { case true: switch ( right ) { case true: return 218; case false: return 183; } case false: switch( right ) { case true: return 182; case false: return 0; } } } } return 0; } void FourDirectionMap::render() { for (int x=0; x<engine.WIDTH; ++x) for (int y=0; y<engine.HEIGHT; ++y) { TCOD_console_set_char( NULL, x, y, getTilePosition(x,y) ); float greyValue = 255 * engine.getRootCharge(x,y); unsigned char greyVal = greyValue>255 ? 255 : (unsigned char) greyValue; TCOD_console_set_char_foreground( NULL , x, y, {greyVal,greyVal,greyVal} ); // DEBUG auto sources = engine.getRootSources(x,y); engine.lockRootSource(x,y); if( sources->begin() != sources->end() ) { int distance = sources->begin()->second; TCOD_console_set_char_background( NULL , x, y, {(unsigned char)(distance*30),0,0}, TCOD_BKGND_SET ); } engine.unlockRootSource(x,y); } } EightDirectionMap::EightDirectionMap() { clear(); } void EightDirectionMap::clear(){ for(int i=0; i<Engine::WIDTH*Engine::HEIGHT; i++) { for(int j=0; j<8; j++) directions[i][j] = false; } //std::fill(directions, directions+(Engine::WIDTH*Engine::HEIGHT)*8, false); } const int EightDirectionMap::directionToIndex(Direction direction) { return (int)direction - 1; } bool EightDirectionMap::checkDirection(int x, int y, Direction direction) { return directions[x+y*Engine::WIDTH][directionToIndex(direction)]; } void EightDirectionMap::addDirection(int x, int y, Direction direction) { directions[x+y*Engine::WIDTH][directionToIndex(direction)] = true; } void EightDirectionMap::removeDirection(int x, int y, Direction direction) { directions[x+y*Engine::WIDTH][directionToIndex(direction)] = false; }<file_sep>/src/Engine.cpp #include "main.hpp" #include <stdlib.h> /* rand */ #include <limits> #include <algorithm> #include <set> #include <iostream> #include <thread> Engine::Engine() : turn(0), lastKey(), gameStatus(RUNNING), structures() { TCODSystem::setFps(FPS); TCOD_console_set_custom_font("terminalAdapted16x16.png", 6, 16, 16); TCODConsole::initRoot(WIDTH, HEIGHT, "liquid_strategy prototype", false, TCOD_RENDERER_GLSL); players[0] = new Player( {0,255,0}, 0 ); players[1] = new Player( {255,0,0}, 1 ); players[2] = new Player( {255,255,0}, 2 ); players[3] = new Player( {0,0,255}, 3 ); colorMap = new ColorMap(); globalHeightMap = new HeightMap(100); rootDirections = new FourDirectionMap(); addCreature( new SolarTree(15,45) ); addCreature( new SolarTree(5,45) ); /* for( int x=1; x<WIDTH-1; ++x ) for( int y=1; y<HEIGHT-1; ++y ) globalHeightMap->setHeight(x,y,0); setPlayer(10,12,players[0]); setPlayer(50,25,players[1]); addStructure( new Spawner(10,12,players[0],0.2) ); addStructure( new Spawner(50,25,players[1],0.2) ); */ loadBitmap("risiko.bmp"); } Engine::~Engine() { for(int i=0;i<4;++i) delete players[i]; delete colorMap; delete globalHeightMap; delete rootDirections; for( auto it=structures.begin(); it!=structures.end(); it++ ) delete (*it); for( auto it=creatures.begin(); it!=creatures.end(); it++ ) delete (*it); } void Engine::addCreature(Creature* creature) { creatures.push_back(creature); } void Engine::removeCreature(Creature* creature) { for( auto it = creatures.begin(); it != creatures.end(); ++it ) { if( *it == creature ) { creatures.erase(it); delete creature; } } } void Engine::addStructure(Structure* structure) { structures.push_back(structure); } void Engine::removeStructure(Structure* structure) { for( auto it = structures.begin(); it != structures.end(); ++it ) { if( *it == structure ) { structures.erase(it); delete structure; } } } Player* Engine::getPlayer(int x, int y) const { return colorMap->getPlayer(x,y); } char Engine::getHeight(int x, int y) const { return colorMap->getHeight(x,y); } char Engine::getGlobalHeight(int x, int y) const { return globalHeightMap->getHeight(x,y); } char Engine::totalGroundHeight(int x, int y, const Player* player) const { char gh = globalHeightMap->getHeight(x,y); char ph = player->getHeight(x,y); int h = (ph>gh ? ph : gh) ; return h>CHAR_MAX ? CHAR_MAX : (char)h ; } char Engine::totalHeight(int x, int y, Player* player) const { char gh = globalHeightMap->getHeight(x,y); char ph = player->getHeight(x,y); int h = getHeight(x,y) + (ph>gh ? ph : gh) ; return h>CHAR_MAX ? CHAR_MAX : (char)h ; } void Engine::setField (int x, int y, Player* player, char height) { setPlayer(x,y,player); setHeight(x,y,height); } void Engine::setPlayer(int x, int y, Player* player) { colorMap->setPlayer(x,y,player); } void Engine::setHeight(int x, int y, char height) { colorMap->setHeight(x,y,height); } void Engine::setGlobalHeight(int x, int y, char height) { globalHeightMap->setHeight(x,y,height); } void Engine::clearLevel() { colorMap->clear(); globalHeightMap->clear(); for( auto it = structures.begin(); it != structures.end(); ++it ) { if( *it != NULL ) delete *it; } structures.clear(); } void Engine::loadBitmap(const char* filename) { int i; FILE* f = fopen(filename, "rb"); unsigned char info[54]; fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header // extract image height and width from header int width = *(int*)&info[18]; int height = *(int*)&info[22]; int size = 3 * width * height; unsigned char data[size]; // allocate 3 bytes per pixel fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once fclose(f); for(i = 0; i < size; i += 3) // switch color values because windows stores them in a funny way { unsigned char tmp = data[i]; data[i] = data[i+2]; data[i+2] = tmp; } // clear the world clearLevel(); // build the global HeightMap according to the bitmap for( int x=0; x<WIDTH; ++x ) for( int y=0; y<HEIGHT; ++y ) { unsigned char r = data[(3*(x+y*width))]; unsigned char g = data[(3*(x+y*width))+1]; unsigned char b = data[(3*(x+y*width))+2]; if( r == g && g == b ) { // if the bitmap is grey set height char height = r<CHAR_MAX ? r : CHAR_MAX; setGlobalHeight(x,y, height ); } else if ( r==255 && g==0 && b==0 ) { // if it's red place a spawner for player 1 addStructure( new Spawner(x,y,players[0]) ); } else if ( r==0 && g==255 && b==0 ) { // if it's green place a spawner for player 2 addStructure( new Spawner(x,y,players[1]) ); } else if ( r==255 && g==255 && b==0 ) { // if it's yellow place a spawner for player 3 addStructure( new Spawner(x,y,players[2]) ); } else if ( r==0 && g==0 && b==255 ) { // if it's blue place a spwaner for player 4 addStructure( new Spawner(x,y,players[3]) ); } else if ( r==100 && g==200 && b==255 ) { // free spawner addStructure( new Spawner(x,y,nullptr) ); } } } void Engine::changeHeight(int x, int y, char change) { colorMap->changeHeight(x,y,change); } char Engine::pumpAt(int x, int y, char amount, Player* pumpingPlayer) { return colorMap->pumpAt(x,y,amount,pumpingPlayer); } void Engine::fightBetween(int x1, int y1, int x2, int y2) { char height1 = getHeight(x1,y1); char height2 = getHeight(x2,y2); char die1 = rand() % (height1+1); char die2 = rand() % (height2+1); if( die2 > die1 ) { // field 2 wins setHeight(x1,y1,0); // field 1 loses all units moveColor(x2,y2,x1,y1, height2); // field 2 moves all units into field 1 } else if( die1 > die2 ) { // else field 1 wins setHeight(x2,y2,0); // field 2 loses all units moveColor(x1,y1,x2,y2, height1); // field 2 moves all units into field 1 } } void Engine::moveColor(int x0, int y0, int x_dest, int y_dest, char amount) { colorMap->moveColor(x0, y0, x_dest, y_dest, amount); } void Engine::update() { ++turn; /// FOR LATER for (int i=0; i<4; ++i) { players[i]->update(); } TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS, &lastKey, NULL); if (lastKey.vk == TCODK_ESCAPE) { gameStatus = EXIT; } for( auto it=structures.begin(); it!=structures.end(); ++it ) { (*it)->update(); } if( perSecond(CREATURE_UPDATES_PER_SECOND) ) { for( auto it=creatures.begin(); it!=creatures.end(); ++it ) { (*it)->update(); } } if( perSecond(20) ) { // let the liquids flow colorMap->update(); } } void Engine::render() { TCODConsole::root->clear(); globalHeightMap->render(); // render the world height rootDirections->render(); // render the roots colorMap->render(); // render the fluids for( auto it=structures.begin(); it!=structures.end(); ++it ) // render the structures (*it)->render(); for( auto it=creatures.begin(); it!=creatures.end(); ++it ) // render the creatures (*it)->render(); for (int i=0; i<4; ++i) { // render the cursors players[i]->render(); } } bool Engine::inMap(int x, int y) const { // returns whether a position is actually on the board return x >= 1 && x < WIDTH-1 && y >= 1 && y < HEIGHT-1; } bool Engine::perSecond(float repetitions) const { // returns true "repetitions" times per second if( repetitions > FPS ) return true; return turn % (unsigned int)(FPS/repetitions) == 0; } template <typename Map> bool key_compare (Map const *lhs, Map const *rhs) { return lhs->size() == rhs->size() && std::equal(lhs->begin(), lhs->end(), rhs->begin(), [] (auto a, auto b) { return a.first == b.first; }); // this line provides the comparision function for std::equal as a lambda expression } bool Engine::checkRootDirection(int x, int y, Direction direction) { return rootDirections->checkDirection( x, y, direction); } bool Engine::checkRootConnection(int x, int y, Direction direction) { int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, direction); return rootDirections->checkDirection( x, y, direction) && rootDirections->checkDirection( x+dx, y+dy, DirectionMap::opposingDirection(direction) ); } void Engine::addRootDirection(int x, int y, Direction direction) { std::thread rootAdditionThread(&Engine::addRootDirectionThread, this, x,y,direction); rootAdditionThread.detach(); } void Engine::addRootDirectionThread(int x, int y, Direction direction) { rootMutex.lock(); //std::cout << "rootMutex aquired\n"; if( !rootAllowed(x,y,direction) ) { rootMutex.unlock(); return; // check whether this new root would violate a law } rootDirections->addDirection( x, y, direction ); auto mySources = *getRootSources(x,y); int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, direction); auto otherSources = *getRootSources(x+dx,y+dy); for( auto it=mySources.begin(); it!=mySources.end(); it++ ) { // update the roots starting from your sources //std::cout << "spreading :"<< x <<","<< y <<"\n"; //std::thread threadHere(&Source::spreadFrom, (*it).first, x,y); //threadHere.detach(); (*it).first->spreadFrom(x,y); } for( auto it=otherSources.begin(); it!=otherSources.end(); it++ ) { // update the roots starting from the other's sources //std::cout << "spreading from other :"<< x+dx <<","<< y+dy <<"\n"; //std::thread threadThere(&Source::spreadFrom, (*it).first, x+dx,y+dy); //threadThere.detach(); (*it).first->spreadFrom(x+dx,y+dy); } rootMutex.unlock(); //std::cout << "rootMutex released\n"; } void Engine::removeRootDirection(int x, int y, Direction direction) { std::thread rootDeletionThread(&Engine::removeRootDirectionThread, this, x,y,direction); rootDeletionThread.detach(); } void Engine::removeRootDirectionThread(int x, int y, Direction direction) { rootMutex.lock(); rootDirections->removeDirection( x, y, direction); int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, direction); // because you just severed a connection auto mySources = *getRootSources(x,y); for( auto it=mySources.begin(); it!=mySources.end(); it++ ) { // update the roots starting from (*it).first->killFrom(x,y); // this field (*it).first->killFrom(x+dx,y+dy); // and the other } rootMutex.unlock(); } void Engine::clearRootField(int x, int y) { for( int i=0; i<ROOT_DIRECTIONS; i++ ) { Direction direction = rootIndexToDirection(i); removeRootDirection(x, y, direction); } } Direction Engine::rootIndexToDirection(int i) const { return rootDirections->indexToDirection(i); } std::map<Source*,int>* Engine::getRootSources(int x, int y) { return &rootSources[x+y*WIDTH]; } float Engine::getRootCharge(int x, int y) { float charge = 0; if( rootMutex.try_lock() ) { // try to access the holy rootSources-system auto sources = getRootSources(x,y); for( auto it=sources->begin(); it!=sources->end(); it++ ) // add the charges of all sources charge += (*it).first->getCharge(); rootMutex.unlock(); rootCharges[x+y*WIDTH] = charge; // set rootCharges, so you can re-read the value more easily later } else { // if you can't charge = getLastRootCharge(x,y); // just use the old charge } return charge; } float Engine::getLastRootCharge(int x, int y) const { return rootCharges[x+y*WIDTH]; } void Engine::rootIterationBegin(int* x_ptr, int* y_ptr) { // starts a search for connected roots at *x_ptr,*y_ptr std::fill(boolArray, boolArray+(WIDTH*HEIGHT), 0); boolArray[(*x_ptr)+(*y_ptr)*WIDTH] = true; indexArray[0] = (*x_ptr)+(*y_ptr)*WIDTH; currentIndex = 0; lastIndex = 0; { int i = 0; Direction currentDirection = rootDirections->indexToDirection(i); while( currentDirection != NEUTRAL ) { // go through all directions int dx = 0, dy = 0; DirectionMap::calcDxDy( &dx,&dy, currentDirection ); int index = (*x_ptr + dx) + (*y_ptr + dy)*WIDTH; if( !boolArray[index] && checkRootConnection( *x_ptr, *y_ptr, currentDirection) ) { // if there is an unfound connection add the connected field to the list indexArray[++lastIndex] = index; boolArray[index] = true; } currentDirection = rootDirections->indexToDirection(++i); } } currentIndex++; } void Engine::rootIterationNext(int* x_ptr, int* y_ptr) { // sets *x_ptr,*y_ptr to the next field in the search for connected roots // set the values if( currentIndex <= lastIndex ) { *x_ptr = indexArray[currentIndex] % WIDTH; *y_ptr = indexArray[currentIndex] / WIDTH; } else { *x_ptr = rootIterationEnd(); *y_ptr = rootIterationEnd(); } // search for more fields int x = indexArray[currentIndex] % WIDTH; int y = indexArray[currentIndex] / WIDTH; int i = 0; Direction currentDirection = rootDirections->indexToDirection(i); while( currentDirection != NEUTRAL ) { // go through all directions int dx = 0, dy = 0; DirectionMap::calcDxDy( &dx,&dy, currentDirection ); int index = (x + dx) + (y + dy)*WIDTH; if( !boolArray[index] && checkRootConnection( x, y, currentDirection) ) { // if there is an unfound connection add the connected field to the list indexArray[++lastIndex] = index; boolArray[index] = true; } currentDirection = rootDirections->indexToDirection(++i); } currentIndex++; } int Engine::rootIterationEnd() const { // returns -1 return -1; } Direction Engine::findRootNeighbour(int x, int y) const { int i = 0; Direction currentDirection = engine.rootIndexToDirection(i); while( currentDirection != NEUTRAL ) { // go through all directions if( engine.checkRootDirection( x, y, currentDirection) ) { // if you find a neighbour return the direction where your found him return currentDirection; } currentDirection = engine.rootIndexToDirection(++i); } return NEUTRAL; } bool Engine::rootAllowed(int x, int y, Direction direction) { int dx=0, dy=0; DirectionMap::calcDxDy(&dx,&dy, direction); if( checkRootDirection( x+dx, y+dy, DirectionMap::opposingDirection(direction) ) ) { // if this root would connect to a neighbour field // check whether these two fields have the same sources, if true they are already connected and the new root would form a circle (forbidden) lockRootSource(x,y); lockRootSource(x+dx,y+dy); bool allowed = !key_compare( getRootSources(x,y), getRootSources(x+dx,y+dy) ); // if they're different everything is fine unlockRootSource(x,y); unlockRootSource(x+dx,y+dy); return allowed; } return true; } void Engine::lockRootSource(int x, int y) { rootSourceMutex[x+y*WIDTH].lock(); } void Engine::unlockRootSource(int x, int y) { rootSourceMutex[x+y*WIDTH].unlock(); }<file_sep>/src/Player.hpp class Player { private: HeightMap heightMap; DirectionMap directionMap; Gamepad gamepad; float cursorX; float cursorY; enum ActionType { NONE, SHOW_HEIGHTMAP, SHOW_DIRECTIONMAP } action; bool wasPressedRB; // whether the shoulder-buttons have already been pressed in the last frame bool wasPressedLB; // brush stuff Brush brush; friend void Brush::renderHeightMap(int,int,const HeightMap*,const Player*) const; friend void Brush::renderDirectionMap(int,int,const DirectionMap*,const Player*) const; bool decreaseCursorOpacity; // to decrease the brush opacity during an action void changeBrushSize(float amount); void changeBrushHeight(char amount); void useDigBrush(); void useFillBrush(); void useDirectionBrush(char dx, char dy); public: TCOD_color_t col; Player(TCOD_color_t col, int cId); void update(); void render() const; // HeightMap void setHeight(int x, int y, char height); char getHeight(int x, int y) const; // DirectionMap void setDirection(int x, int y, Direction direction); Direction getDirection(int x, int y) const; };<file_sep>/src/Creature.hpp class Creature { protected: int x,y; public: Creature(int x, int y); virtual ~Creature() = default; virtual void update() = 0; virtual void render() const = 0; }; class Tree : public Creature { protected: static constexpr int STD_MAX_ROOT_LENGTH = 14; static constexpr int STD_MAX_ROOT_AMOUNT = 14*14; static constexpr char STD_FLUID_NEEDED_FOR_GROWTH = 2; static constexpr char STD_FLUID_NEEDED_FOR_ATTRACTION = 3; int maxRootLength = STD_MAX_ROOT_LENGTH; int maxRootAmount = STD_MAX_ROOT_AMOUNT; char fluidNeededForGrowth = STD_FLUID_NEEDED_FOR_GROWTH; char fluidNeededForAttraction = STD_FLUID_NEEDED_FOR_ATTRACTION; Source* source; void growRoot(); public: Tree(int x, int y); virtual ~Tree(); virtual void update() = 0; virtual void render() const = 0; }; class SolarTree : public Tree { private: static constexpr float STD_CHARGE_PRODUCTION = 0.1; float chargeProduction = STD_CHARGE_PRODUCTION; public: SolarTree(int x, int y, float chargeProduction=STD_CHARGE_PRODUCTION); virtual ~SolarTree(); void update(); void render() const; }; class Seed : Creature { };<file_sep>/makefile SOURCES=$(wildcard src/*.cpp) OBJS=$(SOURCES:.cpp=.o) ifeq ($(shell sh -c 'uname -s'),Linux) LIBFLAGS=-L. -ltcod_debug -ltcodxx_debug -Wl,-rpath=. -lxinput9_1_0 else LIBFLAGS=-Llib -ltcod -static-libgcc -static-libstdc++ -mwindows -lxinput9_1_0 endif liquid : $(OBJS) g++ $(OBJS) -o liquid -Wall $(LIBFLAGS) -g src/main.hpp.gch : src/*.hpp g++ src/main.hpp -Iinclude -Wall src/%.o : src/%.cpp src/main.hpp.gch g++ $< -c -o $@ -Iinclude -Wall -g<file_sep>/src/XInput.hpp #include <Windows.h> #include <Xinput.h> class Gamepad { private: int cId; XINPUT_STATE state; float deadzoneX; float deadzoneY; std::chrono::steady_clock::time_point lastPressed[10]; public: Gamepad() : cId(), deadzoneX(0.1f), deadzoneY(0.1f) { for( int i=0; i<10; ++i ) lastPressed[i] = std::chrono::steady_clock::now(); } Gamepad(int cId, float dzX, float dzY) : cId(cId), deadzoneX(dzX), deadzoneY(dzY) { for( int i=0; i<10; ++i ) lastPressed[i] = std::chrono::steady_clock::now(); } float leftStickX; float leftStickY; float rightStickX; float rightStickY; float leftTrigger; float rightTrigger; int GetPort(); XINPUT_GAMEPAD *GetState(); bool CheckConnection(); bool Refresh(); bool IsPressed(WORD); bool IsPressed(WORD,double cooldown); };<file_sep>/src/Source.cpp #include "main.hpp" #include <iostream> unsigned int Source::lastIndex = 0; // the last index to check within indexArray unsigned int Source::indexArray[Engine::WIDTH*Engine::HEIGHT] = { 0 }; // holds the indices of fields to be checked bool Source::boolArray [Engine::WIDTH*Engine::HEIGHT] = {}; // tells whether a field has been checked already Source::Source(int x, int y) : x(x), y(y), charge(0) { // add yourself to the list of sources on your field addMyPairTo(x,y,0); // create roots into all directions for( int i=0; i<engine.ROOT_DIRECTIONS; i++ ) { engine.addRootDirection(x,y,engine.rootIndexToDirection(i)); } } void Source::increaseCharge(float amount) { charge += amount; } void Source::decreaseCharge(float amount) { charge -= amount; if( charge < 0 ) charge = 0; } void Source::resetCharge() { charge = 0; } float Source::getCharge() const { return charge; } void Source::setToPosition(int* x_ptr, int* y_ptr) { *x_ptr = x; *y_ptr = y; } void Source::spreadFrom(int x, int y) { // find all fields with roots that you are connected to and add yourself to the sources listed there // while doing so, document the distance of the field to you and only spread further into fields that are further away std::fill(boolArray, boolArray+(Engine::WIDTH*Engine::HEIGHT), 0); boolArray[x+y*Engine::WIDTH] = true; indexArray[0] = x+y*Engine::WIDTH; lastIndex = 0; spread(); } void Source::killFrom(int xStart, int yStart) { // find all fields with roots that you are connected to and delete yourself from the sources listed there // while doing so, only spread further into fields that are further away std::fill(boolArray, boolArray+(Engine::WIDTH*Engine::HEIGHT), 0); boolArray[xStart+yStart*Engine::WIDTH] = true; indexArray[0] = xStart+yStart*Engine::WIDTH; lastIndex = 0; for( unsigned int currentIndex=0; currentIndex <= lastIndex; currentIndex++ ) { // find your pair<Source*,int> int x0 = indexArray[currentIndex] % Engine::WIDTH; int y0 = indexArray[currentIndex] / Engine::WIDTH; int* myDistance = myDistanceAt(x0,y0); bool stillConnected = false; // whether or not to delete this source from the current field if( myDistance==NULL ) // you're not there... so you can't spread from there continue; else { // if you're there add all neighbours that are further away int distance = *myDistance; for( int i=0; i<engine.ROOT_DIRECTIONS; i++ ) { Direction direction = engine.rootIndexToDirection(i); // check all directions int dx=0,dy=0; DirectionMap::calcDxDy(&dx,&dy,direction); int index = (x0+dx)+(y0+dy)*Engine::WIDTH; if( !boolArray[index] && engine.checkRootConnection(x0,y0,direction) ) { // if there is a connection to that field boolArray[index] = true; int* myDistanceThere = myDistanceAt(x0+dx,y0+dy); if( myDistanceThere ) { // check if you have a pair there if( *myDistanceThere > distance ) { // if the distance increases indexArray[++lastIndex] = index; // add the field to the killList } else { // if the distance doesn't increase in that direction you've just found an edge stillConnected = true; // then you yourself are still connected, so remember to not kill yourself please } } } } } if( stillConnected ) break; deleteMyPairAt(x0,y0); // delete your pair there } // make sure you didn't delete the true source by accident if( xStart == this->x && yStart == this->y ) addMyPairTo(xStart,yStart,0); } void Source::spread() { // find all fields with roots that you are connected to and add yourself to the sources listed there // while doing so, document the distance of the field to you and only spread further into fields that are further away for( unsigned int currentIndex=0; currentIndex <= lastIndex; currentIndex++ ) { // find your pair<Source*,int> int x0 = indexArray[currentIndex] % Engine::WIDTH; int y0 = indexArray[currentIndex] / Engine::WIDTH; //std::cout << "checking distance at :"<< x0 <<","<< y0 <<"\n"; int* myDistance = myDistanceAt(x0,y0); if( myDistance==NULL ) // you're not there... so you can't spread from there continue; else { // if you're there add all neighbours that are further away //std::cout << "really spreading\n"; int distance = *myDistance; for( int i=0; i<engine.ROOT_DIRECTIONS; i++ ) { Direction direction = engine.rootIndexToDirection(i); // check all directions int dx=0,dy=0; DirectionMap::calcDxDy(&dx,&dy,direction); int index = (x0+dx)+(y0+dy)*Engine::WIDTH; if( !boolArray[index] && engine.checkRootConnection(x0,y0,direction) ) { // if there is a connection to that field int* myDistanceThere = myDistanceAt(x0+dx,y0+dy); if( myDistanceThere ) { // check if you already have a pair there if( *myDistanceThere > distance ) { // if the distance increases *myDistanceThere = distance+1; // make sure the distance isn't too high // add the field to the list indexArray[++lastIndex] = index; boolArray[index] = true; } else // will only be interesting for killFrom continue; } else { // if you don't have a pair there addMyPairTo(x0+dx,y0+dy,distance+1); // add a pair of yours // add the field to the list indexArray[++lastIndex] = index; boolArray[index] = true; } } } } } } void Source::deleteMyPairAt(int x, int y) { engine.lockRootSource(x,y); //std::cout << "rootSource locked in deletePair\n"; engine.getRootSources(x,y)->erase(this); engine.unlockRootSource(x,y); //std::cout << "rootSource released in deletePair\n"; } void Source::addMyPairTo(int x, int y, int distance) { engine.lockRootSource(x,y); //std::cout << "rootSource locked in addPair\n"; engine.getRootSources(x,y)->insert({this,distance}); engine.unlockRootSource(x,y); //std::cout << "rootSource released in addPair\n"; } int* Source::myDistanceAt(int x0, int y0) { try { engine.lockRootSource(x,y); //std::cout << "rootSource locked in DistanceAt\n"; int* distance = &(engine.getRootSources(x0,y0)->at(this)); engine.unlockRootSource(x,y); //std::cout << "rootSource unlocked in DistanceAt\n"; return distance; } catch (std::out_of_range const & ex) { //std::cout << "no distance\n"; engine.unlockRootSource(x,y); //std::cout << "rootSource unlocked in DistanceAt\n"; return NULL; } }<file_sep>/src/Brush.cpp #include "main.hpp" #include <algorithm> #include <cmath> Brush::Brush() : radius(0), height(Engine::DEPTH) { calcBrush(); } void Brush::changeSize(float amount) { radius += amount; if( radius > MAX_BRUSH_RADIUS ) radius = MAX_BRUSH_RADIUS; else if( radius < 0 ) radius = 0; calcBrush(); } void Brush::changeHeight(char amount) { height += amount; if( height > Engine::DEPTH ) height = Engine::DEPTH; else if( height < 0 ) height = 0; calcBrush(); } void Brush::calcBrush() { // delete the old brush std::fill(*brushArray, *brushArray+((int)MAX_BRUSH_RADIUS*2+1*(int)MAX_BRUSH_RADIUS*2+1), 0); // calculate the shape of the brush-head for( int x = -(int)radius; x <= (int)(radius); ++x ) for( int y = -(int)radius; y <= (int)(radius); ++y ) { double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > radius ) continue; // if it's larger than the allowed radius -> skip // else calc the height of the brush at this point if( radius != 0.0 ) brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX] = (char)((1.0 - distance/radius) * (float)height); else brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX] = height; } } double Brush::radiusCondition() const { double condition; condition = radius-1; if( condition < 0 ) condition = 0; return condition; } void Brush::digAt(int xCenter, int yCenter, Player* player) { double condition = radiusCondition(); // go through all fields inside the set radius for( int x = -(int)radius; x <= (int)(radius); ++x ) for( int y = -(int)radius; y <= (int)(radius); ++y ) { //if(brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX]==0) continue; int xPos = xCenter+x; int yPos = yCenter+y; if( engine.inMap(xPos,yPos) == false ) continue;// if the field isn't on the board -> skip double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > condition ) continue; // if it's larger than the allowed radius -> skip // else lower the height of the player's heightmap according to the brush char heightHere = Engine::DEPTH - height ; if( player->getHeight(xCenter+x, yCenter+y) > heightHere ) // but only if it's higher than it should be player->setHeight( xCenter+x, yCenter+y, heightHere ); } } void Brush::fillAt(int xCenter, int yCenter, Player* player) { double condition = radiusCondition(); // go through all fields inside the set radius for( int x = -(int)radius; x <= (int)(radius); ++x ) for( int y = -(int)radius; y <= (int)(radius); ++y ) { //if(brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX]==0) continue; int xPos = xCenter+x; int yPos = yCenter+y; if( engine.inMap(xPos,yPos) == false ) continue;// if the field isn't on the board -> skip double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > condition ) continue; // if it's larger than the allowed radius -> skip // else raise the height of the player's heightmap according to the brush char heightHere = height; if( player->getHeight(xCenter+x, yCenter+y) < heightHere ) // but only if it's lower than it should be player->setHeight( xCenter+x, yCenter+y, heightHere ); } } void Brush::setDirection(int xCenter, int yCenter, Player* player, Direction direction) { double condition = radiusCondition(); // go through all fields inside the set radius for( int x = -(int)radius; x <= (int)(radius); ++x ) for( int y = -(int)radius; y <= (int)(radius); ++y ) { int xPos = xCenter+x; int yPos = yCenter+y; if( engine.inMap(xPos,yPos) == false ) continue;// if the field isn't on the board -> skip double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > condition ) continue; // if it's larger than the allowed radius -> skip // else set the direction on this field player->setDirection(xPos,yPos, direction); /* //engine.removeRootDirection(xPos,yPos, direction); if( direction == NEUTRAL ) engine.clearRootField(xPos,yPos); */ } } void Brush::render( int xCenter, int yCenter, bool decreaseCursorOpacity ) const { TCOD_color_t color = (decreaseCursorOpacity ? TCOD_color_t{100,100,100} : TCOD_color_t{170,170,170}); double condition = radiusCondition(); // go through all fields inside the set radius for( int x = -(int)radius; x <= (int)(radius); ++x ) for( int y = -(int)radius; y <= (int)(radius); ++y ) { //if(brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX]==0) continue; int xPos = xCenter+x; int yPos = yCenter+y; if( engine.inMap(xPos,yPos) == false ) continue;// if the field isn't on the board -> skip double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > condition ) continue; // if it's larger than the allowed radius -> skip // else draw the height TCOD_console_set_char_background( NULL , xPos, yPos, TCOD_color_multiply_scalar( color, (float)height/(float)Engine::DEPTH ), TCOD_BKGND_ADD); } TCOD_console_set_char( NULL, xCenter, yCenter, height+48 ); TCOD_console_set_char_foreground( NULL , xCenter, yCenter, TCOD_color_multiply_scalar(color,1.7) ); } void Brush::renderHeightMap( int xCenter, int yCenter, const HeightMap* heightMap, const Player* player ) const { TCOD_color_t white = TCOD_color_t{255,255,255}; // go through all fields inside the set radius for( int x = -(int)MAX_BRUSH_RADIUS; x <= (int)(MAX_BRUSH_RADIUS); ++x ) for( int y = -(int)MAX_BRUSH_RADIUS; y <= (int)(MAX_BRUSH_RADIUS); ++y ) { //if(brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX]==0) continue; int xPos = xCenter+x; int yPos = yCenter+y; if( engine.inMap(xPos,yPos) == false ) continue; // if the field isn't on the board -> skip double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > MAX_BRUSH_RADIUS-1 ) continue; // if it's larger than the allowed radius -> skip // else draw the height TCOD_console_set_char_background( NULL , xPos, yPos, TCOD_color_lerp( TCOD_console_get_char_background(NULL,xPos,yPos), TCOD_color_multiply_scalar( white, ( (float)engine.totalGroundHeight(xPos,yPos,player) )/(float)Engine::DEPTH), 0.8), TCOD_BKGND_SET ); if( distance <= radiusCondition() ) { // also draw the brush radius with colored dots TCOD_console_set_char( NULL, xPos, yPos, '.' ); TCOD_console_set_char_foreground( NULL , xPos, yPos, player->col ); } } TCOD_console_set_char( NULL, xCenter, yCenter, height+48 ); TCOD_console_set_char_foreground( NULL , xCenter, yCenter, player->col ); } void Brush::renderDirectionMap( int xCenter, int yCenter, const DirectionMap* directionMap, const Player* player ) const { // go through all fields inside the set radius for( int x = -(int)MAX_BRUSH_RADIUS; x <= (int)(MAX_BRUSH_RADIUS); ++x ) for( int y = -(int)MAX_BRUSH_RADIUS; y <= (int)(MAX_BRUSH_RADIUS); ++y ) { //if(brushArray[x+BRUSH_CENTER_INDEX][y+BRUSH_CENTER_INDEX]==0) continue; int xPos = xCenter+x; int yPos = yCenter+y; if( engine.inMap(xPos,yPos) == false ) continue; // if the field isn't on the board -> skip double distance = sqrt( pow(x,2) + pow(y,2) ); // calc the distance to the center if( distance > MAX_BRUSH_RADIUS-1 ) continue; // if it's larger than the allowed radius -> skip // else draw the direction TCOD_console_set_char( NULL, xPos, yPos, DirectionMap::getTilePosition( directionMap->getDirection(xPos,yPos) ) ); TCOD_console_set_char_foreground( NULL , xPos, yPos, player->col ); TCOD_console_set_char_background( NULL , xPos, yPos, TCOD_color_multiply_scalar( TCOD_console_get_char_background(NULL,xPos,yPos), 0.5), TCOD_BKGND_SET ); if( distance <= radiusCondition() ) { // also draw the brush radius with colored fields TCOD_console_set_char_background( NULL , xPos, yPos, TCOD_color_multiply_scalar(player->col,0.3), TCOD_BKGND_ADD ); } } }
6c9a2f5326e650f6a5409f44eced96af94cc6ed8
[ "Markdown", "Makefile", "C++" ]
21
C++
PSteinhaus/Liquid-Game
cec82210e5dd708fc9961f7232fde87098d8334b
a3501ecfaa86737ffab56d60d2f8fb4b4435562e
refs/heads/main
<repo_name>PelumiOgunwole/Finance-App<file_sep>/FinApp.py from kivy.lang import Builder from kivymd.app import MDApp from kivymd.uix.screen import MDScreen from kivy.uix.screenmanager import ScreenManager,Screen from kivymd.uix.menu import MDDropdownMenu from kivy.properties import ObjectProperty from kivy.properties import StringProperty,ListProperty import sqlite3 from datetime import datetime from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.properties import BooleanProperty from kivymd.uix.datatables import MDDataTable from kivy.uix.popup import Popup from kivy.uix.recyclegridlayout import RecycleGridLayout from kivy.uix.button import Button from kivymd.uix.tab import MDTabsBase from kivymd.font_definitions import fonts from kivymd.icon_definitions import md_icons month="" from kivymd.uix.relativelayout import RelativeLayout from kivymd.uix.floatlayout import MDFloatLayout from kivymd.uix.relativelayout import MDRelativeLayout class TextInputPopup(Popup): obj = ObjectProperty(None) obj_text = StringProperty("") def __init__(self, obj, **kwargs): super(TextInputPopup, self).__init__(**kwargs) self.obj = obj self.obj_text = obj.text class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior, RecycleGridLayout): ''' Adds selection and focus behaviour to the view. ''' class SelectableButton(RecycleDataViewBehavior, Button): ''' Add selection support to the Button ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = index return super(SelectableButton, self).refresh_view_attrs(rv, index, data) def on_touch_down(self, touch): ''' Add selection on touch down ''' if super(SelectableButton, self).on_touch_down(touch): return True if self.collide_point(*touch.pos) and self.selectable: return self.parent.select_with_touch(self.index, touch) def apply_selection(self, rv, index, is_selected): ''' Respond to the selection of items in the view. ''' self.selected = is_selected def on_press(self): popup = TextInputPopup(self) popup.open() def update_changes(self, txt): self.text = txt class Page_One(MDScreen): def __init__(self,**kwargs): super().__init__(**kwargs) dropdown=ObjectProperty() def Income_Page(self): pass class Page_Two(MDScreen,MDTabsBase): dropdown = ObjectProperty() amount= StringProperty() description = StringProperty data_items1 = ListProperty([]) def __init__(self, **kwargs): super(Page_Two, self).__init__(**kwargs) #self.show_income_items() try: # Create Database Connection Inc_con = sqlite3.connect("Income.db") Inc_cur = Inc_con.cursor() Inc_cur.execute("""CREATE TABLE IF NOT EXISTS income(id INTEGER PRIMARY KEY autoincrement,Month text CHECK(Month!=""),Source text CHECK(Source!=""),Amount REAL CHECK(Amount!="")) """) Inc_con.commit() Inc_con.close() except sqlite3.IntegrityError: print("Field shouldnt be blank") def insert_data(self): try: current_month= self.m() print(current_month) Inc_con = sqlite3.connect("Income.db") Inc_cur = Inc_con.cursor() Inc_cur.execute("""INSERT INTO income(id,Month,Source,Amount) VALUES(NULL,?,?,?)""",(current_month,self.description,self.amount)) Inc_con.commit() except sqlite3.IntegrityError: print("Field shouldn't be blank") def show_income_items(self,*args): current_month = self.m() Inc_con = sqlite3.connect("Income.db") Inc_cur = Inc_con.cursor() Inc_cur.execute("SELECT * from income WHERE Month=?",(current_month,)) rows = Inc_cur.fetchall() for row in rows: for col in row: self.data_items1.append(col) def get_time(self): global x x=StringProperty() x= datetime.today().strftime("%Y") return x def on_kv_post(self, base_widget): caller = self.ids.caller # This is the MDDropdDownitem from the kivy file months=["January","February","March","April","May","June","July","August","September","October","November","December"] menu_items = [{"viewclass": "MDMenuItem","icon": "calendar", "text": f" {i}"} for i in months] self.dropdown = MDDropdownMenu(caller=caller, items=menu_items, width_mult=4) self.dropdown.bind(on_release=self.set_item) self.dropdown.bind(on_release=self.show_income_items) # Make Database Popup once month is selected def set_item(self, instance_menu, instance_menu_item): # Function meant to get value of month selected in dropdown global month month = instance_menu_item.text a=self.ids.caller.set_item(instance_menu_item.text) instance_menu.dismiss() return month def m(self): l=month return l class Tab(MDFloatLayout,MDTabsBase): pass class Page_Three(MDScreen,MDFloatLayout): def __init__(self,**kwargs): super().__init__(**kwargs) class Page_Four(MDScreen): def __init__(self,**kwargs): super().__init__(**kwargs) class ScreenManage(ScreenManager): pass class MainApp(MDApp): def build(self): self.kv = Builder.load_file("fin.kv") title = "Financial Mobile App" return self.kv def on_start(self): #self.kv.get_screen("Income").ids.tabs.add_widget(Tab(text="Camera")) pass def on_tab_switch( self, instance_tabs, instance_tab, instance_tab_label, tab_text ): '''Called when switching tabs. :type instance_tabs: <kivymd.uix.tab.MDTabs object>; :param instance_tab: <__main__.Tab object>; :param instance_tab_label: <kivymd.uix.tab.MDTabsLabel object>; :param tab_text: text or name icon of tab; ''' instance_tab.ids.budgets.text = tab_text if __name__ == "__main__": MainApp().run()<file_sep>/README.md # Finance-App This app is being built using python and KivyMD
53ebee1a61b6f127801ae4127e88774e2eac86e2
[ "Markdown", "Python" ]
2
Python
PelumiOgunwole/Finance-App
5cbb11494c4e71350a42ecd65ff35343bcbda6e5
31af05b3096d38fb89fb0c68911218f05d71e72a
refs/heads/master
<repo_name>noracosta/stocksud<file_sep>/creditos_guardar.php <?php require_once('Connections/config.php'); ?> <?php require_once('Connections/config2.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php require("class.phpmailer.php"); function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_config, $config); $query_mails = "SELECT * FROM slc_stocksud_mail WHERE idmail = 1"; $mails = mysql_query($query_mails, $config) or die(mysql_error()); $row_mails = mysql_fetch_assoc($mails); $totalRows_mails = mysql_num_rows($mails); if ((isset($_POST["MM_update_row"])) && ($_POST["MM_update_row"] == "formGuardar")) { if($_POST['stockreserva'] == '1'){ $colname_stock = $_POST['id']; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idestado1, idestado2, idestado3, importeaprobado, idSolicitud, slc_stocksud_usuario.mail FROM slc_stocksud_stock LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_stock.idvendedor WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if((($_POST['idestado1'] != '0') && ($row_stock['idestado1'] <> $_POST['idestado1'])) || (($_POST['idestado2'] != '') && ($row_stock['idestado2'] <> $_POST['idestado2'])) || (($_POST['idestado3'] != '') && ($row_stock['idestado3'] <> $_POST['idestado3']))){ if(($_POST['idestado1'] != '') && ($row_stock['idestado1'] <> $_POST['idestado1'])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado1, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado1'], "int"), GetSQLValueString($_POST['id'], "int"), GetSQLValueString('1', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_estado = $row_stock['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1anterior = $row_estado['estado']; $colname_estado = $_POST['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo2 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 16px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 14px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo2">'; $cuerpo .= '<p><img src="'. $relative_path . 'img/presupuesto_logo_VW.jpg"/></p>'; $cuerpo .= '<strong>MODIFICACION DE ESTADO DE CREDITO</strong><br>'; $cuerpo .= '</div>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>CLIENTE: </strong>'; $cuerpo .= $_POST['cliente'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODELO: </strong>'; $cuerpo .= $_POST['modelo'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VIN: </strong>'; $cuerpo .= $_POST['vin']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VENDEDOR: </strong>'; $cuerpo .= $_POST['vendedor']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODIFICACIONES: </strong>'; $cuerpo .= 'Estado 1: '; $cuerpo .= $estado1nuevo; $cuerpo .= ' Importe aprobado: '; $cuerpo .= $_POST['importeaprobado']. "</div>"; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>OBSERVACIONES: </strong>'; $cuerpo .= $_POST['comentario1']. "</div>"; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $to = explode(";",$row_mails['credito']); for($i=0;$i<count($to);$i++){ $mail->AddAddress(trim($to[$i])); } $mail->Subject = 'CREDITO: ' . $_POST['cliente']; $mail->Body = $cuerpo; $mail->Send(); } if(($_POST['idestado2'] != '') && ($row_stock['idestado2'] <> $_POST['idestado2'])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado2, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado2'], "int"), GetSQLValueString($_POST['id'], "int"), GetSQLValueString('1', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_estado = $row_stock['idestado2']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito2 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2anterior = $row_estado['estado']; $colname_estado = $_POST['idestado2']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito2 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo2 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 16px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 14px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo2">'; $cuerpo .= '<p><img src="'. $relative_path . 'img/presupuesto_logo_VW.jpg"/></p>'; $cuerpo .= '<strong>MODIFICACION DE ESTADO DE CREDITO</strong><br>'; $cuerpo .= '</div>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>CLIENTE: </strong>'; $cuerpo .= $_POST['cliente'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODELO: </strong>'; $cuerpo .= $_POST['modelo'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VIN: </strong>'; $cuerpo .= $_POST['vin']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VENDEDOR: </strong>'; $cuerpo .= $_POST['vendedor']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODIFICACIONES: </strong>'; $cuerpo .= 'Estado 2: '; $cuerpo .= $estado2nuevo; $cuerpo .= ' Importe aprobado: '; $cuerpo .= $_POST['importeaprobado']. "</div>"; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>OBSERVACIONES: </strong>'; $cuerpo .= $_POST['comentario2']. "</div>"; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $to = explode(";",$row_mails['credito']); for($i=0;$i<count($to);$i++){ $mail->AddAddress(trim($to[$i])); } $mail->Subject = 'CREDITO: ' . $_POST['cliente']; $mail->Body = $cuerpo; $mail->Send(); } if(($_POST['idestado3'] != '0') && ($row_stock['idestado3'] <> $_POST['idestado3'])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado3, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado3'], "int"), GetSQLValueString($_POST['id'], "int"), GetSQLValueString('1', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_estado = $row_stock['idestado3']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito3 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3anterior = $row_estado['estado']; $colname_estado = $_POST['idestado3']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito3 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo2 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 16px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 14px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo2">'; $cuerpo .= '<p><img src="'. $relative_path . 'img/presupuesto_logo_VW.jpg"/></p>'; $cuerpo .= '<strong>MODIFICACION DE ESTADO DE CREDITO</strong><br>'; $cuerpo .= '</div>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>CLIENTE: </strong>'; $cuerpo .= $_POST['cliente'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODELO: </strong>'; $cuerpo .= $_POST['modelo'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VIN: </strong>'; $cuerpo .= $_POST['vin']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VENDEDOR: </strong>'; $cuerpo .= $_POST['vendedor']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODIFICACIONES: </strong>'; $cuerpo .= 'Estado 3: '; $cuerpo .= $estado3nuevo; $cuerpo .= ' Importe aprobado: '; $cuerpo .= $_POST['importeaprobado']. "</div>"; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>OBSERVACIONES: </strong>'; $cuerpo .= $_POST['comentario3']. "</div>"; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $to = explode(";",$row_mails['credito']); for($i=0;$i<count($to);$i++){ $mail->AddAddress(trim($to[$i])); } $mail->Subject = 'CREDITO: ' . $_POST['cliente']; $mail->Body = $cuerpo; $mail->Send(); } } $updateSQL = sprintf("UPDATE slc_stocksud_stock SET importeaprobado=%s, idestado1=%s, comentario1=%s, idestado2=%s, comentario2=%s, idestado3=%s, comentario3=%s, estadocivil=%s, condominio=%s, profesion=%s, idbanco=%s, idcuota=%s WHERE idstock=%s", GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado1'], "int"), GetSQLValueString($_POST['comentario1'], "text"), GetSQLValueString($_POST['idestado2'], "int"), GetSQLValueString($_POST['comentario2'], "text"), GetSQLValueString($_POST['idestado3'], "int"), GetSQLValueString($_POST['comentario3'], "text"), GetSQLValueString($_POST['estadocivil'], "text"), GetSQLValueString($_POST['condominio'], "int"), GetSQLValueString($_POST['profesion'], "text"), GetSQLValueString($_POST['idbanco'], "text"), GetSQLValueString($_POST['idcuota'], "text"), GetSQLValueString($_POST['id'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); mysql_select_db($database_config, $config); $query_banco = sprintf("SELECT banco FROM slc_stocksud_banco WHERE idbanco = %s ", GetSQLValueString($_POST['idbanco'], "int")); $banco = mysql_query($query_banco, $config) or die(mysql_error()); $row_banco = mysql_fetch_assoc($banco); $totalRows_banco = mysql_num_rows($banco); mysql_select_db($database_config2, $config2); $query_banco2 = sprintf("SELECT idbanco FROM slc_banco WHERE banco LIKE %s ", GetSQLValueString($row_banco['banco'], "text")); $banco2 = mysql_query($query_banco2, $config2) or die(mysql_error()); $row_banco2 = mysql_fetch_assoc($banco2); $totalRows_banco2 = mysql_num_rows($banco2); mysql_select_db($database_config, $config); $query_cantcuotas = sprintf("SELECT cuota FROM slc_stocksud_cuota WHERE idcuota = %s ", GetSQLValueString($_POST['idcuota'], "int")); $cantcuotas = mysql_query($query_cantcuotas, $config) or die(mysql_error()); $row_cantcuotas = mysql_fetch_assoc($cantcuotas); $totalRows_cantcuotas = mysql_num_rows($cantcuotas); mysql_select_db($database_config2, $config2); $query_cantcuotas2 = sprintf("SELECT idCantidadcuotas FROM slc_cantidadcuotas WHERE cantidadcuotas LIKE %s ", GetSQLValueString($row_cantcuotas['cuota'], "text")); $cantcuotas2 = mysql_query($query_cantcuotas2, $config2) or die(mysql_error()); $row_cantcuotas2 = mysql_fetch_assoc($cantcuotas2); $totalRows_cantcuotas2 = mysql_num_rows($cantcuotas2); $updateSQL = sprintf("UPDATE slc_solicitudformapago SET creditoidbanco=%s, creditoidcantidadcuotas=%s WHERE idSolicitud = %s AND formapago = 'credito'", GetSQLValueString($row_banco2['idbanco'], "int"), GetSQLValueString($row_cantcuotas2['idCantidadcuotas'], "int"), GetSQLValueString($row_stock['idSolicitud'], "int")); mysql_select_db($database_config2, $config2); $Result1 = mysql_query($updateSQL, $config2) or die(mysql_error()); } elseif($_POST['stockreserva'] == '2') { $colname_stock = $_POST['id']; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idestado1, idestado2, idestado3, importeaprobado, idSolicitud, slc_stocksud_usuario.mail FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_reserva.idvendedor WHERE idreserva = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if((($_POST['idestado1'] != '') && ($row_stock['idestado1'] <> $_POST['idestado1'])) || (($_POST['idestado2'] != '') && ($row_stock['idestado2'] <> $_POST['idestado2'])) || (($_POST['idestado3'] != '') && ($row_stock['idestado3'] <> $_POST['idestado3']))){ if(($_POST['idestado1'] != '') && ($row_stock['idestado1'] <> $_POST['idestado1'])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado1, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado1'], "int"), GetSQLValueString($_POST['id'], "int"), GetSQLValueString('2', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_estado = $row_stock['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1anterior = $row_estado['estado']; $colname_estado = $_POST['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo2 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 16px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 14px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo2">'; $cuerpo .= '<p><img src="'. $relative_path . 'img/presupuesto_logo_VW.jpg"/></p>'; $cuerpo .= '<strong>MODIFICACION DE ESTADO DE CREDITO</strong><br>'; $cuerpo .= '</div>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>CLIENTE: </strong>'; $cuerpo .= $_POST['cliente'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODELO: </strong>'; $cuerpo .= $_POST['modelo'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VIN: </strong>'; $cuerpo .= $_POST['vin']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VENDEDOR: </strong>'; $cuerpo .= $_POST['vendedor']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODIFICACIONES: </strong>'; $cuerpo .= 'Estado 1: '; $cuerpo .= $estado1nuevo; $cuerpo .= ' Importe aprobado: '; $cuerpo .= $_POST['importeaprobado']. "</div>"; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>OBSERVACIONES: </strong>'; $cuerpo .= $_POST['comentario1']. "</div>"; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $to = explode(";",$row_mails['credito']); for($i=0;$i<count($to);$i++){ $mail->AddAddress(trim($to[$i])); } $mail->Subject = 'CREDITO: ' . $_POST['cliente']; $mail->Body = $cuerpo; $mail->Send(); } if(($_POST['idestado2'] != '') && ($row_stock['idestado2'] <> $_POST['idestado2'])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado2, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado2'], "int"), GetSQLValueString($_POST['id'], "int"), GetSQLValueString('2', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_estado = $row_stock['idestado2']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito2 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2anterior = $row_estado['estado']; $colname_estado = $_POST['idestado2']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito2 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo2 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 16px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 14px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo2">'; $cuerpo .= '<p><img src="'. $relative_path . 'img/presupuesto_logo_VW.jpg"/></p>'; $cuerpo .= '<strong>MODIFICACION DE ESTADO DE CREDITO</strong><br>'; $cuerpo .= '</div>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>CLIENTE: </strong>'; $cuerpo .= $_POST['cliente'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODELO: </strong>'; $cuerpo .= $_POST['modelo'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VIN: </strong>'; $cuerpo .= $_POST['vin']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VENDEDOR: </strong>'; $cuerpo .= $_POST['vendedor']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODIFICACIONES: </strong>'; $cuerpo .= 'Estado 2: '; $cuerpo .= $estado2nuevo; $cuerpo .= ' Importe aprobado: '; $cuerpo .= $_POST['importeaprobado']. "</div>"; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>OBSERVACIONES: </strong>'; $cuerpo .= $_POST['comentario2']. "</div>"; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $to = explode(";",$row_mails['credito']); for($i=0;$i<count($to);$i++){ $mail->AddAddress(trim($to[$i])); } $mail->Subject = 'CREDITO: ' . $_POST['cliente']; $mail->Body = $cuerpo; $mail->Send(); } if(($_POST['idestado3'] != '') && ($row_stock['idestado3'] <> $_POST['idestado3'])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado3, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado3'], "int"), GetSQLValueString($_POST['id'], "int"), GetSQLValueString('2', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_estado = $row_stock['idestado3']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito3 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3anterior = $row_estado['estado']; $colname_estado = $_POST['idestado3']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito3 WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo2 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 16px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 14px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo2">'; $cuerpo .= '<p><img src="'. $relative_path . 'img/presupuesto_logo_VW.jpg"/></p>'; $cuerpo .= '<strong>MODIFICACION DE ESTADO DE CREDITO</strong><br>'; $cuerpo .= '</div>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>CLIENTE: </strong>'; $cuerpo .= $_POST['cliente'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODELO: </strong>'; $cuerpo .= $_POST['modelo'] . "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VIN: </strong>'; $cuerpo .= $_POST['vin']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>VENDEDOR: </strong>'; $cuerpo .= $_POST['vendedor']. "</div>"; $cuerpo .= '<div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>MODIFICACIONES: </strong>'; $cuerpo .= 'Estado 3: '; $cuerpo .= $estado3nuevo; $cuerpo .= ' Importe aprobado: '; $cuerpo .= $_POST['importeaprobado']. "</div>"; $cuerpo .= '<br><div style="border:1; border-color:#333; border-style:solid; width:500px; height:30px"><strong>OBSERVACIONES: </strong>'; $cuerpo .= $_POST['comentario3']. "</div>"; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $to = explode(";",$row_mails['credito']); for($i=0;$i<count($to);$i++){ $mail->AddAddress(trim($to[$i])); } $mail->Subject = 'CREDITO: ' . $_POST['cliente']; $mail->Body = $cuerpo; $mail->Send(); } } $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET importeaprobado=%s, idestado1=%s, comentario1=%s, idestado2=%s, comentario2=%s, idestado3=%s, comentario3=%s, estadocivil=%s, condominio=%s, profesion=%s, idbanco=%s, idcuota=%s WHERE idreserva=%s", GetSQLValueString($_POST['importeaprobado'], "double"), GetSQLValueString($_POST['idestado1'], "int"), GetSQLValueString($_POST['comentario1'], "text"), GetSQLValueString($_POST['idestado2'], "int"), GetSQLValueString($_POST['comentario2'], "text"), GetSQLValueString($_POST['idestado3'], "int"), GetSQLValueString($_POST['comentario3'], "text"), GetSQLValueString($_POST['estadocivil'], "text"), GetSQLValueString($_POST['condominio'], "int"), GetSQLValueString($_POST['profesion'], "text"), GetSQLValueString($_POST['idbanco'], "text"), GetSQLValueString($_POST['idcuota'], "text"), GetSQLValueString($_POST['id'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); mysql_select_db($database_config, $config); $query_banco = sprintf("SELECT banco FROM slc_stocksud_banco WHERE idbanco = %s ", GetSQLValueString($_POST['idbanco'], "int")); $banco = mysql_query($query_banco, $config) or die(mysql_error()); $row_banco = mysql_fetch_assoc($banco); $totalRows_banco = mysql_num_rows($banco); mysql_select_db($database_config2, $config2); $query_banco2 = sprintf("SELECT idbanco FROM slc_banco WHERE banco LIKE %s ", GetSQLValueString($row_banco['banco'], "text")); $banco2 = mysql_query($query_banco2, $config2) or die(mysql_error()); $row_banco2 = mysql_fetch_assoc($banco2); $totalRows_banco2 = mysql_num_rows($banco2); mysql_select_db($database_config, $config); $query_cantcuotas = sprintf("SELECT cuota FROM slc_stocksud_cuota WHERE idcuota = %s ", GetSQLValueString($_POST['idcuota'], "int")); $cantcuotas = mysql_query($query_cantcuotas, $config) or die(mysql_error()); $row_cantcuotas = mysql_fetch_assoc($cantcuotas); $totalRows_cantcuotas = mysql_num_rows($cantcuotas); mysql_select_db($database_config2, $config2); $query_cantcuotas2 = sprintf("SELECT idCantidadcuotas FROM slc_cantidadcuotas WHERE cantidadcuotas LIKE %s ", GetSQLValueString($row_cantcuotas['cuota'], "text")); $cantcuotas2 = mysql_query($query_cantcuotas2, $config2) or die(mysql_error()); $row_cantcuotas2 = mysql_fetch_assoc($cantcuotas2); $totalRows_cantcuotas2 = mysql_num_rows($cantcuotas2); $updateSQL = sprintf("UPDATE slc_solicitudformapago SET creditoidbanco=%s, creditoidcantidadcuotas=%s WHERE idSolicitud = %s AND formapago = 'credito'", GetSQLValueString($row_banco2['idbanco'], "int"), GetSQLValueString($row_cantcuotas2['idCantidadcuotas'], "int"), GetSQLValueString($row_stock['idSolicitud'], "int")); mysql_select_db($database_config2, $config2); $Result1 = mysql_query($updateSQL, $config2) or die(mysql_error()); } header("location: creditos.php?chasis=" . $_POST['chasis'] . "&cliente1=" . $_POST['cliente1'] . "&cliente2=" . $_POST['cliente2'] . "&cliente3=" . $_POST['cliente3'] . "&cliente4=" . $_POST['cliente4'] . "&cliente5=" . $_POST['cliente5'] ); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> </body> <?php mysql_free_result($stock); ?> <file_sep>/stock_nofacturado_solicitud_guardar.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } function sumardiasafecha($fecha,$dia) { list($year,$mon,$day) = explode('-',$fecha); return date('Y-m-d',mktime(0,0,0,$mon,$day+$dia,$year)); } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { //Se actualiza reseva en asignado = 1 if(isset($_POST['idreserva']) && ($_POST['idreserva'] > 0)) { $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET asignado=%s WHERE idreserva=%s", GetSQLValueString("1", "int"), GetSQLValueString($_POST['idreserva'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } //Se busca el idCliente correspondiente al sistema de stock $colname_cliente = $_POST['dni']; mysql_select_db($database_config, $config); $query_cliente = sprintf("SELECT idCliente FROM slc_stock_cliente WHERE dni = %s", GetSQLValueString($colname_cliente, "text")); $cliente = mysql_query($query_cliente, $config) or die(mysql_error()); $row_cliente = mysql_fetch_assoc($cliente); $totalRows_cliente = mysql_num_rows($cliente); //Se actualiza registro de stock con idCliente y otros datos $updateSQL = sprintf("UPDATE slc_stocksud_stocknofacturado SET idCliente=%s, idSolicitud=%s, fechasolicitud=%s, precioventa=%s, intereses=%s, accesorios=%s, total=%s, idvendedor=%s, usadomodelo=%s WHERE idstock=%s", GetSQLValueString($row_cliente['idCliente'], "int"), GetSQLValueString($_POST['idSolicitud'], "int"), GetSQLValueString(fecha($_POST['fechasolicitud']), "date"), GetSQLValueString($_POST['precioventa'], "double"), GetSQLValueString($_POST['intereses'], "double"), GetSQLValueString($_POST['accesorios'], "double"), GetSQLValueString($_POST['total'], "double"), GetSQLValueString($_POST['idvendedor'], "int"), GetSQLValueString($_POST['usadomodelo'], "text"), GetSQLValueString($_POST['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); //Se guarda registro de cliente asignado cuando se asigna a otro cliente if(($row_cliente['idCliente'] != $_POST['idClienteanterior']) && ($_POST['idClienteanterior'] != 0 || $_POST['idClienteanterior'] != '')){ $insertSQL = sprintf("INSERT INTO slc_stocksud_asignacion (idUsuario, idstock, fechahora) VALUES (%s, %s, %s)", GetSQLValueString($_POST['idUsuario'], "int"), GetSQLValueString($_POST['idstock'], "int"), GetSQLValueString($_POST['fechahora'], "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } //Se guarda forma de pago crédito en stock $formapago = $_POST['formapago']; $idFormaPago = $_POST['idFormaPago']; $creditoidbanco = $_POST['creditoidbanco']; $creditoidcantidadcuotas = $_POST['creditoidcantidadcuotas']; $idsucursalbna = $_POST['idsucursalbna']; for($i=0; $i<count($formapago); $i++){ if($formapago[$i] == 'credito'){ $updateSQL = sprintf("UPDATE slc_solicitudformapago SET creditoidbanco=%s, creditoidcantidadcuotas=%s, idsucursalbna=%s WHERE idFormaPago = %s", GetSQLValueString($creditoidbanco[$i], "int"), GetSQLValueString($creditoidcantidadcuotas[$i], "int"), GetSQLValueString($idsucursalbna[$i], "int"), GetSQLValueString($idFormaPago[$i], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_stocksud_stocknofacturado SET idbanco=%s, idcuota=%s WHERE idstock=%s", GetSQLValueString($creditoidbanco[$i], "int"), GetSQLValueString($creditoidcantidadcuotas[$i], "int"), GetSQLValueString($_POST['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } } //Si no existe entrega inserta una entrega if($_POST['idEntrega'] == 0){ $colname_usados = "-1"; if (isset($_POST['idSolicitud'])) { $colname_usados = $_POST['idSolicitud']; } mysql_select_db($database_config, $config); $query_usados = sprintf("SELECT usadodescripcion, usadoanio, usadodominio, usadoidtasacion, importe FROM slc_solicitudformapago WHERE idSolicitud = %s AND formapago = 'usado'", GetSQLValueString($colname_usados, "int")); $usados = mysql_query($query_usados, $config) or die(mysql_error()); $row_usados = mysql_fetch_assoc($usados); $totalRows_usados = mysql_num_rows($usados); if($totalRows_usados > 0) { $entrega_usados = 1; } else { $entrega_usados = 0; } $colname_accesorios = $_POST['idSolicitud']; mysql_select_db($database_config, $config); $query_accesorios = sprintf("SELECT slc_solicitudaccesorio.idAccesorioTipo, slc_solicitudaccesorio.importe, slc_cliente_usuario.usuario FROM slc_solicitudaccesorio LEFT JOIN slc_cliente_usuario ON slc_solicitudaccesorio.idUsuario = slc_cliente_usuario.idUsuario WHERE idSolicitud = %s", GetSQLValueString($colname_accesorios, "int")); $accesorios = mysql_query($query_accesorios, $config) or die(mysql_error()); $row_accesorios = mysql_fetch_assoc($accesorios); $totalRows_accesorios = mysql_num_rows($accesorios); if($totalRows_accesorios > 0) { $entrega_accesorios = 1; } else { $entrega_accesorios = 0; } $prendaPropia = 0; if($_POST['autoahorro'] == 1) { $idTipoEntrega = 2; } else { $idTipoEntrega = 3; } $colname_vendedor = $_POST['vendedor']; mysql_select_db($database_config, $config); $query_vendedor = sprintf("SELECT idUsuario, usuario FROM slc_usuario WHERE usuario LIKE %s", GetSQLValueString($colname_vendedor, "text")); $vendedor = mysql_query($query_vendedor, $config) or die(mysql_error()); $row_vendedor = mysql_fetch_assoc($vendedor); $totalRows_vendedor = mysql_num_rows($vendedor); $colname_stock = $_POST['idstock']; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT slc_stocksud_stocknofacturado.idstock, slc_stocksud_stocknofacturado.idMarca, slc_stocksud_stocknofacturado.modelo, slc_stock_cliente.apellidoynombre, slc_stock_cliente.email FROM slc_stocksud_stocknofacturado LEFT JOIN slc_stock_cliente ON slc_stock_cliente.idCliente = slc_stocksud_stocknofacturado.idCliente WHERE slc_stocksud_stocknofacturado.idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if($totalRows_vendedor > 0) { if(isset($_POST['fechaestimadaentrega']) && ($_POST['fechaestimadaentrega'] != "")) { $fechaHoraEntrega = $_POST['fechaestimadaentrega']; $fechaEntrega = fecha($fechaHoraEntrega,0); //obtiene fecha de caducidad de la encuesta temprana, es la fecha de entrega mas la caducidad que indica la encuesta. $colname_encuesta = $row_stock['idMarca']; mysql_select_db($database_config, $config); $query_encuesta = sprintf("SELECT caducidad FROM slc_encuesta WHERE idtipo = 1 AND activa = 1 AND idMarca = %s ORDER BY idencuesta DESC ", GetSQLValueString($colname_encuesta, "int")); $encuesta = mysql_query($query_encuesta, $config) or die(mysql_error()); $row_encuesta = mysql_fetch_assoc($encuesta); $totalRows_encuesta = mysql_num_rows($encuesta); if(($totalRows_encuesta > 0) && ($row_encuesta['caducidad'] > 0)) { $caducidad = $row_encuesta['caducidad']; } else { $caducidad = 0; } $fechacaducidadenctemprana = sumardiasafecha($fechaEntrega,$caducidad); //obtiene fecha de caducidad de la encuesta llamado de cortesia, es la fecha de entrega mas la caducidad que indica la encuesta, excluyendo domingos y feriados. $colname_encuesta = $row_stock['idMarca']; mysql_select_db($database_config, $config); $query_encuesta = sprintf("SELECT caducidad FROM slc_encuesta WHERE idtipo = 2 AND activa = 1 AND idMarca = %s ORDER BY idencuesta DESC ", GetSQLValueString($colname_encuesta, "int")); $encuesta = mysql_query($query_encuesta, $config) or die(mysql_error()); $row_encuesta = mysql_fetch_assoc($encuesta); $totalRows_encuesta = mysql_num_rows($encuesta); if(($totalRows_encuesta > 0) && ($row_encuesta['caducidad'] > 0)) { $caducidad = $row_encuesta['caducidad']; } else { $caducidad = 0; } $fechacaducidadenccortesia = $fechaEntrega; for($i=1; $i<=$caducidad; $i++) { do { $fechacaducidadenccortesia = strtotime('+1 day',strtotime($fechacaducidadenccortesia)); $fechacaducidadenccortesia = date ('Y-m-d',$fechacaducidadenccortesia); $colname_feriado = $fechacaducidadenccortesia; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } while (($totalRows_feriado > 0) || (date('w',strtotime($fechacaducidadenccortesia)) == 0)); } //obtiene fecha de caducidad de la encuesta call center, es la fecha de entrega mas la caducidad que indica la encuesta, excluyendo domingos y feriados. $colname_encuesta = $row_stock['idMarca']; mysql_select_db($database_config, $config); $query_encuesta = sprintf("SELECT caducidad FROM slc_encuesta WHERE idtipo = 3 AND venta_postventa = 1 AND activa = 1 AND idMarca = %s ORDER BY idencuesta DESC ", GetSQLValueString($colname_encuesta, "int")); $encuesta = mysql_query($query_encuesta, $config) or die(mysql_error()); $row_encuesta = mysql_fetch_assoc($encuesta); $totalRows_encuesta = mysql_num_rows($encuesta); if(($totalRows_encuesta > 0) && ($row_encuesta['caducidad'] > 0)) { $caducidad = $row_encuesta['caducidad']; } else { $caducidad = 0; } $fechacaducidadenccallcenter = $fechacaducidadenccortesia; for($i=1; $i<=$caducidad; $i++) { do { $fechacaducidadenccallcenter = strtotime('+1 day',strtotime($fechacaducidadenccallcenter)); $fechacaducidadenccallcenter = date ('Y-m-d',$fechacaducidadenccallcenter); $colname_feriado = $fechacaducidadenccallcenter; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } while (($totalRows_feriado > 0) || (date('w',strtotime($fechacaducidadenccallcenter)) == 0)); } } if($_POST['chasis'] != "") { $vin = $_POST['chasis']; } else { $vin = $_POST['comision2']; } $updateSQL = sprintf("UPDATE slc_solicitudreserva SET fechaestimadaentrega=%s WHERE idSolicitud=%s", GetSQLValueString(fecha($_POST['fechaestimadaentrega']), "date"), GetSQLValueString($_POST['idSolicitud'], "int")); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $insertSQL = sprintf("INSERT INTO slc_entrega (idCliente, idUsuarioCarga, fechaHoraCarga, idConsultor, idVendedor, idTipoEntrega, VIN, idMarca, modelo, observaciones, accesorios, usados, prendaPropia, idSolicitud, empresa, fechaHoraEntrega, stocknofacturado, fechacaducidadenctemprana, fechacaducidadenccortesia, fechacaducidadenccallcenter) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($row_cliente['idCliente'], "int"), GetSQLValueString('0', "int"), GetSQLValueString(date('Y-m-d h:i'), "date"), GetSQLValueString($_POST['idconsultor'], "int"), GetSQLValueString($row_vendedor['idUsuario'], "int"), GetSQLValueString($idTipoEntrega, "int"), GetSQLValueString($vin, "text"), GetSQLValueString($row_stock['idMarca'], "int"), GetSQLValueString($row_stock['modelo'], "text"), GetSQLValueString('', "text"), GetSQLValueString($entrega_accesorios, "int"), GetSQLValueString($entrega_usados, "int"), GetSQLValueString($prendaPropia, "int"), GetSQLValueString($_POST['idSolicitud'], "text"), GetSQLValueString('3', "int"), GetSQLValueString(fecha($_POST['fechaestimadaentrega']), "date"), GetSQLValueString('1', "int"), GetSQLValueString($fechacaducidadenctemprana, "date"), GetSQLValueString($fechacaducidadenccortesia, "date"), GetSQLValueString($fechacaducidadenccallcenter, "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idEntrega = mysql_insert_id($config); if($totalRows_accesorios > 0){ // Show if recordset not empty do { $colname_accesoriousuario = $row_accesorios['usuario']; mysql_select_db($database_config, $config); $query_accesoriousuario = sprintf("SELECT idUsuario FROM slc_usuario WHERE usuario LIKE %s", GetSQLValueString($colname_accesoriousuario, "text")); $accesoriousuario = mysql_query($query_accesoriousuario, $config) or die(mysql_error()); $row_accesoriousuario = mysql_fetch_assoc($accesoriousuario); $totalRows_accesoriousuario = mysql_num_rows($accesoriousuario); $insertSQL = sprintf("INSERT INTO slc_entregaaccesorio(idEntrega, idAccesorioTipo, accesoriosimporte, idUsuario) VALUES (%s, %s, %s, %s)", GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_accesorios['idAccesorioTipo'], "int"), GetSQLValueString($row_accesorios['importe'], "double"), GetSQLValueString($row_accesoriousuario['idUsuario'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } while ($row_accesorios = mysql_fetch_assoc($accesorios)); } // Show if recordset not empty if($totalRows_usados > 0){ // Show if recordset not empty do { $insertSQL = sprintf("INSERT INTO slc_entregausado(idEntrega, usadoModelo, usadoDominio, usadoAnio, usadoImporte, usadoidtasacion) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_usados['usadodescripcion'], "text"), GetSQLValueString($row_usados['usadodominio'], "text"), GetSQLValueString($row_usados['usadoanio'], "int"), GetSQLValueString($row_usados['importe'], "double"), GetSQLValueString($row_usados['usadoidtasacion'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } while ($row_usados = mysql_fetch_assoc($usados)); } // Show if recordset not empty $colname_consultor = $_POST['idconsultor']; mysql_select_db($database_config, $config); $query_consultor = sprintf("SELECT slc_consultor.idUsuario, slc_consultor.consultor, slc_usuario.email FROM slc_consultor LEFT JOIN slc_usuario on slc_consultor.idUsuario = slc_usuario.idUsuario WHERE idConsultor = %s", GetSQLValueString($colname_consultor, "int")); $consultor = mysql_query($query_consultor, $config) or die(mysql_error()); $row_consultor = mysql_fetch_assoc($consultor); $totalRows_consultor = mysql_num_rows($consultor); //Cierre por sistema de contactos relacionados con la solicitud $updateSQL = sprintf("UPDATE slc_agenda SET idEntrega=%s, estado=%s, cerradopor=%s WHERE estado=%s AND idSolicitud = %s", GetSQLValueString($idEntrega, "int"), GetSQLValueString('1', "int"), GetSQLValueString('1', "int"), GetSQLValueString('0', "int"), GetSQLValueString($_POST['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); //Alta a llamado de revisión de operación $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('+1 day',strtotime($fechacontacto)) ; $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('+1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('6', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de revision de operacion de stock no facturado', "text"), GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { //Se actualiza reseva en asignado = 0 porque el vendedor no está agregado en el sistema de entregas if(isset($_POST['idreserva']) && ($_POST['idreserva'] > 0)) { $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET asignado=%s WHERE idreserva=%s", GetSQLValueString("0", "int"), GetSQLValueString($_POST['idreserva'], "int")); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } $mensaje = "El vehículo no se asignó porque el vendedor no se encuentra agregado en el sistema de entregas: " . $row_vendedor['usuario']; } } else { //Si existe entrega actualiza una entrega $colname_usados = "-1"; if (isset($_POST['idSolicitud'])) { $colname_usados = $_POST['idSolicitud']; } mysql_select_db($database_config, $config); $query_usados = sprintf("SELECT usadodescripcion, usadoanio, usadodominio, usadoidtasacion, importe FROM slc_solicitudformapago WHERE idSolicitud = %s AND formapago = 'usado'", GetSQLValueString($colname_usados, "int")); $usados = mysql_query($query_usados, $config) or die(mysql_error()); $row_usados = mysql_fetch_assoc($usados); $totalRows_usados = mysql_num_rows($usados); if($totalRows_usados > 0) { $entrega_usados = 1; } else { $entrega_usados = 0; } $prendaPropia = 0; if($_POST['autoahorro'] == 1) { $idTipoEntrega = 2; } else { $idTipoEntrega = 3; } $colname_vendedor = $_POST['vendedor']; mysql_select_db($database_config, $config); $query_vendedor = sprintf("SELECT idUsuario, usuario FROM slc_usuario WHERE usuario LIKE %s", GetSQLValueString($colname_vendedor, "text")); $vendedor = mysql_query($query_vendedor, $config) or die(mysql_error()); $row_vendedor = mysql_fetch_assoc($vendedor); $totalRows_vendedor = mysql_num_rows($vendedor); $colname_stock = $_POST['idstock']; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idMarca, modelo, chasis, comision2 FROM slc_stocksud_stocknofacturado WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if($row_stock['chasis'] != '') { $vin = $row_stock['chasis']; } else { $vin = $row_stock['comision2']; } if($totalRows_vendedor > 0) { if(isset($_POST['idEntrega_vin']) && ($_POST['idEntrega_vin'] > 0)) { $updateSQL = sprintf("UPDATE slc_entrega SET VIN=%s WHERE idEntrega=%s", GetSQLValueString('baja-' . $vin, "text"), GetSQLValueString($_POST['idEntrega_vin'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } $colname_entrega = "-1"; if (isset($_POST['idEntrega'])) { $colname_entrega = $_POST['idEntrega']; } mysql_select_db($database_config, $config); $query_entrega = sprintf("SELECT fechaHoraEntrega FROM slc_entrega WHERE idEntrega = %s", GetSQLValueString($colname_entrega, "int")); $entrega = mysql_query($query_entrega, $config) or die(mysql_error()); $row_entrega = mysql_fetch_assoc($entrega); $totalRows_entrega = mysql_num_rows($entrega); if(($row_entrega['fechaHoraEntrega'] == '') || ($row_entrega['fechaHoraEntrega'] == '0000-00-00 00:00:00')){ $fecha_entrega = fecha($_POST['fechaestimadaentrega']); $updateSQL = sprintf("UPDATE slc_solicitudreserva SET fechaestimadaentrega=%s WHERE idSolicitud=%s", GetSQLValueString($fecha_entrega, "date"), GetSQLValueString($_POST['idSolicitud'], "int")); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } else { $fecha_entrega = $row_entrega['fechaHoraEntrega']; } $updateSQL = sprintf("UPDATE slc_entrega SET fechaHoraEntrega=%s, idCliente=%s, VIN=%s, idUsuarioModifica=%s, idConsultor=%s, idVendedor=%s, usados=%s, modelo=%s, baja=%s, empresa=%s, stocknofacturado=%s WHERE idEntrega=%s", GetSQLValueString($fecha_entrega, "date"), GetSQLValueString($row_cliente['idCliente'], "int"), GetSQLValueString($vin, "text"), GetSQLValueString($_POST['idconsultor'], "int"), GetSQLValueString($_POST['idconsultor'], "int"), GetSQLValueString($row_vendedor['idUsuario'], "int"), GetSQLValueString($entrega_usados, "int"), GetSQLValueString($row_stock['modelo'], "text"), GetSQLValueString('0', "int"), GetSQLValueString('3', "int"), GetSQLValueString('1', "int"), GetSQLValueString($_POST['idEntrega'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_entregas_turnos_responsables SET baja=%s WHERE entrega_id=%s", GetSQLValueString('0', "int"), GetSQLValueString($_POST['idEntrega'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_entregas_turnos_consultores SET baja=%s WHERE entrega_id=%s", GetSQLValueString('0', "int"), GetSQLValueString($_POST['idEntrega'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $deleteSQL = sprintf("DELETE FROM slc_entregausado WHERE idEntrega=%s", GetSQLValueString($row_entrega['idEntrega'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); if($totalRows_usados > 0){ // Show if recordset not empty do { $insertSQL = sprintf("INSERT INTO slc_entregausado(idEntrega, usadoModelo, usadoDominio, usadoAnio, usadoImporte, usadoidtasacion) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idEntrega'], "int"), GetSQLValueString($row_usados['usadodescripcion'], "text"), GetSQLValueString($row_usados['usadodominio'], "text"), GetSQLValueString($row_usados['usadoanio'], "int"), GetSQLValueString($row_usados['importe'], "double"), GetSQLValueString($row_usados['usadoidtasacion'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } while ($row_usados = mysql_fetch_assoc($usados)); } // Show if recordset not empty //Cierra el llamado de seguimiento de reseva si está abierto $updateSQL = sprintf("UPDATE slc_agenda SET idEntrega=%s, estado=%s, cerradopor=%s WHERE estado=%s AND idtipoevento=%s AND idSolicitud = %s", GetSQLValueString($_POST['idEntrega'], "int"), GetSQLValueString('1', "int"), GetSQLValueString('1', "int"), GetSQLValueString('0', "int"), GetSQLValueString('2', "int"), GetSQLValueString($_POST['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); //Busca llamado de revisión de operación y de stock no facturado están cerrados por sistema le da de alta a uno nuevo mysql_select_db($database_config, $config); $query_agenda = sprintf("SELECT * FROM slc_agenda WHERE (idtipoevento = '3' OR idtipoevento = '6') AND idEntrega = %s AND estado='3' AND cerradopor='1'", GetSQLValueString($row_entrega['idEntrega'], "int")); $agenda = mysql_query($query_agenda, $config) or die(mysql_error()); $row_agenda = mysql_fetch_assoc($agenda); $totalRows_agenda = mysql_num_rows($agenda); if($totalRows_agenda > 0) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('+1 day',strtotime($fechacontacto)) ; $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('+1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('6', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de revision de operacion de stock no facturado', "text"), GetSQLValueString($_POST['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } else { //Se actualiza reseva en asignado = 0 porque el vendedor no está agregado en el sistema de entregas if(isset($_POST['idreserva']) && ($_POST['idreserva'] > 0)) { $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET asignado=%s WHERE idreserva=%s", GetSQLValueString("0", "int"), GetSQLValueString($_POST['idreserva'], "int")); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } $mensaje = "El vehículo no se asignó porque el vendedor no se encuentra agregado en el sistema de entregas: " . $row_vendedor['usuario']; } } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI GM</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script> function CloseWin(){ window.opener.location.reload(); window.close(); } </script> </head> <body onLoad="CloseWin()"> </body><file_sep>/reportes_consultastock2.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session session_start(); // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles session_unregister('MM_Username'); session_unregister('MM_UserGroup'); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php session_start(); $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); mysql_select_db($database_config, $config); $query_modelo = "SELECT * FROM slc_stocksud_modelo ORDER BY modelo ASC"; $modelo = mysql_query($query_modelo, $config) or die(mysql_error()); $row_modelo = mysql_fetch_assoc($modelo); $totalRows_modelo = mysql_num_rows($modelo); $colname_stock = ""; if (isset($_POST['reserva'])) { $colname_stock = $_POST['reserva']; } $colname2_stock = ""; if (isset($_POST['cliente'])) { $colname2_stock = $_POST['cliente']; } $colname3_stock = "todos"; if (isset($_POST['modelo'])) { $colname3_stock = $_POST['modelo']; } $colname4_stock = ""; if (isset($_POST['color'])) { $colname4_stock = $_POST['color']; } $colname5_stock = ""; if (isset($_POST['fechasolicituddesde'])) { $colname5_stock = fecha($_POST['fechasolicituddesde']); } $colname6_stock = ""; if (isset($_POST['fechasolicitudhasta'])) { $colname6_stock = fecha($_POST['fechasolicitudhasta']); } $colname7_stock = ""; if (isset($_POST['sinfechasolicitud'])) { $colname7_stock = $_POST['sinfechasolicitud']; } $colname8_stock = ""; if (isset($_POST['fechasolicitudtodos'])) { $colname8_stock = $_POST['fechasolicitudtodos']; } $colname9_stock = ""; if (isset($_POST['certificado'])) { $colname9_stock = $_POST['certificado']; } $colname10_stock = ""; if (isset($_POST['comision'])) { $colname10_stock = $_POST['comision']; } $colname11_stock = ""; if (isset($_POST['idvendedor'])) { $colname11_stock = $_POST['idvendedor']; } $colname12_stock = "0"; if (isset($_POST['mesfactura'])) { $colname12_stock = $_POST['mesfactura']; } $colname13_stock = "0"; if (isset($_POST['aniofactura'])) { $colname13_stock = $_POST['aniofactura']; } $colname17_stock = ""; if (isset($_POST['certificadovacios'])) { $colname17_stock = $_POST['certificadovacios']; } $colname18_stock = ""; if (isset($_POST['deudadesde'])) { $colname18_stock = $_POST['deudadesde']; } $colname19_stock = ""; if (isset($_POST['deudahasta'])) { $colname19_stock = $_POST['deudahasta']; } $colname20_stock = " "; if (isset($_POST['entrega'])) { $colname20_stock = $_POST['entrega']; } $colname21_stock = "0"; if (isset($_POST['idpromocion'])) { $colname21_stock = $_POST['idpromocion']; } $colname22_stock = ""; if (isset($_POST['numfactura'])) { $colname22_stock = $_POST['numfactura']; } $colname23_stock = ""; if (isset($_POST['fechasolicitudtodosfecha'])) { $colname23_stock = $_POST['fechasolicitudtodosfecha']; } $colname24_stock = "0"; if (isset($_POST['idbanco'])) { $colname24_stock = $_POST['idbanco']; } $colname25_stock = "1"; if (isset($_POST['stockfacturado'])) { $colname25_stock = $_POST['stockfacturado']; } $colname26_stock = ""; if (isset($_POST['idsucursal'])) { $colname26_stock = $_POST['idsucursal']; } $colname27_stock = ""; if (isset($_POST['iddeposito'])) { $colname27_stock = $_POST['iddeposito']; } $colname28_stock = ""; if (isset($_POST['tienecomision'])) { $colname28_stock = $_POST['tienecomision']; } $colname29_stock = ""; if (isset($_POST['comisiondesde'])) { $colname29_stock = fecha($_POST['comisiondesde']); } $colname30_stock = ""; if (isset($_POST['comisionhasta'])) { $colname30_stock = fecha($_POST['comisionhasta']); } $colname31_stock = "fechaHoraEntrega"; if (isset($_POST['ordenarpor'])) { $colname31_stock = $_POST['ordenarpor']; } mysql_select_db($database_config, $config); if($colname25_stock == '1') { $query_stock = sprintf("SELECT slc_stocksud_stock.orden, slc_stocksud_stock.mes, slc_stocksud_stock.anio, slc_stocksud_stock.comision2, slc_stocksud_stock.numfactura, slc_sucursal.sucursal, slc_deposito.deposito, slc_sucursal_venta.sucursal AS sucursalventa, slc_stocksud_stock.chasis, slc_stocksud_stock.modelo, slc_stocksud_stock.color, slc_stocksud_stock.nrocertif, slc_stocksud_stock.modelocertif, slc_stocksud_stock.importefactcompra, slc_stocksud_stock.reserva, slc_stocksud_stock.observacionesreserva, slc_stock_cliente.apellidoynombre, slc_stocksud_stock.fechasolicitud, slc_entrega.entrega, slc_entrega.fechaHoraEntrega, slc_stocksud_stock.precioventa, slc_stocksud_stock.intereses, slc_stocksud_stock.accesorios, slc_stocksud_stock.total, slc_stocksud_usuario.usuario AS vendedor, slc_stocksud_stock.comision, slc_stocksud_stock.usadomodelo, slc_stocksud_banco.banco FROM slc_stocksud_stock LEFT JOIN slc_stocksud_usuario ON slc_stocksud_stock.idvendedor=slc_stocksud_usuario.idUsuario LEFT JOIN slc_stock_cliente ON slc_stocksud_stock.idCliente = slc_stock_cliente.idCliente LEFT JOIN slc_entrega ON slc_stocksud_stock.chasis = slc_entrega.VIN LEFT JOIN slc_stocksud_banco ON slc_stocksud_banco.idbanco = slc_stocksud_stock.idbanco LEFT JOIN slc_sucursal ON slc_sucursal.id = slc_stocksud_stock.idsucursal LEFT JOIN slc_deposito ON slc_deposito.id = slc_stocksud_stock.iddeposito LEFT JOIN slc_solicitudreserva ON slc_solicitudreserva.idSolicitud = slc_stocksud_stock.idSolicitud LEFT JOIN slc_sucursal_venta ON slc_sucursal_venta.id = slc_solicitudreserva.idsucursalventa WHERE slc_stocksud_stock.modelo LIKE %s", GetSQLValueString("%" . $colname3_stock . "%" , "text")); if($colname_stock != '') { if($colname_stock != '1') { $query_stock .= sprintf(" WHERE slc_stocksud_stock.reserva = %s OR reserva = ''", GetSQLValueString($colname_stock, "int")); } else { $query_stock .= sprintf(" WHERE slc_stocksud_stock.reserva = %s", GetSQLValueString($colname_stock, "int")); } } if($colname2_stock != "") { $query_stock .= sprintf(" AND slc_stock_cliente.apellidoynombre LIKE %s", GetSQLValueString("%" . $colname2_stock . "%", "text")); } if($colname4_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.color LIKE %s", GetSQLValueString("%" . $colname4_stock . "%", "text")); } if(($colname7_stock != "1") && ($colname8_stock != "1") && ($colname5_stock != "") && ($colname6_stock != "")) { $query_stock .= sprintf(" AND slc_stocksud_stock.fechasolicitud BETWEEN %s AND %s ", GetSQLValueString($colname5_stock, "date"), GetSQLValueString($colname6_stock, "date")); } if($colname8_stock != "1"){ if($colname7_stock == "1"){ $query_stock .= " AND ((slc_stocksud_stock.fechasolicitud LIKE '') OR (slc_stocksud_stock.fechasolicitud LIKE '0000-00-00') OR (slc_stocksud_stock.fechasolicitud IS NULL))"; } if($colname23_stock == "1"){ $query_stock .= " AND ((slc_stocksud_stock.fechasolicitud <> '') AND (slc_stocksud_stock.fechasolicitud <> '0000-00-00') AND (slc_stocksud_stock.fechasolicitud IS NOT NULL))"; } } if(($colname9_stock != "") && ($colname17_stock != '1')) { $query_stock .= sprintf(" AND slc_stocksud_stock.certificado LIKE %s", GetSQLValueString("%" . $colname9_stock . "%", "text")); } elseif ($colname17_stock == '1') { $query_stock .= " AND slc_stocksud_stock.certificado IS NULL OR slc_stocksud_stock.certificado LIKE ''"; } if($colname10_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.comision LIKE %s", GetSQLValueString("%" . $colname10_stock . "%", "text")); } if($row_usuario_sesion['idGrupo'] == 3) { $query_stock .= sprintf(" AND slc_stocksud_stock.idvendedor = %s", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } elseif($colname11_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.idvendedor = %s", GetSQLValueString($colname11_stock, "int")); } if(($colname12_stock != "0") && ($colname13_stock != "0")) { $query_stock .= sprintf(" AND slc_stocksud_stock.mes = %s AND slc_stocksud_stock.anio = %s ", GetSQLValueString($colname12_stock, "int"), GetSQLValueString($colname13_stock, "int")); } if(($colname18_stock != "") && ($colname19_stock != "")) { $query_stock .= sprintf(" AND slc_stocksud_stock.deuda BETWEEN %s AND %s", GetSQLValueString($colname18_stock, "double"), GetSQLValueString($colname19_stock, "double")); } if($colname20_stock == '0') { $query_stock .= sprintf(" AND (slc_entrega.entrega = %s OR slc_entrega.entrega IS NULL)", GetSQLValueString($colname20_stock, "int")); } if($colname20_stock == '1') { $query_stock .= sprintf(" AND slc_entrega.entrega = %s", GetSQLValueString($colname20_stock, "int")); } if($colname21_stock != "0") { $query_stock .= sprintf(" AND slc_stocksud_stock.idpromocion = %s", GetSQLValueString($colname21_stock, "int")); } if($colname22_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.numfactura LIKE %s", GetSQLValueString("%" . $colname22_stock . "%", "text")); } if($colname24_stock != "0") { } if($colname26_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.idsucursal = %s", GetSQLValueString($colname26_stock, "int")); } if($colname27_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.iddeposito = %s", GetSQLValueString($colname27_stock, "int")); } if($colname28_stock == "1") { $query_stock .= sprintf(" AND (slc_stocksud_stock.comision <> '' AND slc_stocksud_stock.comision IS NOT NULL", GetSQLValueString($colname27_stock, "int")); } if($colname28_stock == "0") { $query_stock .= sprintf(" AND (slc_stocksud_stock.comision = '' AND slc_stocksud_stock.comision IS NULL", GetSQLValueString($colname27_stock, "int")); } if(($colname29_stock != "") && ($colname30_stock != "")) { $query_stock .= sprintf(" AND slc_stocksud_stock.comision BETWEEN %s AND %s ", GetSQLValueString($colname29_stock, "date"), GetSQLValueString($colname30_stock, "date")); } $query_stock .= " GROUP BY slc_stocksud_stock.idStock ORDER BY " . $colname31_stock; } else { $query_stock = sprintf("SELECT slc_stocksud_stocknofacturado.anio, slc_stocksud_stocknofacturado.comision2, slc_sucursal.sucursal, slc_deposito.deposito, slc_sucursal_venta.sucursal AS sucursalventa, slc_stocksud_stocknofacturado.chasis, slc_stocksud_stocknofacturado.modelo, slc_stocksud_stocknofacturado.color, slc_stocksud_stocknofacturado.reserva, slc_stocksud_stocknofacturado.observacionesreserva, slc_stock_cliente.apellidoynombre, slc_stocksud_stocknofacturado.fechasolicitud, slc_stocksud_stocknofacturado.precioventa, slc_stocksud_stocknofacturado.intereses, slc_stocksud_stocknofacturado.accesorios, slc_stocksud_stocknofacturado.total, slc_stocksud_stocknofacturado.descripcion, slc_stocksud_stocknofacturado.entradapedidonadcon, slc_stocksud_stocknofacturado.semanaproduccionconfirmada, slc_stocksud_usuario.usuario FROM slc_stocksud_stocknofacturado LEFT JOIN slc_stocksud_usuario ON slc_stocksud_stocknofacturado.idvendedor=slc_stocksud_usuario.idUsuario LEFT JOIN slc_stock_cliente ON slc_stocksud_stocknofacturado.idCliente = slc_stock_cliente.idCliente LEFT JOIN slc_entrega ON slc_stocksud_stocknofacturado.chasis = slc_entrega.VIN LEFT JOIN slc_stocksud_banco ON slc_stocksud_banco.idbanco = slc_stocksud_stocknofacturado.idbanco LEFT JOIN slc_sucursal ON slc_sucursal.id = slc_stocksud_stocknofacturado.idsucursal LEFT JOIN slc_deposito ON slc_deposito.id = slc_stocksud_stocknofacturado.iddeposito LEFT JOIN slc_solicitudreserva ON slc_solicitudreserva.idSolicitud = slc_stocksud_stocknofacturado.idSolicitud LEFT JOIN slc_sucursal_venta ON slc_sucursal_venta.id = slc_solicitudreserva.idsucursalventa WHERE slc_stocksud_stocknofacturado.modelo LIKE %s", GetSQLValueString("%" . $colname3_stock . "%" , "text")); if($colname_stock != '') { if($colname_stock != '1') { $query_stock .= sprintf(" WHERE slc_stocksud_stocknofacturado.reserva = %s OR reserva = ''", GetSQLValueString($colname_stock, "int")); } else { $query_stock .= sprintf(" WHERE slc_stocksud_stocknofacturado.reserva = %s", GetSQLValueString($colname_stock, "int")); } } if($colname2_stock != "") { $query_stock .= sprintf(" slc_stock_cliente.apellidoynombre LIKE %s", GetSQLValueString("%" . $colname2_stock . "%", "text")); } if($colname4_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.color LIKE %s", GetSQLValueString("%" . $colname4_stock . "%", "text")); } if(($colname7_stock != "1") && ($colname8_stock != "1") && ($colname5_stock != "") && ($colname6_stock != "")) { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.fechasolicitud BETWEEN %s AND %s ", GetSQLValueString($colname5_stock, "date"), GetSQLValueString($colname6_stock, "date")); } if($colname8_stock != "1"){ if($colname7_stock == "1"){ $query_stock .= " AND ((slc_stocksud_stocknofacturado.fechasolicitud LIKE '') OR (slc_stocksud_stocknofacturado.fechasolicitud LIKE '0000-00-00') OR (slc_stocksud_stocknofacturado.fechasolicitud IS NULL))"; } if($colname23_stock == "1"){ $query_stock .= " AND ((slc_stocksud_stocknofacturado.fechasolicitud <> '') AND (slc_stocksud_stocknofacturado.fechasolicitud <> '0000-00-00') AND (slc_stocksud_stocknofacturado.fechasolicitud IS NOT NULL))"; } } if(($colname9_stock != "") && ($colname17_stock != '1')) { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.certificado LIKE %s", GetSQLValueString("%" . $colname9_stock . "%", "text")); } elseif ($colname17_stock == '1') { $query_stock .= " AND slc_stocksud_stocknofacturado.certificado IS NULL OR slc_stocksud_stocknofacturado.certificado LIKE ''"; } if($colname10_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.comision LIKE %s", GetSQLValueString("%" . $colname10_stock . "%", "text")); } if($row_usuario_sesion['idGrupo'] == 3) { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.idvendedor = %s", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } elseif($colname11_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.idvendedor = %s", GetSQLValueString($colname11_stock, "int")); } if(($colname12_stock != "0") && ($colname13_stock != "0")) { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.mes = %s AND slc_stocksud_stocknofacturado.anio = %s ", GetSQLValueString($colname12_stock, "int"), GetSQLValueString($colname13_stock, "int")); } if(($colname18_stock != "") && ($colname19_stock != "")) { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.deuda BETWEEN %s AND %s", GetSQLValueString($colname18_stock, "double"), GetSQLValueString($colname19_stock, "double")); } if($colname20_stock == '0') { $query_stock .= sprintf(" AND (slc_entrega.entrega = %s OR slc_entrega.entrega IS NULL)", GetSQLValueString($colname20_stock, "int")); } if($colname20_stock == '1') { $query_stock .= sprintf(" AND slc_entrega.entrega = %s", GetSQLValueString($colname20_stock, "int")); } if($colname21_stock != "0") { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.idpromocion = %s", GetSQLValueString($colname21_stock, "int")); } if($colname22_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stocknofacturado.numfactura LIKE %s", GetSQLValueString("%" . $colname22_stock . "%", "text")); } if($colname24_stock != "0") { } if($colname26_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.idsucursal = %s", GetSQLValueString($colname26_stock, "int")); } if($colname27_stock != "") { $query_stock .= sprintf(" AND slc_stocksud_stock.iddeposito = %s", GetSQLValueString($colname27_stock, "int")); } if($colname28_stock == "1") { $query_stock .= sprintf(" AND (slc_stocksud_stock.comision <> '' AND slc_stocksud_stock.comision IS NOT NULL", GetSQLValueString($colname27_stock, "int")); } if($colname28_stock == "0") { $query_stock .= sprintf(" AND (slc_stocksud_stock.comision = '' AND slc_stocksud_stock.comision IS NULL", GetSQLValueString($colname27_stock, "int")); } if(($colname29_stock != "") && ($colname30_stock != "")) { $query_stock .= sprintf(" AND slc_stocksud_stock.comision BETWEEN %s AND %s ", GetSQLValueString($colname29_stock, "date"), GetSQLValueString($colname30_stock, "date")); } $query_stock .= " GROUP BY slc_stocksud_stocknofacturado.idStock ORDER BY " . $colname31_stock; } $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } .Estilo3 {color: #FF0000} .Estilo11 {font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo21 {color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function MM_openBrWindow(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><BR> <table width="99%" height="82" border="1" align="center" cellpadding="4" cellspacing="0" bordercolor="#CCCCCC" id="ppal"> <tr class="Estilo1"> <td height="20" colspan="30" class="Estilo2"><div align="center">CONSULTA DE STOCK</div></td> </tr> <tr class="Estilo1"> <td height="20" class="Estilo2">ORD.</td> <td><span class="Estilo2">MES A&Ntilde;O</span></td> <td><span class="Estilo21">PROGRAMACION</span></td> <td><span class="Estilo2">FACTURA N&deg;</span></td> <td><span class="Estilo2">SUCURSAL</span></td> <td><span class="Estilo2">DEPOSITO</span></td> <td><span class="Estilo2">SUCURSAL DE VENTA</span></td> <td><span class="Estilo2">CHASIS</span></td> <td><span class="Estilo2">MODELO</span></td> <td><span class="Estilo2">COLOR</span></td> <td><span class="Estilo2">CERTIFICADO</span></td> <td><span class="Estilo2">MODELO CERTIFICADO</span></td> <?php if(($row_usuario_sesion['idGrupo'] == 1) || ($row_usuario_sesion['idGrupo'] == 2)){ ?> <td><span class="Estilo2">IMPORTE</span></td> <?php } ?> <td><span class="Estilo2">RESERVA</span></td> <td><span class="Estilo2">OBS. DE RESERVA</span></td> <td><span class="Estilo2">CLIENTE</span></td> <td><span class="Estilo2">FECHA SOLICITUD</span></td> <td><span class="Estilo2">FECHA ENTREGA</span></td> <td><span class="Estilo2">ENTREGA</span></td> <td><span class="Estilo2">PRECIO VENTA</span></td> <?php if(($row_usuario_sesion['idGrupo'] == 1) || ($row_usuario_sesion['idGrupo'] == 2)){ ?> <td><span class="Estilo2">INTERESES</span></td> <td><span class="Estilo2">ACCESORIOS</span></td> <td><span class="Estilo2">TOTAL</span></td> <td><span class="Estilo2">VENDEDOR</span></td> <td><span class="Estilo2">COMISION</span></td> <td><span class="Estilo2">USADO</span></td> <td><span class="Estilo2">BANCO</span></td> <?php } ?> <?php if($colname25_stock == 0) {?> <td><span class="Estilo21">DESCRIPCION</span></td> <td><span class="Estilo21">ENTRADA DE PEDIDO DE NADCOM</span></td> <td><span class="Estilo21">SEMANA DE PRODUCCION CONFIRMADA </span></td> <?php } ?> </tr> <?php do { ?> <tr class="Estilo1" bgcolor="<?php if($row_stock['pedido'] == 'PLAN DE AHORRO'){ echo "#D1FEC5"; } elseif($row_stock['pedido'] == 'VENTAS ESPECIALES' && $row_stock['nombrecliente'] == '<NAME> S.A. '){ echo "#D6FAFC"; } ?>"> <td height="20"><?php echo $row_stock['orden']; ?>&nbsp;</td> <td><?php echo $row_stock['mes']; ?> <?php echo $row_stock['anio']; ?>&nbsp;</td> <td><?php echo $row_stock['comision2']; ?></td> <td><?php echo $row_stock['numfactura']; ?></td> <td><?php echo $row_stock['sucursal']; ?></td> <td><?php echo $row_stock['deposito']; ?></td> <td><?php echo $row_stock['sucursalventa']; ?></td> <td><?php echo $row_stock['chasis']; ?>&nbsp;</td> <td><?php echo $row_stock['modelo']; ?>&nbsp;</td> <td><?php echo $row_stock['color']; ?></td> <td><?php echo $row_stock['nrocertif']; ?>&nbsp;</td> <td><?php echo $row_stock['modelocertif']; ?></td> <?php if(($row_usuario_sesion['idGrupo'] == 1) || ($row_usuario_sesion['idGrupo'] == 2)){ ?> <td><?php echo $row_stock['importefactcompra']; ?>&nbsp;</td> <?php } ?> <td>&nbsp; <?php if($row_stock['reserva'] == 1) { echo "si"; } elseif ($row_stock['reserva'] == NULL){echo " ";} elseif ($row_stock['reserva'] == 0){echo "no";} elseif ($row_stock['reserva'] == 2){echo "no disponible";}?></td> <td><?php echo $row_stock['observacionesreserva']; ?></td> <td><?php echo $row_stock['apellidoynombre']; ?>&nbsp;</td> <td><?php echo fecha($row_stock['fechasolicitud']); ?></td> <td><?php echo fecha($row_stock['fechaHoraEntrega']); ?></td> <td><?php if($row_stock['entrega'] == 1) { echo "si"; } else { echo "no";} ?></td> <td><?php echo $row_stock['precioventa']; ?></td> <?php if(($row_usuario_sesion['idGrupo'] == 1) || ($row_usuario_sesion['idGrupo'] == 2)){ ?> <td><?php echo $row_stock['intereses']; ?></td> <td><?php echo $row_stock['accesorios']; ?></td> <td><?php echo $row_stock['total']; ?></span>&nbsp;</td> <td><?php echo $row_stock['vendedor']; ?></td> <td><?php echo fecha($row_stock['comision']); ?></td> <td><?php echo $row_stock['usadomodelo']; ?></td> <td><?php echo $row_stock['banco']; ?></td> <?php } ?> <?php if($colname25_stock == 0) {?> <td><span class="Estilo11"><?php echo $row_stock['descripcion']; ?></span></td> <td><span class="Estilo11"><?php echo fecha($row_stock['entradapedidonadcon']); ?></span></td> <td><span class="Estilo11"><?php echo $row_stock['semanaproduccionconfirmada']; ?></span></td> <?php } ?> <?php } while ($row_stock = mysql_fetch_assoc($stock)); ?> </table> <blockquote class="Estilo1"> <div align="right">Cantidad de Registros <?php echo $totalRows_stock ?></div> <div align="left"> <?php echo date('d-m-Y H:i');?> </div> <div align="right"><a href="#"><img src="img/imprimir.gif" alt="Imprimir" width="26" height="23" border="0" onClick="MM_callJS('window.print();')"></a>&nbsp;&nbsp;<?php if(($row_usuario_sesion['idGrupo'] == 1) || ($row_usuario_sesion['idGrupo'] == 2)) { ?> <form action="<?php if($colname25_stock == '1') { ?>reporte_consultastock_exportar.php<?php } else { ?>reporte_consultastock_exportar_nofacturado.php<?php } ?>" method="post" name="formexcel" target="_blank" id="formexcel"> <a href="#"> <img src="img/xls.png" alt="Exportar a Excel" width="26" height="26" border="0" onClick="document.formexcel.submit(); "></a> <input name="query_stock" type="hidden" id="query_stock" value="<?php echo $query_stock;?>"> </form> <?php } ?></div> </blockquote> </body> </html> <?php mysql_free_result($stock); mysql_free_result($usuario_sesion); ?> <file_sep>/comisiones_vendedores.php <?php require_once('Connections/config.php'); ?> <?php require_once('funciones.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $currentPage = $_SERVER["PHP_SELF"]; $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); if(isset($_POST['MM_insert']) && ($_POST['MM_insert'] == 'formGuardar')){ if(isset($_POST['idvendedor']) && ($_POST['idvendedor'] > 0)){ $valor = $_POST['valor']; $registrovacio = 0; for($i=0;$i<count($valor);$i++) { if($valor[$i] == ''){ $registrovacio = 1; } } if ($registrovacio == 0) { $insertSQL = sprintf("INSERT INTO slc_comision_vw_vendedor_comision (idvendedor, idescala, fecha, idusuarioactualizacion, fechaactualizacion) VALUES (%s, %s, %s, %s, %s)", GetSQLValueString($_POST['idvendedor'], "int"), GetSQLValueString($_POST['idescala'], "int"), GetSQLValueString($_POST['anio'] . "-" . $_POST['mes'] . "-01", "date"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int"), GetSQLValueString(date('Y-m-d'), "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idvendedorcomision = mysql_insert_id($config); $idvariable=$_POST['idvariable']; $totalpuntos = 0; $sinpuntaje = 0; for($i=0;$i<count($valor);$i++) { $insertSQL = sprintf("INSERT INTO slc_comision_vw_vendedor_variable (idvendedorcomision, idvariable, valor) VALUES (%s, %s, %s)", GetSQLValueString($idvendedorcomision, "int"), GetSQLValueString($idvariable[$i], "int"), GetSQLValueString($valor[$i], "double")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $colname_registro6 = $idvariable[$i]; mysql_select_db($database_config, $config); $query_registro6 = sprintf("SELECT slc_comision_vw_variables.sinpuntos FROM slc_comision_vw_variables WHERE id = %s ", GetSQLValueString($colname_registro6, "int")); $registro6 = mysql_query($query_registro6, $config) or die(mysql_error()); $row_registro6 = mysql_fetch_assoc($registro6); $totalRows_registro6 = mysql_num_rows($registro6); $colname_registro = $idvariable[$i]; $colname2_registro = $valor[$i]; mysql_select_db($database_config, $config); $query_registro = sprintf("SELECT slc_comision_vw_variable_rangos.valor FROM slc_comision_vw_variable_rangos WHERE idvariable = %s AND (%s BETWEEN valor_desde AND valor_hasta) ORDER BY valor_desde ASC LIMIT 1", GetSQLValueString($colname_registro, "int"), GetSQLValueString($colname2_registro, "double")); $registro = mysql_query($query_registro, $config) or die(mysql_error()); $row_registro = mysql_fetch_assoc($registro); $totalRows_registro = mysql_num_rows($registro); $totalpuntos = $totalpuntos + $row_registro['valor']; if(($totalRows_registro == 0) && ($row_registro6['sinpuntos'] == '1')) { $sinpuntaje = 1; } } if($sinpuntaje == 1) { $totalpuntos = 0; } $colname_registro2 = $totalpuntos; mysql_select_db($database_config, $config); $query_registro2 = sprintf("SELECT porcentaje FROM slc_comision_vw_puntaje_rangos WHERE (%s BETWEEN puntajedesde AND puntajehasta) ORDER BY puntajedesde ASC LIMIT 1", GetSQLValueString($colname_registro2, "double")); $registro2 = mysql_query($query_registro2, $config) or die(mysql_error()); $row_registro2 = mysql_fetch_assoc($registro2); $totalRows_registro2 = mysql_num_rows($registro2); if($row_registro2['porcentaje'] > 0) { $porcentaje = $row_registro2['porcentaje']; } else { $porcentaje = 0; } $updateSQL = sprintf("UPDATE slc_comision_vw_vendedor_comision SET totalpuntos=%s, puntajeporcentaje=%s, idusuarioactualizacion=%s, fechaactualizacion=%s WHERE id=%s", GetSQLValueString($totalpuntos, "double"), GetSQLValueString($porcentaje, "double"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int"), GetSQLValueString(date('Y-m-d'), "date"), GetSQLValueString($idvendedorcomision, "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } } } if(isset($_POST['MM_update']) && ($_POST['MM_update'] == 'formGuardar')){ $valor = $_POST['valor']; $registrovacio = 0; for($i=0;$i<count($valor);$i++) { if($valor[$i] == ''){ $registrovacio = 1; } } if ($registrovacio == 0) { $idvendedorvariable=$_POST['idvendedorvariable']; $idvariable=$_POST['idvariable']; $totalpuntos = 0; for($i=0;$i<count($valor);$i++) { $updateSQL = sprintf("UPDATE slc_comision_vw_vendedor_variable SET valor=%s WHERE id=%s", GetSQLValueString($valor[$i], "int"), GetSQLValueString($idvendedorvariable[$i], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $colname_registro6 = $idvariable[$i]; mysql_select_db($database_config, $config); $query_registro6 = sprintf("SELECT slc_comision_vw_variables.sinpuntos FROM slc_comision_vw_variables WHERE id = %s ", GetSQLValueString($colname_registro6, "int")); $registro6 = mysql_query($query_registro6, $config) or die(mysql_error()); $row_registro6 = mysql_fetch_assoc($registro6); $totalRows_registro6 = mysql_num_rows($registro6); $colname_registro = $idvariable[$i]; $colname2_registro = $valor[$i]; mysql_select_db($database_config, $config); $query_registro = sprintf("SELECT slc_comision_vw_variable_rangos.valor FROM slc_comision_vw_variable_rangos WHERE idvariable = %s AND (%s BETWEEN valor_desde AND valor_hasta) ORDER BY valor_desde ASC LIMIT 1", GetSQLValueString($colname_registro, "int"), GetSQLValueString($colname2_registro, "double")); $registro = mysql_query($query_registro, $config) or die(mysql_error()); $row_registro = mysql_fetch_assoc($registro); $totalRows_registro = mysql_num_rows($registro); $totalpuntos = $totalpuntos + $row_registro['valor']; if(($totalRows_registro == 0) && ($row_registro6['sinpuntos'] == '1')) { $sinpuntaje = 1; } } if($sinpuntaje == 1) { $totalpuntos = 0; } $colname_registro2 = $totalpuntos; mysql_select_db($database_config, $config); $query_registro2 = sprintf("SELECT porcentaje FROM slc_comision_vw_puntaje_rangos WHERE (%s BETWEEN puntajedesde AND puntajehasta) ORDER BY puntajedesde ASC LIMIT 1", GetSQLValueString($colname_registro2, "double")); $registro2 = mysql_query($query_registro2, $config) or die(mysql_error()); $row_registro2 = mysql_fetch_assoc($registro2); $totalRows_registro2 = mysql_num_rows($registro2); if($row_registro2['porcentaje'] > 0) { $porcentaje = $row_registro2['porcentaje']; } else { $porcentaje = 0; } $updateSQL = sprintf("UPDATE slc_comision_vw_vendedor_comision SET totalpuntos=%s, puntajeporcentaje=%s, idusuarioactualizacion=%s, fechaactualizacion=%s WHERE id=%s", GetSQLValueString($totalpuntos, "double"), GetSQLValueString($porcentaje, "double"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int"), GetSQLValueString(date('Y-m-d'), "date"), GetSQLValueString($_POST['idvendedorcomision'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } } if(isset($_POST['MM_close']) && ($_POST['MM_close'] == 'formCerrar')){ $updateSQL = sprintf("UPDATE slc_comision_vw_vendedor_comision SET estado=%s, estadoidusuario=%s, estadofecha=%s WHERE idescala=%s AND fecha=%s", GetSQLValueString('1', "int"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int"), GetSQLValueString(date('Y-m-d'), "date"), GetSQLValueString($_POST['idescala'], "int"), GetSQLValueString($_POST['anio'] . "-" . $_POST['mes'] . "-01", "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } if(isset($_POST['MM_close']) && ($_POST['MM_close'] == 'formAbrir')){ $updateSQL = sprintf("UPDATE slc_comision_vw_vendedor_comision SET estado=%s, estadoidusuario=%s, estadofecha=%s WHERE idescala=%s AND fecha=%s", GetSQLValueString('0', "int"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int"), GetSQLValueString(date('Y-m-d'), "date"), GetSQLValueString($_POST['idescala'], "int"), GetSQLValueString($_POST['anio'] . "-" . $_POST['mes'] . "-01", "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } if(isset($_POST['MM_delete']) && ($_POST['MM_delete'] == 'formGuardar')){ $deleteSQL = sprintf("DELETE FROM slc_comision_vw_vendedor_variable WHERE idvendedorcomision=%s", GetSQLValueString($_POST['idvendedorcomision'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); $deleteSQL = sprintf("DELETE FROM slc_comision_vw_vendedor_comision WHERE id=%s", GetSQLValueString($_POST['idvendedorcomision'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); } mysql_select_db($database_config, $config); $query_registros = "SELECT idUsuario, nombre FROM slc_stocksud_usuario WHERE activo = 1 AND idGrupo = 3 ORDER BY nombre ASC"; $registros = mysql_query($query_registros, $config) or die(mysql_error()); $row_registros = mysql_fetch_assoc($registros); $totalRows_registros = mysql_num_rows($registros); $colname_registros2 = "-1"; if (isset($_GET['id'])) { $colname_registros2 = $_GET['id']; } mysql_select_db($database_config, $config); $query_registros2 = sprintf("SELECT slc_comision_vw_variables.id, slc_comision_vw_variables.nombre FROM slc_comision_vw_escala_variable LEFT JOIN slc_comision_vw_variables ON slc_comision_vw_variables.id = slc_comision_vw_escala_variable.idvariable WHERE idescala = %s ORDER BY slc_comision_vw_variables.nombre ASC", GetSQLValueString($colname_registros2, "int")); $registros2 = mysql_query($query_registros2, $config) or die(mysql_error()); $row_registros2 = mysql_fetch_assoc($registros2); $totalRows_registros2 = mysql_num_rows($registros2); $colname_registros3 = "-1"; if (isset($_GET['id'])) { $colname_registros3 = $_GET['id']; } mysql_select_db($database_config, $config); $query_registros3 = sprintf("SELECT slc_comision_vw_variables.id, slc_comision_vw_variables.nombre FROM slc_comision_vw_escala_variable LEFT JOIN slc_comision_vw_variables ON slc_comision_vw_variables.id = slc_comision_vw_escala_variable.idvariable WHERE idescala = %s ORDER BY slc_comision_vw_variables.nombre ASC", GetSQLValueString($colname_registros3, "int")); $registros3 = mysql_query($query_registros3, $config) or die(mysql_error()); $row_registros3 = mysql_fetch_assoc($registros3); $totalRows_registros3 = mysql_num_rows($registros3); $colname_registros4 = "-1"; if (isset($_GET['id'])) { $colname_registros4 = $_GET['id']; } $colname2_registros4 = "-1"; if (isset($_GET['mes'])) { $colname2_registros4 = $_GET['mes']; } $colname3_registros4 = "-1"; if (isset($_GET['anio'])) { $colname3_registros4 = $_GET['anio']; } mysql_select_db($database_config, $config); $query_registros4 = sprintf("SELECT slc_comision_vw_vendedor_comision.id, slc_comision_vw_vendedor_comision.totalpuntos, slc_comision_vw_vendedor_comision.puntajeporcentaje, slc_stocksud_usuario.nombre AS vendedor, slc_comision_vw_vendedor_comision.idvendedor, slc_comision_vw_vendedor_comision.estado, slc_comision_vw_escalas.nombre FROM slc_comision_vw_vendedor_comision LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_comision_vw_vendedor_comision.idvendedor LEFT JOIN slc_comision_vw_escalas ON slc_comision_vw_escalas.id = slc_comision_vw_vendedor_comision.idescala WHERE slc_comision_vw_vendedor_comision.idescala = %s AND slc_comision_vw_vendedor_comision.fecha = %s ", GetSQLValueString($colname_registros4, "int"),GetSQLValueString($colname3_registros4 . "-" . $colname2_registros4 . "-01", "date")); if($row_usuario_sesion['idGrupo'] == '3') { $query_registros4 .= " AND slc_comision_vw_vendedor_comision.idvendedor = " . $row_usuario_sesion['idUsuario']; } $registros4 = mysql_query($query_registros4, $config) or die(mysql_error()); $row_registros4 = mysql_fetch_assoc($registros4); $totalRows_registros4 = mysql_num_rows($registros4); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo21 {color: #333333; font-weight: bold; } --> </style> <script type="text/javascript"> function MM_validateForm() { //v4.0 if (document.getElementById){ var i,p,q,nm,tl,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); tl=val.title; if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- El '+tl+' es requerido.\n'; } } if (errors) alert('Error:\n'+errors); document.MM_returnValue = (errors == ''); } } </script> <!--ajax-autocomplete --> <script type="text/javascript" src="ajax-autocomplete/jquery.js"></script> <script type='text/javascript' src='ajax-autocomplete/jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="ajax-autocomplete/jquery.autocomplete.css" /> <script type="text/javascript"> $().ready(function() { $("#nombre").autocomplete("comisiones_buscar_escala.php?idescala=<?php echo $_GET['id'];?>", { width: 325, matchContains: true, //mustMatch: true, //minChars: 0, //multiple: true, //highlight: false, //multipleSeparator: ",", selectFirst: false }); $("#nombre").result(function(event, data, formatted) { $("#nombre").val(data[1]); $("#id").val(data[2]); }); $("#vendedor").autocomplete("comisiones_buscar_vendedor.php?mes=<?php echo $_GET['mes'];?>&anio=<?php echo $_GET['anio'];?>", { width: 325, matchContains: true, //mustMatch: true, //minChars: 0, //multiple: true, //highlight: false, //multipleSeparator: ",", selectFirst: false }); $("#vendedor").result(function(event, data, formatted) { $("#vendedor").val(data[1]); $("#idvendedor").val(data[2]); }); }); </script> <!--ajax-autocomplete --> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } </script> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="396" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD</span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td height="292" colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td><table width="100%" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>COMISIONES DE VENDEDORES</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td bgcolor="#FFFFFF"><table width="100%" cellpadding="0" cellspacing="4"> <tr> <td class="Estilo11"> <table width="100%" align="left" cellpadding="0" cellspacing="0"> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="7" class="Estilo11"><table width="100%" cellspacing="0" cellpadding="0"> <form action="comisiones_vendedores.php" method="GET" name="formBuscar" id="formBuscar"> <tr> <td valign="middle" class="Estilo11"><span class="Estilo21">ESCALA</span> <input name="nombre" type="text" class="Estilo11" id="nombre" value="<?php if(isset($_GET['nombre'])) { echo $_GET['nombre'];};?>" size="50" maxlength="100"> <span class="Estilo21"> <input name="id" type="hidden" id="id" value="<?php echo $_GET['id'];?>"> MES</span><span class="texto"> <select name="mes" class="Estilo11" id="mes"> <option value="01" <?php if(isset($_GET['mes'])) { if (!(strcmp("01", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>01</option> <option value="02" <?php if(isset($_GET['mes'])) { if (!(strcmp("02", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>02</option> <option value="03" <?php if(isset($_GET['mes'])) { if (!(strcmp("03", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>03</option> <option value="04" <?php if(isset($_GET['mes'])) { if (!(strcmp("04", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>04</option> <option value="05" <?php if(isset($_GET['mes'])) { if (!(strcmp("05", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>05</option> <option value="06" <?php if(isset($_GET['mes'])) { if (!(strcmp("06", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>06</option> <option value="07" <?php if(isset($_GET['mes'])) { if (!(strcmp("07", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>07</option> <option value="08" <?php if(isset($_GET['mes'])) { if (!(strcmp("08", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>08</option> <option value="09" <?php if(isset($_GET['mes'])) { if (!(strcmp("09", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>09</option> <option value="10" <?php if(isset($_GET['mes'])) { if (!(strcmp("10", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>10</option> <option value="11" <?php if(isset($_GET['mes'])) { if (!(strcmp("11", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>11</option> <option value="12" <?php if(isset($_GET['mes'])) { if (!(strcmp("12", $_GET['mes']))) {echo "selected=\"selected\"";} }?>>12</option> </select> <span class="Estilo21">A&Ntilde;O</span> <select name="anio" class="Estilo11" id="anio"> if (!(strcmp(date ("Y")-3, $_GET['anio']))) {echo "selected=\"selected\"";}} ?>><?php echo date ("Y")-3;?></option> <option value="<?php echo date ("Y")-2;?>" <?php if(isset($_GET['anio'])){ if (!(strcmp(date ("Y")-2, $_GET['anio']))) {echo "selected=\"selected\"";}} ?>><?php echo date ("Y")-2;?></option> <option value="<?php echo date ("Y")-1;?>" <?php if(isset($_GET['anio'])){ if (!(strcmp(date ("Y")-1, $_GET['anio']))) {echo "selected=\"selected\"";}} ?>><?php echo date ("Y")-1;?></option> <option value="<?php echo date ("Y");?>" <?php if(isset($_GET['anio'])){ if (!(strcmp(date ("Y"), $_GET['anio']))) {echo "selected=\"selected\"";}} ?>><?php echo date ("Y");?></option> <option value="<?php echo date ("Y")+1;?>" <?php if(isset($_GET['anio'])){ if (!(strcmp(date ("Y")+1, $_GET['anio']))) {echo "selected=\"selected\"";}} ?>><?php echo date ("Y")+1;?></option> </select> </span> <input name="Submit" type="submit" class="Estilo11" value="Buscar"></td> </tr> </form> <?php if($totalRows_registros4 > 0) { ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="formCerrar" id="formCerrar"> <tr> <td height="30" align="center" valign="middle" class="Estilo21"><?php echo $row_registros4['nombre'] . " " . $_GET['mes'] . "/" . $_GET['anio']; ?> <?php if($row_usuario_sesion['idGrupo'] == 1) { ?> <?php if($row_registros4['estado'] == 0) { ?> <a href="#"><img src="img/security_f2.png" alt="Cerrar" width="18" height="18" title="Cerrar" onClick="document.formCerrar.MM_close.value = 'formCerrar';document.formCerrar.submit();" border="0"></a> <?php } ?> <?php if($row_registros4['estado'] == 1) { ?> <a href="#"><img src="img/security_f3.png" alt="Abrir" width="18" height="18" title="Abrir" onClick="document.formCerrar.MM_close.value = 'formAbrir';document.formCerrar.submit();" border="0"></a> <?php } ?> <?php } ?> <input name="idescala" type="hidden" id="idescala" value="<?php echo $_GET['id'];?>"> <input name="mes" type="hidden" id="mes" value="<?php echo $_GET['mes'];?>"> <input name="anio" type="hidden" id="anio" value="<?php echo $_GET['anio'];?>"> <input name="MM_close" type="hidden" id="MM_close" value="formGuardar"></td> </tr> </form> <?php } ?> </table></td> </tr> <?php if($row_usuario_sesion['idGrupo'] != '3') { ?> <?php if ($totalRows_registros2 > 0) { // Show if recordset not empty ?> <?php if($row_registros4['estado'] == 0) { ?> <tr valign="middle"> <td> <form action="comisiones_vendedores_importador.php" method="POST" enctype="multipart/form-data" name="formImportar" id="formImportar" onSubmit="if(confirm ('Se agregar&aacute;n los datos en la base de datos.')) { MM_validateForm('pathArchivo','','R');return document.MM_returnValue;} else {history.go(0);return '';}"> <input name="pathArchivo" type="file" class="Estilo11" id="pathArchivo" title="archivo a impotar"> <span class="Estilo21"> <input name="idescala" type="hidden" id="idescala" value="<?php echo $_GET['id'];?>"> <input name="mes" type="hidden" id="mes" value="<?php echo $_GET['mes'];?>"> <input name="anio" type="hidden" id="anio" value="<?php echo $_GET['anio'];?>"> <input name="idUsuario" type="hidden" id="idUsuario" value="<?php echo $row_usuario_sesion['idUsuario']; ?>"> </span> <input name="Importar" type="submit" class="Estilo11" id="Importar" value="Importar"> <input name="descargar" type="button" class="Estilo11" id="descargar" onClick="MM_openBrWindow('comisiones_vendedores_generar_excel.php?id=<?php echo $_GET['id'];?> ','','')" value="Descargar plantilla comisiones"> </form> </td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" class="Estilo11"><span class="Estilo21">VENDEDOR</span></td> <?php do { ?> <td bgcolor="#EFEFEF" class="Estilo11"><span class="Estilo21"><?php echo $row_registros2['nombre']; ?></span></td> <?php } while ($row_registros2 = mysql_fetch_assoc($registros2)); ?> <?php } // Show if recordset not empty ?> <td align="center" class="Estilo11"></td> </tr> <?php } ?> <?php $colname_registros2 = "-1"; if (isset($_GET['id'])) { $colname_registros2 = $_GET['id']; } mysql_select_db($database_config, $config); $query_registros2 = sprintf("SELECT slc_comision_vw_variables.id, slc_comision_vw_variables.nombre FROM slc_comision_vw_escala_variable LEFT JOIN slc_comision_vw_variables ON slc_comision_vw_variables.id = slc_comision_vw_escala_variable.idvariable WHERE idescala = %s ORDER BY slc_comision_vw_variables.nombre ASC", GetSQLValueString($colname_registros2, "int")); $registros2 = mysql_query($query_registros2, $config) or die(mysql_error()); $row_registros2 = mysql_fetch_assoc($registros2); $totalRows_registros2 = mysql_num_rows($registros2); ?> <?php if ($totalRows_registros2 > 0) { // Show if recordset not empty ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="formGuardar" id="formGuardar"> <?php if($row_registros4['estado'] == 0) { ?> <tr valign="middle"> <td height="20" class="Estilo11"><input name="vendedor" type="text" class="Estilo11" id="vendedor" > <input name="idvendedor" type="hidden" id="idvendedor"></td> <?php do { ?> <td class="Estilo11"><input name="valor[]" type="text" class="Estilo11" id="valor[]" size="6" maxlength="11" <?php if($row_usuario_sesion['idGrupo'] == '3') { ?>readonly="readonly"<?php } ?>><input name="idvariable[]" type="hidden" id="idvariable[]" value="<?php echo $row_registros2['id']; ?>"></td> <?php } while ($row_registros2 = mysql_fetch_assoc($registros2)); ?> <td align="center" class="Estilo11"> <a href="#"><img src="img/agregar.gif" alt="Nuevo" width="15" height="15" title="Nuevo" onClick="document.formGuardar.submit();" border="0"></a> <input name="idescala" type="hidden" id="idescala" value="<?php echo $_GET['id'];?>"> <input name="mes" type="hidden" id="mes" value="<?php echo $_GET['mes'];?>"> <input name="anio" type="hidden" id="anio" value="<?php echo $_GET['anio'];?>"> <input type="hidden" name="MM_insert" value="formGuardar"> </td> </tr> <?php } ?> </form> <?php } // Show if recordset not empty ?> <?php } ?> </table> </td> </tr> <tr> <td> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <?php if ($totalRows_registros3 > 0) { // Show if recordset not empty ?> <tr bgcolor="#EFEFEF" class="Estilo11"> <td height="20" class="Estilo21">VENDEDOR</td> <?php do { ?> <td align="center" bgcolor="#EFEFEF"><span class="Estilo21"><?php echo $row_registros3['nombre']; ?></span></td> <?php } while ($row_registros3 = mysql_fetch_assoc($registros3)); ?> <td align="center" bgcolor="#EFEFEF" class="Estilo21">TOTAL PUNTOS</td> <td align="center" bgcolor="#EFEFEF" class="Estilo21">PREMIO %</td> <td class="Estilo21">&nbsp;</td> </tr> <?php if ($totalRows_registros4 > 0) { // Show if recordset not empty ?> <?php do { ?> <?php $colname_registros3 = "-1"; if (isset($_GET['id'])) { $colname_registros3 = $_GET['id']; } mysql_select_db($database_config, $config); $query_registros3 = sprintf("SELECT slc_comision_vw_variables.id, slc_comision_vw_variables.nombre FROM slc_comision_vw_escala_variable LEFT JOIN slc_comision_vw_variables ON slc_comision_vw_variables.id = slc_comision_vw_escala_variable.idvariable WHERE idescala = %s ORDER BY slc_comision_vw_variables.nombre ASC", GetSQLValueString($colname_registros3, "int")); $registros3 = mysql_query($query_registros3, $config) or die(mysql_error()); $row_registros3 = mysql_fetch_assoc($registros3); $totalRows_registros3 = mysql_num_rows($registros3); ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="formGuardar<?php echo $row_registros4['idvendedor']; ?>" id="formGuardar"> <tr class="Estilo11"> <td height="20"><?php echo ucwords($row_registros4['vendedor']); ?></td> <?php do { ?> <?php $colname_registros5 = $row_registros4['id']; $colname2_registros5 = $row_registros3['id']; mysql_select_db($database_config, $config); $query_registros5 = sprintf("SELECT slc_comision_vw_vendedor_variable.id AS idvendedorvariable, slc_comision_vw_vendedor_variable.valor FROM slc_comision_vw_vendedor_variable WHERE slc_comision_vw_vendedor_variable.idvendedorcomision = %s AND slc_comision_vw_vendedor_variable.idvariable = %s", GetSQLValueString($colname_registros5, "int"), GetSQLValueString($colname2_registros5, "int")); $registros5 = mysql_query($query_registros5, $config) or die(mysql_error()); $row_registros5 = mysql_fetch_assoc($registros5); $totalRows_registros5 = mysql_num_rows($registros5); ?> <td align="center"> <input name="valor[]" type="text" class="Estilo11" id="valor[]" value="<?php echo $row_registros5['valor']; ?>" size="6" maxlength="11" <?php if($row_registros4['estado'] == 1) { echo "readonly";}?> <?php if($row_usuario_sesion['idGrupo'] == '3') { echo "readonly";} ?>> <input name="idvendedorvariable[]" type="hidden" id="idvendedorvariable[]" value="<?php echo $row_registros5['idvendedorvariable']; ?>"> <input name="idvariable[]" type="hidden" id="idvariable[]" value="<?php echo $row_registros3['id']; ?>"> <input name="idvendedorcomision" type="hidden" id="idvendedorcomision" value="<?php echo $row_registros4['id']; ?>"></td> <?php } while ($row_registros3 = mysql_fetch_assoc($registros3)); ?> <td align="center"><?php echo $row_registros4['totalpuntos']; ?></td> <td align="center"><?php echo $row_registros4['puntajeporcentaje']; ?></td> <td align="right" valign="middle"> <?php if($row_usuario_sesion['idGrupo'] != '3') { ?> <?php if($row_registros4['estado'] == 0) { ?> <a href="#"><img src="img/save_f2.png" alt="Guardar" width="18" height="18" title="Guardar" onClick="document.formGuardar<?php echo $row_registros4['idvendedor']; ?>.MM_update.value = 'formGuardar';document.formGuardar<?php echo $row_registros4['idvendedor']; ?>.submit();" border="0"></a> <input name="MM_update" type="hidden" id="MM_update">&nbsp; <a href="#"><img src="img/cancelar.png" alt="Borrar" width="18" height="18" title="Borrar" onClick="document.formGuardar<?php echo $row_registros4['idvendedor']; ?>.MM_delete.value = 'formGuardar';document.formGuardar<?php echo $row_registros4['idvendedor']; ?>.submit();" border="0"></a> <input name="MM_delete" type="hidden" id="MM_delete"> <?php } ?> <?php } ?> </td> </tr> </form> <?php } while ($row_registros4 = mysql_fetch_assoc($registros4)); ?> <?php } // Show if recordset not empty ?> <tr valign="middle"> <td height="1" colspan="<?php echo ($totalRows_registros2 + 5);?>" bgcolor="#969393"></td> </tr> <?php } // Show if recordset not empty ?> </table > </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); mysql_free_result($registros2); mysql_free_result($registros4); ?> <file_sep>/stock_comision_importador.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); ?> <?php $mensaje = ""; if ((isset($_POST["Importar3"])) && ($_POST["Importar3"] == "Importar Comisiones")) { if($_FILES['pathArchivo3']['name']!=''){ if($_FILES['pathArchivo3']['size']){ $type = explode(".", $_FILES['pathArchivo3']['name']); if($type[1] == 'csv'){ $fp = fopen ($_FILES['pathArchivo3']['tmp_name'],"r"); if ($fp != false) { if(count(fgetcsv($fp,1000,',')) > 1) { $separador = ','; } elseif(count(fgetcsv($fp,1000,';')) > 1) { $separador = ';'; } } fclose ($fp); $fp = fopen ($_FILES['pathArchivo3']['tmp_name'],"r"); if ($fp != false) { if( !ini_get('safe_mode') ){ set_time_limit(90); } $estableceri = 0; while ($data = fgetcsv ($fp, 1000, $separador)) { $i = 0; if($estableceri == 0) { foreach($data as $row) { switch (trim(strtolower($row))) { case 'comision': $icomision = $i; break; case 'vin': $ivin = $i; break; case 'importe comision': $iimportecomision = $i; break; } $i++ ; } $estableceri = 1; } else { $comision_temp = $data[$icomision]; $comision_temp = explode("/",$comision_temp); $comision[] = $comision_temp[2] . "-" . $comision_temp[1] . "-" . $comision_temp[0]; $vin[] = $data[$ivin]; $importecomision[] = $data[$iimportecomision]; } } fclose ($fp); $cant=count($vin); if(isset($_POST['actualizar']) && ($_POST['actualizar'] == 1)) { for ($i=0; $i<$cant; $i++){ mysql_select_db($database_config, $config); $query_stock_VIN = sprintf("SELECT idstock, comision FROM slc_stocksud_stock WHERE chasis = %s", GetSQLValueString($vin[$i] , "text")); $stock_VIN = mysql_query($query_stock_VIN, $config) or die(mysql_error()); $row_stock_VIN = mysql_fetch_assoc($stock_VIN); $totalRows_stock_VIN = mysql_num_rows($stock_VIN); if(($totalRows_stock_VIN > 0) && ($comision[$i] != '') && ($row_stock_VIN['comision'] == '' || $row_stock_VIN['comision'] == '0000-00-00' || $row_stock_VIN['comision'] == '0000-00-01')) { $updateSQL = sprintf("UPDATE slc_stocksud_stock SET comision=%s WHERE idstock=%s", GetSQLValueString($comision[$i], "date"), GetSQLValueString($row_stock_VIN['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $mensajeimporto .= $vin[$i] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $comision[$i] . "<br>"; } else { $mensajenoimporto .= $vin[$i] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $comision[$i] . "<br>"; } if(($totalRows_stock_VIN > 0) && ($row_stock_VIN['importecomision'] == '') && ($importecomision[$i] != '')) { $updateSQL = sprintf("UPDATE slc_stocksud_stock SET importecomision=%s WHERE idstock=%s", GetSQLValueString($importecomision[$i], "double"), GetSQLValueString($row_stock_VIN['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $mensajeimportoimpcomision .= $vin[$i] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $importecomision[$i] . "<br>"; } } $mensaje="Se importaron los datos."; } else { $preguntaactualizar = 0; for ($i=0; $i<$cant; $i++){ mysql_select_db($database_config, $config); $query_stock_VIN = sprintf("SELECT idstock, comision FROM slc_stocksud_stock WHERE chasis = %s", GetSQLValueString($vin[$i] , "text")); $stock_VIN = mysql_query($query_stock_VIN, $config) or die(mysql_error()); $row_stock_VIN = mysql_fetch_assoc($stock_VIN); $totalRows_stock_VIN = mysql_num_rows($stock_VIN); if(($totalRows_stock_VIN > 0) && ($comision[$i] != '') && ($row_stock_VIN['comision'] == '' || $row_stock_VIN['comision'] == '0000-00-00' || $row_stock_VIN['comision'] == '0000-00-01')){ $preguntaactualizar = 1; } } } } else { $mensaje="Error al abrir el archivo."; } } else { $mensaje="El archivo seleccionado debe ser CSV (delimitado por comas)."; } } else { $mensaje="El archivo seleccionado no es correcto."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> function MM_goToURL() { //v3.0 var i, args=MM_goToURL.arguments; document.MM_returnValue = false; for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'"); } </script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD </span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>STOCK COMISIONES</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td height="220" valign="top" bgcolor="#FFFFFF"><table width="100%" height="100%" cellpadding="0" cellspacing="4"> <?php if($mensaje != "") {?> <tr> <td valign="top" class="Estilo1"><?php if($mensaje != "") {echo $mensaje;}?></td> </tr> <?php } ?> <?php if($preguntaactualizar == 1){ ?> <tr> <td valign="top" class="Estilo1"> <form action="stock_comision_importador.php" method="POST" enctype="multipart/form-data" name="formImportar3" id="formImportar3" onSubmit="if(confirm ('Se agregar&aacute;n los datos en la base de datos.')) { MM_validateForm('pathArchivo3','','R');return document.MM_returnValue;} else {history.go(0);return '';}"> Se actualizarán comisiones, ¿desea actualizarlas? <br> <input name="pathArchivo3" type="file" class="Estilo11" id="pathArchivo3" title="archivo a impotar"> <input name="actualizar" type="hidden" id="actualizar" value="1"> <input name="Importar3" type="submit" class="Estilo11" id="Importar3" value="Importar Comisiones"> <input name="noimportar" type="button" class="Estilo11" id="noimportar" onClick="MM_goToURL('parent','stock.php');return document.MM_returnValue" value="No importar"> </form> </td> </tr> <?php } ?> <?php if($mensajeimporto != ''){ ?> <tr> <td valign="top" class="Estilo1">Las comisiones siguientes se actualizaron: <br> <strong>VIN &nbsp;&nbsp;&nbsp;&nbsp;COMISION</strong><br> <?php echo $mensajeimporto;?></td> </tr> <?php } ?> <?php if($mensajenoimporto != ''){ ?> <tr> <td valign="top" class="Estilo1">Las comisiones siguientes no se actualizaron: <br><strong>VIN &nbsp;&nbsp;&nbsp;&nbsp;COMISION</strong><br> <?php echo $mensajenoimporto;?></td> </tr> <?php } ?> <?php if($mensajeimportoimpcomision != ''){ ?> <tr> <td valign="top" class="Estilo1">Los importes de comisión siguientes se actualizaron: <br><strong>VIN &nbsp;&nbsp;&nbsp;&nbsp;IMPORTE COMISION</strong><br> <?php echo $mensajeimportoimpcomision;?></td> </tr> <?php } ?> </table> </td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); ?> <file_sep>/comisiones_buscar_vendedor.php <?php require_once('Connections/config.php'); ?> <?php require_once('funciones.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_registros = "-1"; if (isset($_GET['q'])) { $colname_registros = utf8_encode($_GET['q']); } else { return; } $colname2_registros = "-1"; if (isset($_GET['mes'])) { $colname2_registros = $_GET['mes']; } $colname3_registros = "-1"; if (isset($_GET['anio'])) { $colname3_registros = $_GET['anio']; } mysql_select_db($database_config, $config); $query_registros = sprintf("SELECT * FROM slc_stocksud_usuario WHERE nombre LIKE %s AND activo = 1 AND idGrupo = 3 AND NOT EXISTS (SELECT idvendedor FROM slc_comision_vw_vendedor_comision WHERE slc_comision_vw_vendedor_comision.idvendedor = slc_stocksud_usuario.idUsuario AND slc_comision_vw_vendedor_comision.fecha LIKE %s) ORDER BY nombre", GetSQLValueString("%" . $colname_registros . "%", "text"), GetSQLValueString($colname3_registros . "-" . $colname2_registros ."-01", "date")); $registros = mysql_query($query_registros, $config) or die(mysql_error()); $row_registros = mysql_fetch_assoc($registros); $totalRows_registros = mysql_num_rows($registros); if ($totalRows_registros > 0) { // Show if recordset not empty do { echo $row_registros['nombre'] . "|" . $row_registros['nombre']. "|" . $row_registros['idUsuario'] . "\n"; } while ($row_registros = mysql_fetch_assoc($registros)); } // Show if recordset not empty mysql_free_result($registros); ?><file_sep>/xc2/examples/func.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Xin Calendar 2 Step-by-step: The user functions</title> <link rel=stylesheet href="xc2.css" type="text/css"> <link rel=stylesheet href="../css/xc2_default.css" type="text/css"> <script language="javascript" src="../config/xc2_default.js"></script> <script language="javascript" src="../script/xc2_inpage.js"></script> <script language="javascript"> function getDateValue(id) { return document.getElementById(id).innerHTML; } function setDateValue(id, date) { document.getElementById(id).innerHTML=date; } </script> </head> <body> <p align="center" class="title">Xin Calendar 2 Step-by-step: The user functions</p> <p align="center" class="copyright"><a href="http://www.yxscripts.com">yxScripts.com</a></p> <p class="para">Please pick a date: [ <span title="Click me" style="cursor:pointer;" id="holder" onclick="showCalendar('', 'holder', 'holder', '', 'holder', -55, 20, 1)">2004-08-01</span> ]</p> <p class="para">Besides the helper functions, Xin Calendar 2 also provides some user functions that can be overwritten for customization purposes:</p> <ul> <li>beforeGetDateValue(ref_field, target_field) ... a void function, executes before the calendar gets the value of ref_field.</li> <ol> <li>ref_field ... defined in the showCalendar() call, the date field whose value is the date reference for the calendar</li> <li>target_field ... defined in the showCalendar() call, the date field whose value will be set by the calendar</li> </ol><br> <li>afterGetDateValue(ref_field, target_field, date) ... simply returns the [ date ] given, executes after the calendar gets the value of ref_field.</li> <ol> <li>ref_field ... same as above</li> <li>target_field ... same as above</li> <li>date ... the field value from the ref_field</li> </ol><br> <li>getDateValue(field) ... returns [ field.value ], the calendar calls it to get the value of the given field object.<br><br></li> <li>beforeSetDateValue(ref_field, target_field, date) ... returns the [ date ], executes before the calendar sets the value for target_field.<br><br></li> <li>afterSetDateValue(ref_field, target_field, date) ... a void function, executes after the calendar sets the value for target_field.<br><br></li> <li>setDateValue(field, date) ... simply executes [ field.value = date ], the calendar calls it to set the value for target_field.</li> </ul><br> <p class="para">For example, we want to alert the date picked instead of updating a date field, then we can have:</p> <pre> &lt;script language="javascript" src="../script/xc2_inpage.js"&gt;&lt;/script&gt; &lt;script language="javascript"&gt; function setDateValue(field, date) { alert("You have picked: "+date); } &lt;/script&gt; </pre><br> <p class="para">We can also pass a function handler as the [ target_field ] parameter in the showCalendar() call and execute that function with the date picked as the parameter:</p> <pre> ... &lt;script language="javascript"&gt; function setDateValue(func, date) { func(date); } &lt;/script&gt; ... &lt;input ... onfocus="showCalendar('', <font color="red">alert</font>, this, '', 'holder', 0, 0, 1)"&gt; </pre><br> <p class="para">Likewise, we can customize the getDateValue() function to change the way a date reference is read. Thus, if we have the following setup, we can associate a calendar to a SPAN tag just like the one on page top:</p> <pre> function getDateValue(id) { return document.getElementById(id).innerHTML; } function setDateValue(id, date) { document.getElementById(id).innerHTML=date; } ... &lt;SPAN ID="cal_tag" onclick="showCalendar('', 'cal_tag', 'cal_tag', ..., 1)"&gt;2004-08-01&lt;/SPAN&gt; </pre> <p class="para">[<a href="bottom.html">Scrolling arrows on bottom</a>]&nbsp;[<a href="../index.html#steps">Back to index page</a>]</p> <p align="center"># # #</p> <p>&nbsp;</p> </body> </html> <file_sep>/stock_envio_mail.php <?php require_once('Connections/config.php'); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 11px; color: #666666; } .Estilo2 { color: #333333; font-size: 14px; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><BR> <table width="99%" border="0" align="center"> <tr class="Estilo1"> <td width="40%" align="center" valign="middle" class="Estilo1"><img src="<?php echo $relative_path;?>img/presupuesto_logo_VW.jpg" width="300" height="68" alt=""/></td> <td width="60%" align="center" valign="middle" class="Estilo1"><p>San Mart&iacute;n Sur 600 &ndash; <NAME> &ndash; Mendoza<br>0810 666 1033</p></td> </tr> <tr> <td height="1" colspan="2" bgcolor="#575757"></td> </tr> <tr> <td height="20" colspan="2" class="Estilo2"><p>Estimado <?php echo $_GET['apellidoynombre'];?></p></td> </tr> <tr> <td height="20" colspan="2" class="Estilo1"> <p><span class="Estilo2">Felicitaciones por su compra!</span> Le damos la bienvenida a Yacopini Sud y esperamos que este sea el inicio de una relación para toda la vida. </p> <p>Nuestro objetivo es brindarle la mejor calidad, atención y servicio durante la compra y entrega de su 0KM. Por eso, queremos adelantarle los pasos para la entrega de su nuevo <span class="Estilo2"><?php echo $_GET['modelo'];?></span>.</p> <p>Para facilitar y coordinar su entrega ha sido asignado el Consultor de Administración <strong><NAME></strong> (Teléfono: 4222848 int:1351 / e-mail <a href="mailto:<EMAIL>"><EMAIL></a>), quien estará a cargo de todo el proceso administrativo. En caso de ser necesario el supervisor del área es <strong><NAME></strong> (mail <a href="mailto:<EMAIL>"><strong><EMAIL></strong></a>). Los horarios de atención son de lunes a viernes de 9:00 a 13:00 y de 17:00 a 21:00 y los sábados de 09:00 a 13:00.</p> <p><strong>Informaci&oacute;n &uacute;til</strong>:</p> <p>1. Documentaci&oacute;n: </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull; Personas f&iacute;sicas:: DNI original y un servicio, resumen o impuesto reciente a nombre del titular con el domicilio actual. </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull; Sociedades: Estatuto Comercial y poder de los firmantes certificados. Por cada firmantes la documentaci&oacute;n requerida a personas f&iacute;sicas</p> <p>2. Cuentas Bancarias: Las cuentas habilitadas para dep&oacute;sito en efectivo o transferencia bancarias son: </p> <p>&nbsp;</p></td> </tr> <tr> <td height="20" colspan="2" class="Estilo1"><table width="544" border="1" cellpadding="4" cellspacing="0" class="Estilo1" bordercolor="#CCC"> <tr> <td width="177" nowrap><p><strong><u>BANCO FRANCES</u></strong></p></td> <td width="180" nowrap><p><strong><u>BANCO SANTANDER RIO</u></strong></p></td> <td width="187" nowrap><p><strong><u>BANCO CREDICOOP</u></strong></p></td> </tr> <tr> <td width="177" nowrap><p><strong>TITULAR: YACOPINI SUD S.A.</strong></p></td> <td width="180" nowrap><p><strong>TITULAR: YACOPINI SUD S.A.</strong></p></td> <td width="187" nowrap><p><strong>TITULAR: YACOPINI SUD S.A.</strong></p></td> </tr> <tr> <td width="177" nowrap><p><strong>C.U.I.T.: </strong>30-70915918-2<strong></strong></p></td> <td width="180" nowrap><p><strong>C.U.I.T.: </strong>30-70915918-2<strong></strong></p></td> <td width="187" nowrap><p>CUIT: 30-70915918-2</p></td> </tr> <tr> <td width="177" nowrap><p>CTA CTE PESOS N&ordm;:<strong> </strong>285-2145/1 </p></td> <td width="180" nowrap><p>CTA CTE PESOS N&ordm;:360/000476/7</p></td> <td width="187" nowrap><p>CTA CTE PESOS N&ordm;: 191-116-438209</p></td> </tr> <tr> <td width="177" nowrap><p>C.B.U.: 0170285120000000214513</p></td> <td width="180" nowrap><p><strong>C.B.U.: </strong>072036002 0000000047672<strong></strong></p></td> <td width="187" nowrap><p>CBU: 1910116555011604382096</p></td> </tr> </table> <p>Debe presentar en Tesorer&iacute;a las boletas originales de dep&oacute;sito o transferencias bancarias realizadas, con suficiente anticipaci&oacute;n o 24hs h&aacute;biles previas a la entrega de la unidad.</p> <p>&nbsp;</p></td> </tr> <tr> <td height="20" colspan="2" class="Estilo1"><p>3. Documentaci&oacute;n Usado: T&iacute;tulo, tarjetas verdes y azules, libre deuda de patentes y multas, verificaci&oacute;n t&eacute;cnica, informe con bloqueo de dominio libre de grav&aacute;menes, formulario 08 firmado, documentaci&oacute;n GNC (en caso de corresponder). La documentaci&oacute;n debe ser entregada a su consultor 48 hs antes del d&iacute;a de la entrega. </p> <p>4. Operaciones superiores a $ 600.000 anuales: debe presentar Certificaci&oacute;n de ingresos emitida por Contador y certificadas por Consejo Profesional.</p> <p>5. Seguro del automotor: para retirar su 0km debe tener seguro. Ud. puede solicitar el no rodamiento para tramitarlo a su consultor de Administraci&oacute;n. Si la operaci&oacute;n es con cr&eacute;dito, la cobertura tiene vigencia desde el momento de liquidaci&oacute;n del mismo y puede pedir su certificado de cobertura a su consultor.</p> <p>6. Accesorios: Ud. puede coordinar con su consultor la colocaci&oacute;n de accesorios en su veh&iacute;culo antes de la entrega del mismo.</p> <p>7 . Prueba de manejo: Ud. puede realizar una prueba de manejo de su veh&iacute;culo.</p> <p>La entrega de su 0km es muy importante para Yacopini Sud y estimamos que demandar&aacute; una hora de tiempo realizar todo el proceso, el cual incluye:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull; Facturaci&oacute;n y firma de documentaci&oacute;n.</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull; Explicaciones de los detalles del veh&iacute;culo y entrega de Check List de la revisi&oacute;n t&eacute;cnica.</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull; Explicaci&oacute;n de la garant&iacute;a y per&iacute;odos de mantenimiento.</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&bull; Presentaci&oacute;n de contactos de postventa y explicaci&oacute;n de los servicios de asistencia de Volkswagen.</p> <p><strong><em>Le recordamos que su opini&oacute;n como cliente es muy importante para mejorar nuestro nivel de atenci&oacute;n y servicio. Luego de la entrega de su 0km nos pondremos en contacto con usted para saber si se encuentra SUMAMENTE SATISFECHO.</em></strong></p> <p class="Estilo2">LE DAMOS LA BIENVENIDA COMO CLIENTE DE YACOPINI SUD. FELICITACIONES!!!</p></td> </tr> </table> <blockquote class="Estilo1">&nbsp;</blockquote> </body> </html> <file_sep>/stock_nofacturado_solicitud.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $colname_solicitudreserva = "-1"; if (isset($_GET['idSolicitud'])) { $colname_solicitudreserva = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_solicitudreserva = sprintf("SELECT slc_cliente.tipopersona, slc_cliente.condicioniva, slc_cliente.condicioningresosbrutos, slc_cliente.contacto, slc_cliente.apellidoynombre, slc_cliente.telefono, slc_cliente.celular, slc_cliente.email, slc_cliente.dni, slc_cliente.nacionalidad, slc_cliente.domicilio, slc_cliente.fechanacimiento, slc_cliente.estadocivil, slc_cliente.coyugeapellidoynombre, slc_cliente.ocupacion, slc_cliente.politicamenteexpuesta, slc_cliente.lugardenacimiento, slc_cliente.sexo, slc_cliente.reventa, slc_solicitudreserva.idPresupuesto, slc_solicitudreserva.fechaHora, slc_solicitudreserva.idSolicitud, slc_solicitudreserva.idCliente, slc_solicitudreserva.idMarca, slc_solicitudreserva.modelo, slc_solicitudreserva.descuento, slc_solicitudreserva.descuentoespecial, slc_solicitudreserva.preciolista, slc_solicitudreserva.cambiomodelo, slc_solicitudreserva.gastosretiro, slc_solicitudreserva.autoahorro, slc_solicitudreserva.precio, slc_solicitudreserva.gastospatentamiento, slc_solicitudreserva.gastosentrega, slc_solicitudreserva.intereses, slc_solicitudreserva.otros, slc_solicitudreserva.accesorios, slc_solicitudreserva.iva, slc_solicitudreserva.percepcioningresosbrutos, slc_solicitudreserva.fechaHora, slc_solicitudreserva.numero, slc_solicitudreserva.anio, slc_solicitudreserva.color1, slc_solicitudreserva.color2, slc_solicitudreserva.color3, slc_solicitudreserva.VIN, slc_solicitudreserva.disponibilidadchasis, slc_solicitudreserva.observaciones, slc_solicitudreserva.fechaestimadaentrega, slc_cliente_usuario.usuario, slc_solicitudreserva.impresionidUsuario, slc_solicitudreserva.impresionautorizacion, slc_solicitudreserva.reserva, slc_sucursal_venta.codigo, slc_sucursal_venta.sucursal FROM slc_solicitudreserva LEFT JOIN slc_cliente ON slc_solicitudreserva.idCliente = slc_cliente.idCliente LEFT JOIN slc_cliente_usuario ON slc_solicitudreserva.idUsuario = slc_cliente_usuario.idUsuario LEFT JOIN slc_sucursal_venta ON slc_sucursal_venta.id = slc_solicitudreserva.idsucursalventa WHERE idSolicitud = %s", GetSQLValueString($colname_solicitudreserva, "int")); $solicitudreserva = mysql_query($query_solicitudreserva, $config) or die(mysql_error()); $row_solicitudreserva = mysql_fetch_assoc($solicitudreserva); $totalRows_solicitudreserva = mysql_num_rows($solicitudreserva); $colname_otroscompradores = "-1"; if (isset($_GET['idSolicitud'])) { $colname_otroscompradores = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_otroscompradores = sprintf("SELECT slc_cliente.idCliente, slc_cliente.tipopersona, slc_cliente.apellidoynombre, slc_cliente.nombre, slc_cliente.apellido, slc_cliente.telefono, slc_cliente.celular, slc_cliente.email, slc_cliente.dni, slc_cliente.condicioniva, slc_cliente.contacto, slc_cliente.nacionalidad, slc_cliente.domicilio, slc_cliente.fechanacimiento, slc_cliente.estadocivil, slc_cliente.coyugeapellidoynombre FROM slc_solicitudcomprador LEFT JOIN slc_cliente ON slc_cliente.idCliente = slc_solicitudcomprador.idCliente WHERE idSolicitud = %s", GetSQLValueString($colname_otroscompradores, "int")); $otroscompradores = mysql_query($query_otroscompradores, $config) or die(mysql_error()); $row_otroscompradores = mysql_fetch_assoc($otroscompradores); $totalRows_otroscompradores = mysql_num_rows($otroscompradores); $colname_accesorios = "-1"; if (isset($_GET['idSolicitud'])) { $colname_accesorios = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_accesorios = sprintf("SELECT * FROM slc_solicitudaccesorio WHERE idSolicitud = %s", GetSQLValueString($colname_accesorios, "int")); $accesorios = mysql_query($query_accesorios, $config) or die(mysql_error()); $row_accesorios = mysql_fetch_assoc($accesorios); $totalRows_accesorios = mysql_num_rows($accesorios); $colname_formaspago = "-1"; if (isset($_GET['idSolicitud'])) { $colname_formaspago = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_formaspago = sprintf("SELECT * FROM slc_solicitudformapago WHERE idSolicitud = %s", GetSQLValueString($colname_formaspago, "int")); $formaspago = mysql_query($query_formaspago, $config) or die(mysql_error()); $row_formaspago = mysql_fetch_assoc($formaspago); $totalRows_formaspago = mysql_num_rows($formaspago); $colname_vendedor = $row_solicitudreserva['usuario']; mysql_select_db($database_config, $config); $query_vendedor = sprintf("SELECT idUsuario, idconsultor FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_vendedor, "text")); $vendedor = mysql_query($query_vendedor, $config) or die(mysql_error()); $row_vendedor = mysql_fetch_assoc($vendedor); $totalRows_vendedor = mysql_num_rows($vendedor); $colname_consultor = $row_vendedor['idconsultor']; mysql_select_db($database_config, $config); $query_consultor = sprintf("SELECT consultor FROM slc_consultor WHERE idConsultor = %s", GetSQLValueString($colname_consultor, "int")); $consultor = mysql_query($query_consultor, $config) or die(mysql_error()); $row_consultor = mysql_fetch_assoc($consultor); $totalRows_consultor = mysql_num_rows($consultor); mysql_select_db($database_config, $config); $query_banco = "SELECT * FROM slc_banco ORDER BY banco ASC"; $banco = mysql_query($query_banco, $config) or die(mysql_error()); $row_banco = mysql_fetch_assoc($banco); $totalRows_banco = mysql_num_rows($banco); mysql_select_db($database_config, $config); $query_sucursalbna = "SELECT * FROM slc_sucursalbna ORDER BY sucursal ASC"; $sucursalbna = mysql_query($query_sucursalbna, $config) or die(mysql_error()); $row_sucursalbna = mysql_fetch_assoc($sucursalbna); $totalRows_sucursalbna = mysql_num_rows($sucursalbna); mysql_select_db($database_config, $config); $query_cantcuotas = "SELECT * FROM slc_cantidadcuotas ORDER BY cantidadcuotas ASC"; $cantcuotas = mysql_query($query_cantcuotas, $config) or die(mysql_error()); $row_cantcuotas = mysql_fetch_assoc($cantcuotas); $totalRows_cantcuotas = mysql_num_rows($cantcuotas); $colname_stock = "-1"; if (isset($_GET['idstock'])) { $colname_stock = $_GET['idstock']; } mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idCliente, fechasolicitud, chasis, comision2 FROM slc_stocksud_stocknofacturado LEFT JOIN slc_deposito ON slc_deposito.id = slc_stocksud_stocknofacturado.iddeposito WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); $colname_entrega = "-1"; if (isset($_GET['idSolicitud'])) { $colname_entrega = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_entrega = sprintf("SELECT idEntrega, VIN FROM slc_entrega WHERE idSolicitud = %s AND baja = 1", GetSQLValueString($colname_entrega, "int")); $entrega = mysql_query($query_entrega, $config) or die(mysql_error()); $row_entrega = mysql_fetch_assoc($entrega); $totalRows_entrega = mysql_num_rows($entrega); if($totalRows_entrega > 0){ //Entrega con la misma solicitud if($row_stock['chasis'] != "") { $vin = $row_stock['chasis']; } else { $vin = $row_stock['comision2']; } if($row_entrega['VIN'] == $vin) { //Entrega con mismo VIN (y con la misma solicitud) $guardar = 1; $idEntrega = $row_entrega['idEntrega']; $idEntrega_vin = 0; } else { //Entrega con distinto VIN (y con la misma solicitud) $colname_entrega_vin = $vin; $colname2_entrega_vin = "-1"; if (isset($_GET['idSolicitud'])) { $colname2_entrega_vin = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_entrega_vin = sprintf("SELECT idEntrega, idSolicitud, VIN FROM slc_entrega WHERE VIN LIKE %s AND baja = 1 AND idSolicitud <> %s", GetSQLValueString($colname_entrega_vin, "text"), GetSQLValueString($colname2_entrega_vin, "int")); $entrega_vin = mysql_query($query_entrega_vin, $config) or die(mysql_error()); $row_entrega_vin = mysql_fetch_assoc($entrega_vin); $totalRows_entrega_vin = mysql_num_rows($entrega_vin); if($totalRows_entrega_vin > 0) { //Entrega con el mismo VIN (y con distinta solicitud) $guardar = 1; $idEntrega = $row_entrega['idEntrega']; $idEntrega_vin = $row_entrega_vin['idEntrega']; $error = 1; } else { $guardar = 1; $idEntrega = $row_entrega['idEntrega']; $idEntrega_vin = 0; } } } else { //Entrega con distinta solicitud if($row_stock['chasis'] != "") { $vin = $row_stock['chasis']; } else { $vin = $row_stock['comision2']; } $colname_entrega_vin = $vin; $colname2_entrega_vin = "-1"; if (isset($_GET['idSolicitud'])) { $colname2_entrega_vin = $_GET['idSolicitud']; } mysql_select_db($database_config, $config); $query_entrega_vin = sprintf("SELECT idEntrega, idSolicitud, VIN FROM slc_entrega WHERE VIN LIKE %s AND baja = 1 AND idSolicitud <> %s", GetSQLValueString($colname_entrega_vin, "text"), GetSQLValueString($colname2_entrega_vin, "int")); $entrega_vin = mysql_query($query_entrega_vin, $config) or die(mysql_error()); $row_entrega_vin = mysql_fetch_assoc($entrega_vin); $totalRows_entrega_vin = mysql_num_rows($entrega_vin); if($totalRows_entrega_vin > 0) { //Entrega con el mismo VIN (y con distinta solicitud) $guardar = 0; $error = 1; } else { //No ecuentra entrega $guardar = 1; $idEntrega = 0; $idEntrega_vin = 0; } } $colname_vendedor_entrega = $row_solicitudreserva['usuario']; mysql_select_db($database_config, $config); $query_vendedor_entrega = sprintf("SELECT idUsuario, usuario FROM slc_usuario WHERE usuario LIKE %s", GetSQLValueString($colname_vendedor_entrega, "text")); $vendedor_entrega = mysql_query($query_vendedor_entrega, $config) or die(mysql_error()); $row_vendedor_entrega = mysql_fetch_assoc($vendedor_entrega); $totalRows_vendedor_entrega = mysql_num_rows($vendedor_entrega); if($totalRows_vendedor_entrega == 0) { $error2 = 1; $guardar = 0; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>TERRITORIO YACOPINI</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> function guardar(){ f=document.formGuardar; if(f.fechasolicitud.value == ''){ alert('Debe seleccionar una fecha de solicitud.'); f.fechasolicitud.focus; return (0); } if(f.fechaestimadaentrega.value == ''){ alert('Debe seleccionar una fecha estimada de entrega.'); f.fechaestimadaentrega.focus; return (0); } else { var fechaestimadaentrega = f.fechaestimadaentrega.value; var fechaentrega = fechaestimadaentrega.split("-"); var fecha = new Date(fechaentrega[2]+"-"+fechaentrega[1]+"-"+fechaentrega[0]) var hoy = new Date(); hoy.setDate(hoy.getDate()+1); if (fecha <= hoy) { alert('La fecha estimada de entrega debe ser mayor dos días mayor a la fecha actual.'); f.fechaestimadaentrega.focus; return (0); } } if((f.idconsultor.value == '') | (f.idconsultor.value == '0')){ alert('Se requiere asignar un consultor, consultar con Sistemas.'); f.idconsultor.focus; return (0); } f.btnguardar.disabled = true; f.target = '_parent'; f.method = 'POST'; f.action = 'stock_nofacturado_solicitud_guardar.php'; f.submit(); } </script> <!-- Calendario Pou up --> <link rel=stylesheet href="xc2/css/xc2_default.css" type="text/css"> <style type="text/css"> .weekend { font-family:verdana; font-size:11px; line-height:14px; width:23px; text-align:center; color:#cc0000; background-color:#f0f0f0; border:1px solid #f0f0f0; padding:1px; cursor:pointer; } #rojo { color: #F00; } </style> <script language="javascript" src="xc2/config/xc2_default.js"></script> <script language="javascript"> xcDateFormat="dd-mm-yyyy"; xcArrowPosition=1; xcFootTagSwitch=[1, 0, 0, 1, 0, 0, 0, 0]; //xcMods[1].order=1; xcMods[2].order=1; </script> <script language="javascript" src="xc2/script/xc2_inpage.js"></script> <script language="javascript"> //setRange("1", daysAfter(0),daysAfter(45)); setLoopWeek("1", "weekend", "", 1, 1, "Sat", "Sun"); </script> <!-- /Calendario Pou up --> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar" action=""> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="6" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>STOCK Solicitud de Reserva <input name="idUsuario" type="hidden" id="idUsuario" value="<?php echo $row_usuario_sesion['idUsuario']; ?>"> <input name="fechahora" type="hidden" id="fechahora" value="<?php echo date('Y-m-d H:i:s') ; ?>"> <input name="idreserva" type="hidden" id="idreserva" value="<?php if(isset($_GET['idreserva'])) { echo $_GET['idreserva']; } else if(isset($_POST['idreserva'])) { echo $_POST['idreserva']; } else { echo "0";} ?>"> <span class="Estilo2"> <input name="chasis" type="hidden" id="chasis" value="<?php echo $row_stock['chasis']; ?>"> <input name="comision2" type="hidden" id="comision2" value="<?php echo $row_stock['comision2']; ?>"> <input name="idEntrega" type="hidden" id="idEntrega" value="<?php echo $idEntrega; ?>"> <input name="idEntrega_vin" type="hidden" id="idEntrega_vin" value="<?php echo $idEntrega_vin; ?>"> </span></strong></td> </tr> </table></td> </tr> <?php if($error == 1) { ?> <tr valign="middle"> <td height="20" colspan="6" class="Estilo2" style="color:#F4080C">Existe una entrega dada de baja no definitiva con este VIN relacionada a otra reserva, debe dar de baja definitiva a la entrega o relacionar la reserva de la entrega a otro VIN, para poder realizar esta asignaci&oacute;n.</td> </tr> <?php } ?> <?php if(($row_stock['codigo'] != '') && ($row_solicitudreserva['codigo']!= '') && ($row_stock['codigo'] != $row_solicitudreserva['codigo'])) { ?> <tr valign="middle"> <td height="20" colspan="6" class="Estilo2" style="color:#F4080C">El déposito y la sucursal de venta son diferentes. El depósito es: <?php echo $row_stock['deposito'];?> y la sucursal es: <?php echo $row_solicitudreserva['sucursal'];?></td> </tr> <?php } ?> <?php if($error2 == 1) { ?> <tr valign="middle"> <td height="20" colspan="6" class="Estilo2" style="color:#F4080C">El vendedor <?php echo $row_vendedor['usuario'];?> no se encuentra agregado en el Sistema de Entregas, se debe agregar el vendedor en el Sistema de Entregas, para poder realizar esta asignaci&oacute;n.</td> </tr> <?php } ?> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Fecha de Solicitud</strong></td> <td class="Estilo1"><input name="fechasolicitud" type="text" class="Estilo1" id="fechasolicitud" onFocus="showCalendar('1',this,this,'','holder',0,10,1);" value="<?php echo fecha($row_stock['fechasolicitud']); ?>" size="10" maxlength="10" /> <img src="img/calendario.gif" alt="Calendario" width="14" height="16" onClick="showCalendar('1',document.formGuardar.fechasolicitud,document.formGuardar.fechasolicitud,'','holder',0,10,1)"></td> <td height="20" class="Estilo1"><strong>Vendedor</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['usuario']; ?> <input name="idvendedor" type="hidden" id="idvendedor" value="<?php echo $row_vendedor['idUsuario']; ?>"> <input name="vendedor" type="hidden" id="vendedor" value="<?php echo $row_solicitudreserva['usuario']; ?>"></td> <td class="Estilo1"><strong>Consultor Asignado</strong></td> <td class="Estilo1"><?php echo $row_consultor['consultor']; ?> <input name="idconsultor" type="hidden" id="idconsultor" value="<?php echo $row_vendedor['idconsultor']; ?>"></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"> <strong>Precio Venta</strong><br> <?php if($row_solicitudreserva['autoahorro'] == 1) { $precioventa = ($row_solicitudreserva['preciolista'] - $row_solicitudreserva['descuento'] + $row_solicitudreserva['gastosretiro'] + $row_solicitudreserva['cambiomodelo'] ); } else { $precioventa = $row_solicitudreserva['precio']; } echo $precioventa; ?> <input name="precioventa" type="hidden" id="precioventa" value="<?php echo $precioventa;?>"> <input name="autoahorro" type="hidden" id="autoahorro" value="<?php echo $row_solicitudreserva['autoahorro'];?>"></td> <td class="Estilo1"><strong> <strong>Intereses</strong></strong><br> <?php echo $row_solicitudreserva['intereses']; ?> <input name="intereses" type="hidden" id="intereses" value="<?php echo $row_solicitudreserva['intereses'];?>"></td> <td class="Estilo1"> <strong>Accesorios</strong><br> <?php echo ($row_solicitudreserva['accesorios'] + $row_solicitudreserva['otros']); ?> <input name="accesorios" type="hidden" id="accesorios" value="<?php echo ($row_solicitudreserva['accesorios'] + $row_solicitudreserva['otros']); ?>"></td> <td colspan="3" class="Estilo1"><strong>Total</strong><br> <?php echo number_format($precioventa + $row_solicitudreserva['intereses'] + $row_solicitudreserva['accesorios'] + $row_solicitudreserva['otros'],0,",","."); ?> <input name="total" type="hidden" id="total" value="<?php $precioventa + $row_solicitudreserva['intereses'] + $row_solicitudreserva['accesorios'] + $row_solicitudreserva['otros']?>"></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="6" class="Estilo1"><span class="Estilo2">DATOS CLIENTE</span></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Persona</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['tipopersona']; ?> <input name="idSolicitud" type="hidden" id="idSolicitud" value="<?php echo $row_solicitudreserva['idSolicitud']; ?>"> <input name="idstock" type="hidden" id="idstock" value="<?php echo $_GET['idstock']; ?>"></td> <td height="20" class="Estilo1"><strong>Condici&oacute;n frente al IVA</strong></td> <td height="20" colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['condicioniva']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong><label id="labelapellidoynombre">Apellido y Nombre</label></strong></td> <td height="20" class="Estilo1"><!--<a href="consultas_clientes_nuevo_cliente.php" rel="shadowbox;width=500;height=250"><img src="img/agregar.gif" width="15" height="15" border="0" alt="Nuevo"></a> --><?php echo $row_solicitudreserva['apellidoynombre']; ?></td> <td height="20" class="Estilo1"><strong><label id="labelcondicioningresosbrutos">Condici&oacute;n Ingesos Brutos</label></strong></td> <td height="20" colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['condicioningresosbrutos']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong><label id="labeldni">DNI</label></strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['dni']; ?> <input name="dni" type="hidden" id="dni" value="<?php echo $row_solicitudreserva['dni']; ?>"> <input name="idClienteanterior" type="hidden" id="idClienteanterior" value="<?php echo $row_stock['idCliente']; ?>"></td> <td class="Estilo1"><strong>Agencia</strong></td> <td colspan="3" class="Estilo1"><?php if($row_solicitudreserva['reventa'] == '1') { echo "si";} else {echo "no";}?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Tel&eacute;fono</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['telefono']; ?></td> <td class="Estilo1"><label id="labelcontacto"><strong>Persona de contacto</strong></label></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['contacto']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Celular</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['celular']; ?></td> <td class="Estilo1">&nbsp;</td> <td colspan="3" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Email</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['email']; ?></td> <td class="Estilo1"><strong>Fecha de Nacimiento</strong></td> <td colspan="3" class="Estilo1"><?php echo fecha($row_solicitudreserva['fechanacimiento']); ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Domicilio</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['domicilio']; ?></td> <td class="Estilo1"><strong>Nacionalidad</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['nacionalidad']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Estado Civil</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['estadocivil']; ?></td> <td class="Estilo1"><strong>Ocupaci&oacute;n</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['ocupacion'];?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Apellido y Nombre C&oacute;nyuge</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['coyugeapellidoynombre']; ?></td> <td class="Estilo1"><strong>Lugar de Nacimiento</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['lugardenacimiento'];?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>&iquest;Es una persona pol&iacute;tcamente expuesta?</strong></td> <td class="Estilo1"><?php if (!(strcmp($row_solicitudreserva['politicamenteexpuesta'],"1"))) {echo "si";} else { echo "no";}?></td> <td class="Estilo1"><strong>Sexo</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['sexo']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Otros Clientes</strong></td> <td height="20" colspan="5" class="Estilo1"> <table width="100%" border="0"> <tr> <td height="25" class="Estilo1"><strong>Persona</strong></td> <td class="Estilo1"><strong>Apellido y Nombre/Raz&oacute;n Social</strong></td> <td class="Estilo1"><strong>Nacionalidad</strong></td> <td class="Estilo1"><strong>Estado Civil</strong></td> <td class="Estilo1"><strong>Domicilio</strong></td> <td class="Estilo1"><strong>Tel&eacute;fono</strong></td> <td class="Estilo1"><strong>Email</strong></td> <td class="Estilo1"><strong>DNI/CUIT/ CUIL</strong></td> <td class="Estilo1"><strong>Fecha de Nacimiento</strong></td> <td class="Estilo1"><strong>Condici&oacute;n Frente al IVA</strong></td> <td class="Estilo1"><strong>Apellido y Nombre C&oacute;nyuge</strong></td> </tr> <?php do { ?> <tr> <td height="25" class="Estilo1"><?php echo $row_otroscompradores['tipopersona']; ?></td> <td height="25" class="Estilo1"><?php echo $row_otroscompradores['apellidoynombre']; ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['nacionalidad']; ?></td> <td width="9%" class="Estilo1"><?php echo $row_otroscompradores['estadocivil']; ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['domicilio']; ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['telefono']; ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['email']; ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['dni']; ?></td> <td class="Estilo1"><?php echo fecha($row_otroscompradores['fechanacimiento']); ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['condicioniva']; ?></td> <td class="Estilo1"><?php echo $row_otroscompradores['coyugeapellidoynombre']; ?></td> </tr> <?php } while ($row_otroscompradores = mysql_fetch_assoc($otroscompradores)); ?> </table> </td> </tr> <tr valign="middle"> <td height="20" colspan="2" bgcolor="#EFEFEF" class="Estilo1"><span class="Estilo2">DATOS DE LA SOLICITUD DE RESERVA</span></td> <td width="19%" bgcolor="#EFEFEF" class="Estilo1">&nbsp;</td> <td width="31" colspan="3" bgcolor="#EFEFEF" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td width="16%" height="20" class="Estilo1"><strong>Fecha</strong></td> <td width="34%" class="Estilo1"><?php echo fecha($row_solicitudreserva['fechaHora']); ?></td> <td class="Estilo1"><strong>Vendedor</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['usuario']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Marca</strong></td> <td class="Estilo1"><?php if($row_solicitudreserva['idMarca'] == '1') { echo "chevrolet"; } else { echo "volswagen";}?></td> <td class="Estilo1"><strong>Modelo</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['modelo']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Color 1</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['color1']; ?></td> <td class="Estilo1"><strong>A&ntilde;o</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['anio']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Color 3</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['color3']; ?></td> <td class="Estilo1"><strong>Color 2</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['color3']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Precio</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['precio']; ?></td> <td class="Estilo1"><strong>Precio de lista</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['preciolista']; ?></td> </tr> <?php if(isset($_POST['descuento'])) { $descuento = $preciolista + $_POST['gastosentrega'] + $_POST['gastospatentamiento'] - $_POST['precio']; } ?> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Descuento</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['descuento']; ?></td> <td class="Estilo1"><strong>Gastos de patentamiento</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['gastospatentamiento']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Intereses/Gastos prendarios</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['intereses']; ?></td> <td class="Estilo1"><strong>Gastos de entrega</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['gastosentrega']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Otros</strong></td> <td class="Estilo1"><?php echo $row_solicitudreserva['otros']; ?></td> <td class="Estilo1"><strong>IVA</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_solicitudreserva['iva']; ?></td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Fecha Estimada de Entrega</strong></td> <td class="Estilo1"><input name="fechaestimadaentrega" type="text" class="Estilo1" id="fechaestimadaentrega" onFocus="showCalendar('1',this,this,'','holder',0,10,1);" value="<?php echo fecha($row_solicitudreserva['fechaestimadaentrega']); ?>" size="10" maxlength="10" /> <img src="img/calendario.gif" alt="Calendario" width="14" height="16" onClick="showCalendar('1',document.formGuardar.fechaestimadaentrega,document.formGuardar.fechaestimadaentrega,'','holder',0,10,1)"></td> <td class="Estilo1"><strong><?php if ($row_solicitudreserva['descuentoespecial']!='0') {echo "Descuento especial";}?></strong></td> <td colspan="3" class="Estilo1"> <?php if ($row_solicitudreserva['descuentoespecial']!='0') { echo $row_solicitudreserva['descuentoespecial']; } ?> </td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Accesorios </strong></td> <td colspan="5" class="Estilo1"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="30%" height="25" class="Estilo1"><strong>Tipo de Accesorio </strong></td> <td class="Estilo1"><strong>Importe</strong></td> </tr> <tr> <td height="1" colspan="2" bgcolor="#CACACA"></td> </tr> <?php if ($totalRows_accesorios > 0) { // Show if recordset not empty ?> <?php $totalaccesorios = 0; ?> <?php do { ?> <?php $colname_tipoAccesorio = $row_accesorios['idAccesorioTipo']; mysql_select_db($database_config, $config); $query_tipoAccesorio = sprintf("SELECT * FROM slc_accesoriotipo WHERE idAccesorioTipo = %s", GetSQLValueString($colname_tipoAccesorio, "int")); $tipoAccesorio = mysql_query($query_tipoAccesorio, $config) or die(mysql_error()); $row_tipoAccesorio = mysql_fetch_assoc($tipoAccesorio); $totalRows_tipoAccesorio = mysql_num_rows($tipoAccesorio); ?> <tr class="Estilo1"> <td height="25"><?php echo $row_tipoAccesorio['accesorioTipo']; ?></td> <td><?php echo $row_accesorios['importe']; ?></td> </tr> <?php $totalaccesorios = $totalaccesorios + $row_accesorios['importe'];?> <?php } while ($row_accesorios = mysql_fetch_assoc($accesorios)); ?> <?php mysql_free_result($tipoAccesorio); ?> <?php mysql_free_result($accesorios); ?> <?php } // Show if recordset not empty ?> <tr> <td height="20" align="right" class="Estilo1"><strong>Total Accesorios</strong>&nbsp;&nbsp;&nbsp;</td> <td height="20" class="Estilo1"><?php echo $totalaccesorios;?></td> </tr> </table> </td> </tr> <?php $total = $row_solicitudreserva['preciolista']+$row_solicitudreserva['gastosentrega']+$row_solicitudreserva['gastospatentamiento']+$row_solicitudreserva['intereses']+$row_solicitudreserva['accesorios']+$row_solicitudreserva['otros']-$row_solicitudreserva['descuento']-$row_solicitudreserva['descuentoespecial']; if($row_solicitudreserva['reventa'] != '1') { if(($row_solicitudreserva['condicioniva'] == 'Responsable Inscripto') || ($row_solicitudreserva['condicioniva'] == 'Monotributista')) { if(($row_solicitudreserva['condicioningresosbrutos'] == 'Inscripto') || ($row_solicitudreserva['condicioningresosbrutos'] == 'Convenio Multilateral')) { $subtotal = $total; if($row_solicitudreserva['condicioningresosbrutos'] == 'Inscripto') { $porcentajeib = 0.02; } elseif ($row_solicitudreserva['condicioningresosbrutos'] == 'Convenio Multilateral') { $porcentajeib = 0.01; } if($row_solicitudreserva['iva'] == '21') { $percepcioningresosbrutos = round(($subtotal/1.21)*$porcentajeib,2); } elseif($row_solicitudreserva['iva'] == '10.5') { $percepcioningresosbrutos = round(((($row_solicitudreserva['preciolista']-$descuento)/1.105)+(($row_solicitudreserva['gastosentrega']+$row_solicitudreserva['gastospatentamiento']+$row_solicitudreserva['accesorios']+$row_solicitudreserva['intereses']+$row_solicitudreserva['otros'])/1.21))*$porcentajeib,2); } $total = $subtotal + $percepcioningresosbrutos; } else { $subtotal = 0; $percepcioningresosbrutos = 0; } } else { $subtotal = 0; $percepcioningresosbrutos = 0; } } else { $subtotal = 0; $percepcioningresosbrutos = 0; } ?> <tr valign="middle"> <td height="1" colspan="6" align="center" bgcolor="#CCC" class="Estilo1"></td> </tr> <?php if($row_solicitudreserva['reventa'] != '1') { if(($row_solicitudreserva['condicioniva'] == 'Responsable Inscripto') || ($row_solicitudreserva['condicioniva'] == 'Monotributista')) { if(($row_solicitudreserva['condicioningresosbrutos'] == 'Inscripto') || ($row_solicitudreserva['condicioningresosbrutos'] == 'Convenio Multilateral')) { ?> <tr valign="middle"> <td class="Estilo2"><strong>Total</strong></td> <td class="Estilo1"><input name="subtotal2" type="text" class="Estilo1" style="font-size:14px;font-weight:bold;border-color:#FFF; border:1px; text-align:right" id="subtotal2" value="<?php echo "$" . number_format($subtotal,2,',', '.');?>" size="15" maxlength="15" readonly/></td> <td class="Estilo1">&nbsp;</td> <td colspan="3" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td class="Estilo2"><strong>Percepci&oacute;n Ingresos Brutos</strong></td> <td class="Estilo1"><input name="percepcioningresosbrutos2" type="text" class="Estilo1" style="font-size:14px;font-weight:bold;border-color:#FFF; border:1px; text-align:right" id="percepcioningresosbrutos2" value="<?php echo "$" . number_format($percepcioningresosbrutos,2,',', '.');?>" size="15" maxlength="15" readonly/></td> <td class="Estilo1">&nbsp;</td> <td colspan="3" class="Estilo1">&nbsp;</td> </tr> <?php } } }?> <tr valign="middle"> <td class="Estilo2"><strong>Total General</strong></td> <td class="Estilo1"><input name="total2" type="text" class="Estilo1" style="font-size:14px;font-weight:bold;border-color:#FFF; border:1px; text-align:right;" id="total2" value="<?php echo "$" . number_format($total,2,',', '.');?>" size="15" maxlength="15" readonly/> <input name="total" type="hidden" id="total" value="<?php echo $total;?>"> <input name="percepcioningresosbrutos" type="hidden" id="percepcioningresosbrutos" value="<?php echo $percepcioningresosbrutos;?>"> <input name="subtotal" type="hidden" id="subtotal" value="<?php echo $subtotal;?>"></td> <td class="Estilo1">&nbsp;</td> <td colspan="3" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td height="20" colspan="2" bgcolor="#EFEFEF" class="Estilo1"><span class="Estilo2">FORMAS DE PAGO</span></td> <td bgcolor="#EFEFEF" class="Estilo1">&nbsp;</td> <td colspan="3" bgcolor="#EFEFEF" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td colspan="6" class="Estilo1"> <table width="99%" border="0"> <tr> <td><span class="Estilo1"><strong>Forma de Pago</strong></span></td> <td class="Estilo1"><strong>Solicitud</strong></td> <td class="Estilo1"><strong>Grupo</strong></td> <td class="Estilo1"><strong>Orden</strong></td> <td class="Estilo1"><strong>Descripci&oacute;n</strong></td> <td class="Estilo1"><strong>Usado a&ntilde;o</strong></td> <td class="Estilo1"><strong>Usado dominio</strong></td> <td class="Estilo1"><strong>Banco</strong></td> <td class="Estilo1"><strong>Cantidad Cuotas</strong></td> <td class="Estilo1"><strong>Importe Cuota</strong></td> <td class="Estilo1"><strong>Importe</strong></td> </tr> <?php $totalpagos = 0; $i = 0; ?> <?php do { ?> <?php if ($totalRows_formaspago > 0) { // Show if recordset not empty ?> <tr> <td valign="bottom" class="Estilo1"><input name="formapago[]" type="text" class="Estilo1" id="formapago[]" value="<?php echo $row_formaspago['formapago']; ?>" readonly> <input name="usadoidtasacion[]" type="hidden" id="usadoidtasacion[]" value="<?php echo $row_formaspago['usadoidtasacion'];?>"> <input name="idFormaPago[]" type="hidden" id="idFormaPago[]" value="<?php echo $row_formaspago['idFormaPago']; ?>"></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'plan de ahorro'){?> <input name="plandeahorrosolicitud[]" type="text" class="Estilo1" id="plandeahorrosolicitud[]" title="solicitud" value="<?php echo $row_formaspago['plandeahorrosolicitud']; ?>" size="10" maxlength="8" readonly> <?php } else { ?> <input name="plandeahorrosolicitud[]" type="hidden" id="plandeahorrosolicitud[]" value="<?php echo $row_formaspago['plandeahorrosolicitud']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'plan de ahorro'){?> <input name="plandeahorrogrupo[]" type="text" class="Estilo1" id="plandeahorrogrupo[]" title="grupo" value="<?php echo $row_formaspago['plandeahorrogrupo']; ?>" size="10" maxlength="6" readonly> <?php } else { ?> <input name="plandeahorrogrupo[]" type="hidden" id="plandeahorrogrupo[]" value="<?php echo $row_formaspago['plandeahorrogrupo']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'plan de ahorro'){?> <input name="plandeahorroorden[]" type="text" class="Estilo1" id="plandeahorroorden[]" title="orden" value="<?php echo $row_formaspago['plandeahorroorden']; ?>" size="10" maxlength="3" readonly> <?php } else { ?> <input name="plandeahorroorden[]" type="hidden" id="plandeahorroorden[]" value="<?php echo $row_formaspago['plandeahorroorden']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'usado'){?> <input name="usadodescripcion[]" type="text" class="Estilo1" id="usadodescripcion[]" title="descripci&oacute;n" value="<?php echo $row_formaspago['usadodescripcion']; ?>" size="30" maxlength="30" readonly> <input name="usadomodelo" type="hidden" id="usadomodelo" value="<?php echo $row_formaspago['usadodescripcion']; ?>"> <?php } else { ?> <input name="usadodescripcion[]" type="hidden" id="usadodescripcion[]" value="<?php echo $row_formaspago['usadodescripcion']; ?>"> <?php } ?> <?php if($row_formaspago['formapago'] == 'canje'){?> <input name="canjedescripcion[]" type="text" class="Estilo1" id="canjedescripcion[]" title="descripci&oacute;n" value="<?php echo $row_formaspago['canjedescripcion']; ?>" size="30" maxlength="30" readonly> <?php } else { ?> <input name="canjedescripcion[]" type="hidden" id="canjedescripcion[]" value="<?php echo $row_formaspago['canjedescripcion']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'usado'){?> <input name="usadoanio[]" type="text" class="Estilo1" id="usadoanio[]" title="a&ntilde;o" value="<?php echo $row_formaspago['usadoanio']; ?>" size="4" maxlength="10" readonly> <?php } else { ?> <input name="usadoanio[]" type="hidden" id="usadoanio[]" value="<?php echo $row_formaspago['usadoanio']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'usado'){?> <input name="usadodominio[]" type="text" class="Estilo1" id="usadodominio[]" title="dominio" value="<?php echo $row_formaspago['usadodominio']; ?>" size="10" maxlength="10" readonly> <?php } else { ?> <input name="usadodominio[]" type="hidden" id="usadodominio[]" value="<?php echo $row_formaspago['usadodominio']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'credito'){?> <select name="creditoidbanco[]" class="Estilo1" id="creditoidbanco[]"> <option value=" " <?php if (!(strcmp(" ", $row_formaspago['creditoidbanco']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_banco['idBanco']?>"<?php if (!(strcmp($row_banco['idBanco'], $row_formaspago['creditoidbanco']))) {echo "selected=\"selected\"";} ?>><?php echo $row_banco['banco']?></option> <?php } while ($row_banco = mysql_fetch_assoc($banco)); $rows = mysql_num_rows($banco); if($rows > 0) { mysql_data_seek($banco, 0); $row_banco = mysql_fetch_assoc($banco); } ?> </select> <select name="idsucursalbna[]" class="Estilo1" id="idsucursalbna[]" <?php if($row_formaspago['creditoidbanco'] != '12'){ ?> style="display:none" <?php } ?>> <option value="0" <?php if (!(strcmp(0, $row_formaspago['creditoidbanco']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_sucursalbna['idsucursal']; ?>" <?php if (!(strcmp($row_sucursalbna['idsucursal'], $row_formaspago['idsucursalbna']))) {echo "selected=\"selected\"";} ?>><?php echo $row_sucursalbna['sucursal']?></option> <?php } while ($row_sucursalbna = mysql_fetch_assoc($sucursalbna)); $rows = mysql_num_rows($sucursalbna); if($rows > 0) { mysql_data_seek($sucursalbna, 0); $row_sucursalbna = mysql_fetch_assoc($sucursalbna); } ?> </select> <?php } else { ?> <input name="creditoidbanco[]" type="hidden" id="creditoidbanco[]" value="<?php echo $row_formaspago['creditoidbanco']; ?>"> <?php } ?> <?php if($row_formaspago['formapago'] == 'leasing'){?> <select name="leasingidbanco[]" class="Estilo1" id="leasingidbanco[]" disabled> <option value=" " <?php if (!(strcmp(" ", $row_formaspago['leasingidbanco']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_banco['idBanco']?>"<?php if (!(strcmp($row_banco['idBanco'], $row_formaspago['leasingidbanco']))) {echo "selected=\"selected\"";} ?>><?php echo $row_banco['banco']?></option> <?php } while ($row_banco = mysql_fetch_assoc($banco)); $rows = mysql_num_rows($banco); if($rows > 0) { mysql_data_seek($banco, 0); $row_banco = mysql_fetch_assoc($banco); } ?> </select> <?php } else { ?> <input name="leasingidbanco[]" type="hidden" id="leasingidbanco[]" value="<?php echo $row_formaspago['leasingidbanco']; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'credito'){?> <select name="creditoidcantidadcuotas[]" class="Estilo1" id="creditoidcantidadcuotas[]"> <option value=" " <?php if (!(strcmp(" ", $row_formaspago['creditoidcantidadcuotas']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_cantcuotas['idCantidadcuotas']?>"<?php if (!(strcmp($row_cantcuotas['idCantidadcuotas'], $row_formaspago['creditoidcantidadcuotas']))) {echo "selected=\"selected\"";} ?>><?php echo $row_cantcuotas['cantidadcuotas']?></option> <?php } while ($row_cantcuotas = mysql_fetch_assoc($cantcuotas)); $rows = mysql_num_rows($cantcuotas); if($rows > 0) { mysql_data_seek($cantcuotas, 0); $row_cantcuotas = mysql_fetch_assoc($cantcuotas); } ?> </select> <?php } else { ?> <input name="creditoidcantidadcuotas[]" type="hidden" id="creditoidcantidadcuotas[]" value="<?php echo $creditoidcantidadcuotas[$i]; ?>"> <?php } ?> <?php if($row_formaspago['formapago'] == 'financiacion propia'){?> <select name="finanpropiaidcantidadcuotas[]" class="Estilo1" id="finanpropiaidcantidadcuotas[]" disabled> <option value=" " <?php if (!(strcmp(" ", $row_formaspago['finanpropiaidcantidadcuotas']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_cantcuotas['idCantidadcuotas']?>"<?php if (!(strcmp($row_cantcuotas['idCantidadcuotas'], $row_formaspago['finanpropiaidcantidadcuotas']))) {echo "selected=\"selected\"";} ?>><?php echo $row_cantcuotas['cantidadcuotas']?></option> <?php } while ($row_cantcuotas = mysql_fetch_assoc($cantcuotas)); $rows = mysql_num_rows($cantcuotas); if($rows > 0) { mysql_data_seek($cantcuotas, 0); $row_cantcuotas = mysql_fetch_assoc($cantcuotas); } ?> </select> <?php } else { ?> <input name="finanpropiaidcantidadcuotas[]" type="hidden" id="finanpropiaidcantidadcuotas[]" value="<?php echo $finanpropiaidcantidadcuotas[$i]; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><?php if($row_formaspago['formapago'] == 'credito'){?> <input name="creditoimportecuota[]" type="text" class="Estilo1" id="creditoimportecuota[]" title="importe cuota" value="<?php echo $row_formaspago['creditoimportecuota']; ?>" size="10" maxlength="10" readonly> <?php } else { ?> <input name="creditoimportecuota[]" type="hidden" id="creditoimportecuota[]" value="<?php echo $creditoimportecuota[$i]; ?>"> <?php } ?> <?php if($row_formaspago['formapago'] == 'financiacion propia'){?> <input name="finanpropiaimportecuota[]" type="text" class="Estilo1" id="finanpropiaimportecuota[]" title="importe cuota" value="<?php echo $row_formaspago['finanpropiaimportecuota']; ?>" size="10" maxlength="10" readonly> <?php } else { ?> <input name="finanpropiaimportecuota[]" type="hidden" id="finanpropiaimportecuota[]" value="<?php echo $finanpropiaimportecuota[$i]; ?>"> <?php } ?></td> <td valign="bottom" class="Estilo1"><input name="importe[]" type="text" class="Estilo1" id="importe[]" title="importe" value="<?php echo $row_formaspago['importe']; ?>" size="15" maxlength="10" readonly></td> </tr> <?php $totalpagos = $totalpagos + $row_formaspago['importe']; $i++?> <?php } // Show if recordset not empty ?> <?php } while ($row_formaspago = mysql_fetch_assoc($formaspago)); ?> <tr> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td valign="bottom" class="Estilo1">&nbsp;</td> <td align="right" valign="bottom" class="Estilo1"><strong>Total Pagos&nbsp;$</strong></td> <td valign="bottom" class="Estilo1"><input name="totalpagos2" type="text" class="Estilo1" id="totalpagos2" value="<?php echo number_format($totalpagos,2,',', '.');?>" size="15" maxlength="15" readonly/> <input name="totalpagos" type="hidden" id="totalpagos" value="<?php echo $totalpagos;?>"></td> </tr> </table> </td> </tr> <tr valign="middle"> <td height="25" class="Estilo1"><strong>Observaciones</strong></td> <td colspan="5" class="Estilo1"><?php echo $row_solicitudreserva['observaciones'];?> </td> </tr> <tr valign="middle"> <td colspan="6" align="center" valign="middle" class="Estilo1"><?php if ($guardar == 1) {?> <input name="btnguardar" type="button" class="Estilo1" id="btnguardar" value="Guardar" onClick="guardar();"> <?php } ?> &nbsp; <input name="Cancelar" type="button" class="Estilo1" id="Cancelar" onClick="window.close()" value="Cancelar"></td> </tr> <tr valign="middle"> <td colspan="6" align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input type="hidden" name="MM_update" value="formGuardar"> </form> </div></td> </tr> </table> </body> </html> <?php mysql_free_result($otroscompradores); mysql_free_result($solicitudreserva); mysql_free_result($banco); mysql_free_result($cantcuotas); ?> <file_sep>/creditos_guardar25-04-2013.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php require("class.phpmailer.php"); function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } if ((isset($_POST["MM_update_rows"])) && ($_POST["MM_update_rows"] == "formGuardar")) { $id = $_POST['id']; $stockreserva = $_POST['stockreserva']; $importeaprobado = $_POST['importeaprobado']; $idestado1 = $_POST['idestado1']; $comentario1 = $_POST['comentario1']; $idestado2 = $_POST['idestado2']; $comentario2 = $_POST['comentario2']; $idestado3 = $_POST['idestado3']; $comentario3 = $_POST['comentario3']; $cliente = $_POST['cliente']; $vin = $_POST['vin']; $modelo = $_POST['modelo']; $vendedor = $_POST['vendedor']; $estadocivil = $_POST['estadocivil']; $registros = count($id); for($i=0; $i<$registros; $i++){ if($stockreserva[$i] == '1'){ $colname_stock = $id[$i]; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idestado1, idestado2, idestado3, importeaprobado, slc_stocksud_usuario.mail FROM slc_stocksud_stock LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_stock.idvendedor WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if((($idestado1[$i] != '') && ($row_stock['idestado1'] <> $idestado1[$i])) || (($idestado2[$i] != '') && ($row_stock['idestado2'] <> $idestado2[$i])) || (($idestado3[$i] != '') && ($row_stock['idestado3'] <> $idestado3[$i]))){ if(($idestado1[$i] != '') && ($row_stock['idestado1'] <> $idestado1[$i])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado1, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado1[$i], "int"), GetSQLValueString($id[$i], "int"), GetSQLValueString('1', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } if(($idestado2[$i] != '') && ($row_stock['idestado2'] <> $idestado2[$i])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado2, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado2[$i], "int"), GetSQLValueString($id[$i], "int"), GetSQLValueString('1', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } if(($idestado3[$i] != '') && ($row_stock['idestado3'] <> $idestado3[$i])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado3, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado3[$i], "int"), GetSQLValueString($id[$i], "int"), GetSQLValueString('1', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } $colname_estado = $row_stock['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1anterior = $row_estado['estado']; $colname_estado = $row_stock['idestado2']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2anterior = $row_estado['estado']; $colname_estado = $row_stock['idestado3']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3anterior = $row_estado['estado']; $colname_estado = $idestado1[$i]; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1nuevo = $row_estado['estado']; $colname_estado = $idestado2[$i]; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2nuevo = $row_estado['estado']; $colname_estado = $idestado3[$i]; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 12px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= 'Los datos para el cr&eacute;dito del cliente '; $cuerpo .= $cliente[$i]; $cuerpo .= ', para el vin '; $cuerpo .= $vin[$i]; $cuerpo .= ', modelo '; $cuerpo .= $modelo[$i]; $cuerpo .= ', y vendedor '; $cuerpo .= $vendedor[$i]; $cuerpo .= ' han sido actualizados. <br>'; $cuerpo .= '<br>Estado 1 anterior: '; $cuerpo .= $estado1anterior; $cuerpo .= '<br>Estado 1 nuevo: '; $cuerpo .= $estado1nuevo; $cuerpo .= '<br>Estado 2 anterior: '; $cuerpo .= $estado2anterior; $cuerpo .= '<br>Estado 2 nuevo: '; $cuerpo .= $estado2nuevo; $cuerpo .= '<br>Estado 3 anterior: '; $cuerpo .= $estado3anterior; $cuerpo .= '<br>Estado 3 nuevo: '; $cuerpo .= $estado3nuevo; $cuerpo .= '<br>Importe aprobado: '; $cuerpo .= $importeaprobado[$i]; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->Subject = 'CREDITO: ' . $cliente[$i]; $mail->Body = $cuerpo; $mail->Send(); } $updateSQL = sprintf("UPDATE slc_stocksud_stock SET importeaprobado=%s, idestado1=%s, comentario1=%s, idestado2=%s, comentario2=%s, idestado3=%s, comentario3=%s, estadocivil=%s WHERE idstock=%s", GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado1[$i], "int"), GetSQLValueString($comentario1[$i], "text"), GetSQLValueString($idestado2[$i], "int"), GetSQLValueString($comentario2[$i], "text"), GetSQLValueString($idestado3[$i], "int"), GetSQLValueString($comentario3[$i], "text"), GetSQLValueString($estadocivil[$i], "text"), GetSQLValueString($id[$i], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } elseif($stockreserva[$i] == '2') { $colname_stock = $id[$i]; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idestado1, idestado2, idestado3, importeaprobado, slc_stocksud_usuario.mail FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_reserva.idvendedor WHERE idreserva = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if((($idestado1[$i] != '') && ($row_stock['idestado1'] <> $idestado1[$i])) || (($idestado2[$i] != '') && ($row_stock['idestado2'] <> $idestado2[$i])) || (($idestado3[$i] != '') && ($row_stock['idestado3'] <> $idestado3[$i]))){ if(($idestado1[$i] != '') && ($row_stock['idestado1'] <> $idestado1[$i])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado1, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado1[$i], "int"), GetSQLValueString($id[$i], "int"), GetSQLValueString('2', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } if(($idestado2[$i] != '') && ($row_stock['idestado2'] <> $idestado2[$i])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado2, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado2[$i], "int"), GetSQLValueString($id[$i], "int"), GetSQLValueString('2', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } if(($idestado3[$i] != '') && ($row_stock['idestado3'] <> $idestado3[$i])){ $insertSQL = sprintf("INSERT INTO slc_stocksud_cambioestadocredito (idusuario, fechahora, importeaprobado, idestado3, id, stockreserva) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['idusuario'], "int"), GetSQLValueString(date("Y-m-d H:i"), "date"), GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado3[$i], "int"), GetSQLValueString($id[$i], "int"), GetSQLValueString('2', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } $colname_estado = $row_stock['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1anterior = $row_estado['estado']; $colname_estado = $row_stock['idestado2']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2anterior = $row_estado['estado']; $colname_estado = $row_stock['idestado3']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3anterior = $row_estado['estado']; $colname_estado = $idestado1[$i]; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado1nuevo = $row_estado['estado']; $colname_estado = $idestado2[$i]; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado2nuevo = $row_estado['estado']; $colname_estado = $idestado3[$i]; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT estado FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $estado3nuevo = $row_estado['estado']; $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 12px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= 'Los datos para el cr&eacute;dito del cliente '; $cuerpo .= $cliente[$i]; $cuerpo .= ', para el vin '; $cuerpo .= $vin[$i]; $cuerpo .= ', modelo '; $cuerpo .= $modelo[$i]; $cuerpo .= ', y vendedor '; $cuerpo .= $vendedor[$i]; $cuerpo .= ' han sido actualizados. <br>'; $cuerpo .= '<br>Estado 1 anterior: '; $cuerpo .= $estado1anterior; $cuerpo .= '<br>Estado 1 nuevo: '; $cuerpo .= $estado1nuevo; $cuerpo .= '<br>Estado 2 anterior: '; $cuerpo .= $estado2anterior; $cuerpo .= '<br>Estado 2 nuevo: '; $cuerpo .= $estado2nuevo; $cuerpo .= '<br>Estado 3 anterior: '; $cuerpo .= $estado3anterior; $cuerpo .= '<br>Estado 3 nuevo: '; $cuerpo .= $estado3nuevo; $cuerpo .= '<br>Importe aprobado: '; $cuerpo .= $importeaprobado[$i]; $cuerpo .= '</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->AddAddress('<EMAIL>'); $mail->Subject = 'CREDITO: ' . $cliente[$i]; $mail->Body = $cuerpo; $mail->Send(); } $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET importeaprobado=%s, idestado1=%s, comentario1=%s, idestado2=%s, comentario2=%s, idestado3=%s, comentario3=%s, estadocivil=%s WHERE idreserva=%s", GetSQLValueString($importeaprobado[$i], "double"), GetSQLValueString($idestado1[$i], "int"), GetSQLValueString($comentario1[$i], "text"), GetSQLValueString($idestado2[$i], "int"), GetSQLValueString($comentario2[$i], "text"), GetSQLValueString($idestado3[$i], "int"), GetSQLValueString($comentario3[$i], "text"), GetSQLValueString($estadocivil[$i], "text"), GetSQLValueString($id[$i], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } } header("location: creditos.php"); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> </body> <?php mysql_free_result($stock); ?> <file_sep>/reportes_comision2.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session session_start(); // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles session_unregister('MM_Username'); session_unregister('MM_UserGroup'); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php session_start(); $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $colname_registro = ""; if (isset($_POST['fechadesde'])) { $colname_registro = fecha($_POST['fechadesde']); } $colname2_registro = ""; if (isset($_POST['fechahasta'])) { $colname2_registro = fecha($_POST['fechahasta']); } $colname3_registro = ""; if (isset($_POST['entrega'])) { $colname3_registro = $_POST['entrega']; } $colname4_registro = ""; if (isset($_POST['comision_tiene'])) { $colname4_registro = $_POST['comision_tiene']; } $colname5_registro = ""; if (isset($_POST['comisiondesde'])) { $colname5_registro = fecha($_POST['comisiondesde']); } $colname6_registro = ""; if (isset($_POST['comisionhasta'])) { $colname6_registro = fecha($_POST['comisionhasta']); } $colname7_registro = "0"; if (isset($_POST['idvendedor'])) { $colname7_registro = $_POST['idvendedor']; } $colname8_registro = "0"; if (isset($_POST['idsucursalventa'])) { $colname8_registro = $_POST['idsucursalventa']; } $colname9_registro = "0"; if (isset($_POST['idConsultor'])) { $colname9_registro = $_POST['idConsultor']; } $colname10_registro = "0"; if (isset($_POST['idTipoEntrega'])) { $colname10_registro = $_POST['idTipoEntrega']; } $colname11_registro = ""; if (isset($_POST['nocomisionable'])) { $colname11_registro = $_POST['nocomisionable']; } mysql_select_db($database_config, $config); $query_registro = "SELECT slc_stocksud_stock.chasis, slc_stocksud_stock.modelo, slc_stocksud_stock.fechasolicitud, slc_stocksud_stock.comision, slc_stocksud_stock.nocomisionable, slc_stocksud_stock.precioventa, slc_stock_cliente.apellidoynombre AS cliente, slc_stock_cliente.reventa, slc_entrega.fechaHoraEntrega, slc_entrega.entrega, slc_stocksud_usuario.nombre AS vendedor, slc_sucursal_venta.sucursal, slc_consultor.consultor, slc_solicitudreserva.iva, slc_encuesta_realizada.idencuestarealizada FROM slc_stocksud_stock LEFT JOIN slc_entrega ON slc_entrega.VIN = slc_stocksud_stock.chasis LEFT JOIN slc_stock_cliente ON slc_stock_cliente.idCliente = slc_stocksud_stock.idCliente LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_stock.idvendedor LEFT JOIN slc_solicitudreserva ON slc_solicitudreserva.idSolicitud = slc_entrega.idSolicitud LEFT JOIN slc_sucursal_venta ON slc_sucursal_venta.id = slc_solicitudreserva.idsucursalventa LEFT JOIN slc_consultor ON slc_consultor.idConsultor = slc_entrega.idConsultor LEFT JOIN slc_encuesta_realizada ON slc_encuesta_realizada.identrega = slc_entrega.identrega LEFT JOIN slc_encuesta ON (slc_encuesta.idencuesta = slc_encuesta_realizada.idencuesta AND slc_encuesta.idtipo = 2) WHERE slc_stocksud_stock.chasis <> ''"; if(($colname_registro != "") && ($colname2_registro != "")) { $query_registro .= sprintf(" AND DATE(slc_entrega.fechaHoraEntrega) BETWEEN %s AND %s ", GetSQLValueString($colname_registro, "date"), GetSQLValueString($colname2_registro, "date")); } if($colname3_registro != "") { $query_registro .= sprintf(" AND slc_entrega.entrega = %s ", GetSQLValueString($colname3_registro, "int")); } if($colname4_registro == "1") { $query_registro .= " AND (slc_stocksud_stock.comision IS NOT NULL AND slc_stocksud_stock.comision <> '0000-00-00' OR YEAR(slc_stocksud_stock.comision) <> '0000')"; } if($colname4_registro == "0") { $query_registro .= " AND (slc_stocksud_stock.comision IS NULL OR slc_stocksud_stock.comision = '0000-00-00' OR YEAR(slc_stocksud_stock.comision) = '0000')"; } if(($colname5_registro != "") && ($colname6_registro != "")) { $query_registro .= sprintf(" AND slc_stocksud_stock.comision BETWEEN %s AND %s ", GetSQLValueString($colname5_registro, "date"), GetSQLValueString($colname6_registro, "date")); } if($colname7_registro != 0) { $query_registro .= sprintf(" AND slc_stocksud_stock.idvendedor = %s ", GetSQLValueString($colname7_registro, "int")); } if($colname8_registro != 0) { $query_registro .= sprintf(" AND slc_solicitudreserva.idsucursalventa = %s ", GetSQLValueString($colname8_registro, "int")); } if($colname9_registro != 0) { $query_registro .= sprintf(" AND slc_entrega.idConsultor = %s ", GetSQLValueString($colname9_registro, "int")); } if($colname10_registro != 0) { $query_registro .= sprintf(" AND slc_entrega.idTipoEntrega = %s ", GetSQLValueString($colname10_registro, "int")); } if($colname11_registro != "") { $query_registro .= sprintf(" AND slc_stocksud_stock.nocomisionable = %s ", GetSQLValueString($colname11_registro, "int")); } $query_registro .= " GROUP BY slc_stocksud_stock.chasis ORDER BY comision ASC "; $registro = mysql_query($query_registro, $config) or die(mysql_error()); $row_registro = mysql_fetch_assoc($registro); $totalRows_registro = mysql_num_rows($registro); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } .Estilo3 {color: #FF0000} .Estilo11 {font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function MM_openBrWindow(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><BR> <table width="99%" border="1" align="center" cellpadding="4" cellspacing="0" bordercolor="#CCCCCC" id="ppal"> <tr class="Estilo1"> <td height="20" colspan="15" align="center" class="Estilo2">REPORTE DE COMISION</td> </tr> <tr class="Estilo1"> <td height="20" class="Estilo2">VIN</td> <td><span class="Estilo2">MODELO</span></td> <td><span class="Estilo2">CLIENTE</span></td> <td><span class="Estilo2">VENDEDOR</span></td> <td><span class="Estilo2">AGENCIA</span></td> <td><span class="Estilo2">FECHA DE SOLICITUD</span></td> <td><span class="Estilo2">FECHA DE ENTREGA</span></td> <td><span class="Estilo2">ENTREGA</span></td> <td><span class="Estilo2">SUCURSAL</span></td> <td><span class="Estilo2">CONSULTOR</span></td> <td><span class="Estilo2">COMISION</span></td> <td><span class="Estilo2">NO COMISIONABLE</span></td> <td><span class="Estilo2">REALIZO LLAMADO DE CORTESIA</span></td> <td><span class="Estilo2">IVA</span></td> <td><span class="Estilo2">PRECIO VENTA</span></td> </tr> <?php do { ?> <tr class="Estilo1"> <td height="20"><?php echo $row_registro['chasis']; ?></td> <td><?php echo $row_registro['modelo']; ?></td> <td><?php echo $row_registro['cliente']; ?></td> <td><?php echo $row_registro['vendedor']; ?></td> <td><?php if( $row_registro['reventa'] == 1) {echo "si";} else {echo "no";} ?></td> <td><?php echo fecha($row_registro['fechasolicitud']); ?></td> <td><?php echo fecha($row_registro['fechaHoraEntrega']); ?></td> <td><?php if($row_registro['entrega'] == 1) {echo "si";} else {echo "no";} ?></td> <td><?php echo $row_registro['sucursal']; ?></td> <td><?php echo $row_registro['consultor']; ?></td> <td ><?php echo fecha($row_registro['comision']); ?></td> <td ><?php if($row_registro['nocomisionable'] == '1') {echo "No Comisionable";} else {echo "Comisionable";} ?></td> <td ><?php if($row_registro['idencuestarealizada'] > 0){echo "si";}; ?></td> <td ><?php echo $row_registro['iva']; ?></td> <td ><?php echo $row_registro['precioventa']; ?></td> <?php } while ($row_registro = mysql_fetch_assoc($registro)); ?> </table> <blockquote class="Estilo1"> <div align="right">Cantidad de Registros <?php echo $totalRows_registro ?></div> <div align="left"> <?php echo date('d-m-Y H:i');?> </div> <div align="right"><a href="#"><img src="img/imprimir.gif" alt="Imprimir" width="26" height="23" border="0" onClick="MM_callJS('window.print();')"></a>&nbsp;&nbsp;<form action="reporte_comision_generar_excel.php" method="post" name="formexcel" target="_blank" id="formexcel"><a href="#"> <img src="img/xls.png" alt="Exportar a Excel" width="26" height="26" border="0" onClick="document.formexcel.submit(); "></a> <input name="query_registro" type="hidden" id="query_registro" value="<?php echo $query_registro;?>"> </form></div> </blockquote> </body> </html> <?php mysql_free_result($registro); ?> <file_sep>/turnos_asignar_cliente.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $maxRows_creditos = 20; $pageNum_creditos = 0; if (isset($_GET['pageNum_creditos'])) { $pageNum_creditos = $_GET['pageNum_creditos']; } $startRow_creditos = $pageNum_creditos * $maxRows_creditos; $colname_creditos = ""; if (isset($_GET['cliente'])) { $colname_creditos = trim($_GET['cliente']); } mysql_select_db($database_config, $config); $query_creditos = sprintf("(SELECT slc_stocksud_reserva.idreserva AS id, slc_stocksud_reserva.cliente, slc_stocksud_modelo.modelo, slc_stocksud_usuario.usuario AS vendedor, slc_stocksud_reserva.VIN AS vin, slc_stocksud_banco.banco, 2 AS stockreserva, slc_stocksud_reserva.importeaprobado FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_modelo ON slc_stocksud_reserva.idmodelo = slc_stocksud_modelo.idmodelo LEFT JOIN slc_stocksud_usuario ON slc_stocksud_reserva.idvendedor = slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_color ON slc_stocksud_reserva.idcolor1 = slc_stocksud_color.idcolor LEFT JOIN slc_stocksud_banco ON slc_stocksud_reserva.idbanco = slc_stocksud_banco.idbanco WHERE slc_stocksud_reserva.idbanco <> 0 AND slc_stocksud_reserva.idestado1 = 1 AND slc_stocksud_reserva.fecha >= '2012-10-14' "); if($colname_creditos != ""){ $query_creditos .= sprintf(" AND slc_stocksud_reserva.cliente LIKE %s", GetSQLValueString("%" . $colname_creditos . "%", "text")); } if($row_usuario_sesion['idGrupo'] == '3'){ $query_creditos .= sprintf(" AND slc_stocksud_reserva.idvendedor = %s", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } $query_creditos .= sprintf(") UNION (SELECT slc_stocksud_stock.idstock AS id, slc_stock_cliente.apellidoynombre AS cliente, slc_stocksud_stock.modelo, slc_stocksud_usuario.usuario AS vendedor, slc_stocksud_stock.chasis AS vin, slc_stocksud_banco.banco, 1 AS stockreserva, slc_stocksud_stock.importeaprobado FROM slc_stocksud_stock LEFT JOIN slc_stock_cliente ON slc_stocksud_stock.idCliente = slc_stock_cliente.idCliente LEFT JOIN slc_stocksud_usuario ON slc_stocksud_stock.idvendedor = slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_banco ON slc_stocksud_stock.idbanco = slc_stocksud_banco.idbanco LEFT JOIN slc_entrega ON slc_entrega.VIN = slc_stocksud_stock.chasis WHERE slc_stocksud_stock.idbanco <> 0 AND (slc_entrega.entrega = 0 OR slc_entrega.entrega IS NULL) AND slc_stocksud_stock.idestado1 = 1 AND slc_stocksud_stock.fechasolicitud >= '2012-10-14' "); if($colname_creditos != ""){ $query_creditos .= sprintf(" AND slc_stock_cliente.apellidoynombre LIKE %s", GetSQLValueString("%" . $colname_creditos . "%", "text")); } if($row_usuario_sesion['idGrupo'] == '3'){ $query_creditos .= sprintf(" AND slc_stocksud_stock.idvendedor = %s", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } $query_creditos .= ") ORDER BY cliente ASC"; $creditos = mysql_query($query_creditos, $config) or die(mysql_error()); $row_creditos = mysql_fetch_assoc($creditos); if (isset($_GET['totalRows_creditos'])) { $totalRows_creditos = $_GET['totalRows_creditos']; } else { $all_creditos = mysql_query($query_creditos); $totalRows_creditos = mysql_num_rows($all_creditos); } $totalPages_creditos = ceil($totalRows_creditos/$maxRows_creditos)-1; $queryString_creditos = ""; if (!empty($_SERVER['QUERY_STRING'])) { $params = explode("&", $_SERVER['QUERY_STRING']); $newParams = array(); foreach ($params as $param) { if (stristr($param, "pageNum_creditos") == false && stristr($param, "totalRows_creditos") == false) { array_push($newParams, $param); } } if (count($newParams) != 0) { $queryString_creditos = "&" . htmlentities(implode("&", $newParams)); } } $queryString_creditos = sprintf("&totalRows_creditos=%d%s", $totalRows_creditos, $queryString_creditos); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo21 {color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD</span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>TURNOS</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td valign="top" bgcolor="#FFFFFF"><table width="95%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#EFEFEF"> <td width="16%" class="Estilo11"><span class="Estilo21">SELECCIONAR CLIENTE</span></td> <td width="34%" class="Estilo11">&nbsp;</td> <td width="19%" class="Estilo11">&nbsp;</td> <td width="31%" class="Estilo11">&nbsp;</td> </tr> <tr valign="middle"> <td colspan="4" class="Estilo11"><form action="turnos_asignar_cliente.php" method="get" id="formBuscar"> Cliente <input name="cliente" type="text" class="Estilo11" id="cliente" onFocus="this.value=''" value="<?php echo $_GET['cliente'];?>" size="20" maxlength="100"> <input name="Submit" type="submit" class="Estilo11" value="Buscar"> </form></td> </tr> <tr valign="middle"> <td colspan="4" class="Estilo11"><form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar"> <table width="100%" border="0" cellspacing="2" cellpadding="5"> <tr class="Estilo11" bgcolor="#EFEFEF"> <td height="25"><strong>Cliente</strong></td> <td><strong>Modelo</strong></td> <td bgcolor="#EFEFEF"><strong>VIN</strong></td> <td><strong>Vendedor</strong></td> <td><strong>Banco</strong></td> <td><strong>Importe Aprobado</strong></td> <td><strong>Stock / Reserva</strong></td> <td><strong>Asignar</strong></td> </tr> <?php if ($totalRows_creditos > 0) { // Show if recordset not empty ?> <?php do { ?> <?php $colname_turno = $row_creditos['id']; $colname2_turno = $row_creditos['stockreserva']; mysql_select_db($database_config, $config); $query_turno = sprintf("SELECT idturno, DATE(fechahora) AS fecha FROM slc_stocksud_turno WHERE id = %s AND stockreserva = %s", GetSQLValueString($colname_turno, "int"), GetSQLValueString($colname2_turno, "int")); $turno = mysql_query($query_turno, $config) or die(mysql_error()); $row_turno = mysql_fetch_assoc($turno); $totalRows_turno = mysql_num_rows($turno); ?> <?php if (($totalRows_turno == '0') || ($row_turno['fecha'] >= date('Y-m-d'))){?> <tr> <td height="20" class="Estilo11"><?php echo $row_creditos['cliente']; ?></td> <td class="Estilo11"><?php echo $row_creditos['modelo']; ?></td> <td class="Estilo11"><?php echo $row_creditos['vin']; ?></td> <td class="Estilo11"><?php echo $row_creditos['vendedor']; ?></td> <td class="Estilo11"><?php echo $row_creditos['banco']; ?></td> <td align="right" class="Estilo11"><?php echo $row_creditos['importeaprobado']; ?></td> <td class="Estilo11"><?php if($row_creditos['stockreserva']=='1') { echo "stock"; } elseif($row_creditos['stockreserva']=='2') {echo "reserva"; };?></td> <td class="Estilo11"><?php if($row_turno['idturno'] == ''){?> <a href="#"><img src="img/calendario.gif" alt="Asignar Turno" width="14" height="16" border="0" onClick="window.open('turnos_asignar.php?id=<?php echo $row_creditos['id'];?>&stockreserva=<?php echo $row_creditos['stockreserva'];?>','Turnos','scrollbars=yes,resizable=yes,width=800,height=350')"> <?php } elseif($row_turno['idturno'] != ''){?> <a href="turnos_asignar_cancelar.php?idturno=<?php echo $row_turno['idturno']; ?>"><img src="img/cancelar.png" alt="Cancelar turno" width="18" height="18" border="0"></a> <?php } ?></td> </tr> <tr> <td height="1" colspan="8" bgcolor="#EFEFEF"></td> </tr> <?php } ?> <?php } while ($row_creditos = mysql_fetch_assoc($creditos)); ?> <?php } // Show if recordset not empty ?> </table> </form></td> </tr> </table></td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <file_sep>/comisiones_puntaje_nuevo.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_config, $config); $query_consultores = "SELECT * FROM slc_consultor ORDER BY consultor ASC"; $consultores = mysql_query($query_consultores, $config) or die(mysql_error()); $row_consultores = mysql_fetch_assoc($consultores); $totalRows_consultores = mysql_num_rows($consultores); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; if(f.nombre.value == ''){ alert("Debe ingresar el nombre"); f.nombre.focus; return (0); } if(f.vigenciadesde.value == ''){ alert("Debe ingresar la vigencia"); f.vigenciadesde.focus; return (0); } f.target = '_parent'; f.method = 'POST'; f.action = 'comisiones_puntaje_guardar.php'; f.submit(); } function agregarrango() { f=document.formGuardar; if(f.descripcion_agregar.value == ''){ alert("Debe ingresar una descripción."); f.descripcion_agregar.focus; return (0); } if(f.puntajedesde_agregar.value == ''){ alert("Debe ingresar un puntaje desde."); f.puntajedesde_agregar.focus; return (0); } if(f.puntajehasta_agregar.value == ''){ alert("Debe ingresar un puntaje hasta."); f.puntajehasta_agregar.focus; return (0); } if(f.porcentaje_agregar.value == ''){ alert("Debe ingresar un porcentaje."); f.porcentaje_agregar.focus; return (0); } f.target = '_parent'; f.method = 'POST'; f.action = 'comisiones_puntaje_nuevo.php'; f.submit(); } //--> </script> <!-- Calendario Pou up --> <link rel=stylesheet href="xc2/css/xc2_default.css" type="text/css"> <style type="text/css"> .weekend { font-family:verdana; font-size:11px; line-height:14px; width:23px; text-align:center; color:#cc0000; background-color:#f0f0f0; border:1px solid #f0f0f0; padding:1px; cursor:pointer; } #rojo { color: #F00; } </style> <script language="javascript" src="xc2/config/xc2_default.js"></script> <script language="javascript"> xcDateFormat="dd-mm-yyyy"; xcArrowPosition=1; xcFootTagSwitch=[1, 0, 0, 1, 0, 0, 0, 0]; //xcMods[1].order=1; xcMods[2].order=1; </script> <script language="javascript" src="xc2/script/xc2_inpage.js"></script> <script language="javascript"> //setRange("1", daysAfter(0),daysAfter(45)); setLoopWeek("1", "weekend", "", 1, 1, "Sat", "Sun"); </script> <!-- /Calendario Pou up --> <!--ajax-autocomplete --> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="4" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>COMISIONES - PUNTAJE Nuevo</strong></td> </tr> </table></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="4" class="Estilo1"><span class="Estilo2">DATOS DE LA VARIABLE</span></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Nombre</strong></td> <td class="Estilo1"><input name="nombre" type="text" class="Estilo1" id="nombre" value="<?php echo $_POST['nombre'];?>" size="50" maxlength="100"></td> <td class="Estilo1"><strong>Vigencia desde</strong></td> <td class="Estilo1"><input name="vigenciadesde" type="text" class="Estilo1" id="vigenciadesde" onFocus="showCalendar('1',this,this,'','holder',0,10,1);" value="<?php echo $_POST['vigenciadesde'];?>" size="10" maxlength="10" /> <img src="img/calendario.gif" alt="Calendario" width="14" height="16" onClick="showCalendar('1',document.formGuardar.vigenciadesde,document.formGuardar.vigenciadesde,'','holder',0,10,1)"></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="4" class="Estilo1"><span class="Estilo2">RANGOS DE LA VARIABLE</span></td> </tr> <tr valign="middle"> <td colspan="4" class="Estilo1"><table width="100%" border="0" cellpadding="4"> <tbody> <tr> <td><strong><span class="Estilo1">Descripci&oacute;n</span></strong></td> <td class="Estilo1"><strong>Puntaje desde</strong></td> <td class="Estilo1"><strong>Puntaje hasta</strong></td> <td><strong><span class="Estilo1">Porcentaje</span></strong></td> <td>&nbsp;</td> </tr> <tr> <td><textarea name="descripcion_agregar" cols="40" rows="2" class="Estilo1" id="descripcion_agregar"></textarea></td> <td><input name="puntajedesde_agregar" type="text" class="Estilo1" id="puntajedesde_agregar" maxlength="11"></td> <td><input name="puntajehasta_agregar" type="text" class="Estilo1" id="puntajehasta_agregar" maxlength="11"></td> <td><input name="porcentaje_agregar" type="text" class="Estilo1" id="porcentaje_agregar" maxlength="11"></td> <td><input name="btnagregar" type="button" class="Estilo1" id="btnagregar" value="Agregar" onClick="agregarrango()"> <input name="rangoborrar" type="hidden" id="rangoborrar"></td> </tr> <?php if (isset($_POST['rango_descripcion']) && $_POST['rango_descripcion']!='') { $rango_descripcion = $_POST['rango_descripcion']; $rango_porcentaje = $_POST['rango_porcentaje']; $rango_puntajedesde = $_POST['rango_puntajedesde']; $rango_puntajehasta = $_POST['rango_puntajehasta']; } if (isset($_POST['descripcion_agregar']) && $_POST['descripcion_agregar']!='') { $rango_descripcion[] = $_POST['descripcion_agregar']; $rango_porcentaje[] = $_POST['porcentaje_agregar']; $rango_puntajedesde[] = $_POST['puntajedesde_agregar']; $rango_puntajehasta[] = $_POST['puntajehasta_agregar']; } for ($i=0;$i<count($rango_descripcion);$i++) { if(($_POST['rangoborrar'] == '') || ($_POST['rangoborrar'] != $i)) { ?> <tr> <td><textarea name="rango_descripcion[]" cols="40" rows="2" readonly class="Estilo1" id="rango_descripcion[]"><?php echo $rango_descripcion[$i];?></textarea></td> <td><input name="rango_puntajedesde[]" type="text" class="Estilo1" id="rango_puntajedesde[]" value="<?php echo $rango_puntajedesde[$i];?>" maxlength="11" readonly></td> <td><input name="rango_puntajehasta[]" type="text" class="Estilo1" id="rango_puntajehasta[]" value="<?php echo $rango_puntajehasta[$i];?>" maxlength="11" readonly></td> <td><input name="rango_porcentaje[]" type="text" class="Estilo1" id="rango_porcentaje[]" value="<?php echo $rango_porcentaje[$i];?>" maxlength="11" readonly></td> <td><input name="btnborrar" type="button" class="Estilo1" id="btnborrar" value="Borrar" onClick="document.formGuardar.rangoborrar.value='<?php echo $i;?>'; document.formGuardar.submit();"></td> </tr> <?php } ?> <?php } ?> </tbody> </table></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1"><input name="Guardar" type="button" class="Estilo1" id="Guardar" value="Guardar" onClick="guardar();"> &nbsp;&nbsp; <input name="Cancelar" type="button" class="Estilo1" id="Cancelar" onClick="window.close()" value="Cancelar"></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input type="hidden" name="MM_insert" value="formGuardar"> </form> </div></td> </tr> </table> </body> </html> <file_sep>/creditos_historial_cambioestado.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_historial = "-1"; if (isset($_GET['id'])) { $colname_historial = $_GET['id']; } $colname2_historial = "-1"; if (isset($_GET['stockreserva'])) { $colname2_historial = $_GET['stockreserva']; } mysql_select_db($database_config, $config); $query_historial = sprintf("SELECT * FROM slc_stocksud_cambioestadocredito WHERE id = %s AND stockreserva = %s ORDER BY fechahora DESC", GetSQLValueString($colname_historial, "int"),GetSQLValueString($colname2_historial, "int")); $historial = mysql_query($query_historial, $config) or die(mysql_error()); $row_historial = mysql_fetch_assoc($historial); $totalRows_historial = mysql_num_rows($historial); function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; if(f.usuario.value == ''){ alert("Debe ingresar el usuario"); f.nombre.focus; return (0); } if(f.clave.value == ''){ alert("Debe ingresar la clave"); f.nombre.focus; return (0); } f.target = '_parent'; f.method = 'POST'; f.action = 'usuarios_guardar.php'; f.submit(); } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <table width="95%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="6" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td height="20" class="Estilo1"><strong>CREDITOS Hitorial Cambio de Estado</strong></td> </tr> </table></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" class="Estilo1"><strong>FECHA HORA</strong></td> <td class="Estilo1"><strong>USUARIO</strong></td> <td class="Estilo1"><strong>IMPORTE APROBADO</strong></td> <td class="Estilo1"><strong>ESTADO 1</strong></td> <td class="Estilo1"><strong>ESTADO 2</strong></td> <td class="Estilo1"><strong>ESTADO 3</strong></td> </tr> <?php do { ?> <?php $colname_usuario = $row_historial['idusuario']; mysql_select_db($database_config, $config); $query_usuario = sprintf("SELECT * FROM slc_stocksud_usuario WHERE idUsuario = %s", GetSQLValueString($colname_usuario, "int")); $usuario = mysql_query($query_usuario, $config) or die(mysql_error()); $row_usuario = mysql_fetch_assoc($usuario); $totalRows_usuario = mysql_num_rows($usuario); $colname_estado = $row_historial['idestado1']; mysql_select_db($database_config, $config); $query_estado = sprintf("SELECT * FROM slc_stocksud_estadocredito WHERE idestado = %s", GetSQLValueString($colname_estado, "int")); $estado = mysql_query($query_estado, $config) or die(mysql_error()); $row_estado = mysql_fetch_assoc($estado); $totalRows_estado = mysql_num_rows($estado); $colname_estado2 = $row_historial['idestado2']; mysql_select_db($database_config, $config); $query_estado2 = sprintf("SELECT * FROM slc_stocksud_estadocredito2 WHERE idestado = %s", GetSQLValueString($colname_estado2, "int")); $estado2 = mysql_query($query_estado2, $config) or die(mysql_error()); $row_estado2 = mysql_fetch_assoc($estado2); $totalRows_estado2 = mysql_num_rows($estado2); $colname_estado3 = $row_historial['idestado3']; mysql_select_db($database_config, $config); $query_estado3 = sprintf("SELECT * FROM slc_stocksud_estadocredito3 WHERE idestado = %s", GetSQLValueString($colname_estado3, "int")); $estado3 = mysql_query($query_estado3, $config) or die(mysql_error()); $row_estado3 = mysql_fetch_assoc($estado3); $totalRows_estado3 = mysql_num_rows($estado3); ?> <tr valign="middle"> <td align="left" valign="middle" class="Estilo1"><?php echo fecha($row_historial['fechahora'],0); ?></td> <td valign="middle" class="Estilo1"><?php echo $row_usuario['usuario']; ?></td> <td align="right" valign="middle" class="Estilo1"><?php echo $row_historial['importeaprobado']; ?></td> <td valign="middle" class="Estilo1"><?php echo $row_estado['estado']; ?></td> <td valign="middle" class="Estilo1"><?php echo $row_estado2['estado']; ?></td> <td valign="middle" class="Estilo1"><?php echo $row_estado3['estado']; ?></td> </tr> <?php } while ($row_historial = mysql_fetch_assoc($historial)); ?> </table> </div></td> </tr> </table> </body> </html> <?php mysql_free_result($historial); mysql_free_result($usuario); mysql_free_result($estado); ?> <file_sep>/turnos_guardar.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function ultimodia($anho,$mes){ if (((fmod($anho,4)==0) and (fmod($anho,100)!=0)) or (fmod($anho,400)==0)) { $dias_febrero = 29; } else { $dias_febrero = 28; } switch($mes) { case 1: return 31; break; case 2: return $dias_febrero; break; case 3: return 31; break; case 4: return 30; break; case 5: return 31; break; case 6: return 30; break; case 7: return 31; break; case 8: return 31; break; case 9: return 30; break; case 10: return 31; break; case 11: return 30; break; case 12: return 31; break; } } function diasemana ($dia, $mes, $ano) { $dias = array('do', 'lu', 'ma', 'mi', 'ju', 'vi', 'sa'); return $dias[date('w', mktime(0,0,0,$mes,$dia,$ano))]; } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "formGuardar")) { $anio = $_POST["anio"]; $mes = $_POST["mes"]; $cantdias = ultimodia($anio,$mes); for($i=1; $i<=$cantdias;$i++){ $colname_feriados = $anio . "-" . $mes . "-" . $i; mysql_select_db($database_config, $config); $query_feriados = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriados, "date")); $feriados = mysql_query($query_feriados, $config) or die(mysql_error()); $row_feriados = mysql_fetch_assoc($feriados); $totalRows_feriados = mysql_num_rows($feriados); if($totalRows_feriados == 0) { $colname_turno = $anio . "-" . $mes . "-" . $i; mysql_select_db($database_config, $config); $query_turno = sprintf("SELECT * FROM slc_stocksud_turno WHERE DATE(fechahora) = %s", GetSQLValueString($colname_turno, "date")); $turno = mysql_query($query_turno, $config) or die(mysql_error()); $row_turno = mysql_fetch_assoc($turno); $totalRows_turno = mysql_num_rows($turno); if($totalRows_turno == 0){ if(diasemana($i,$mes,$anio) == 'lu' || diasemana($i,$mes,$anio) == 'ma' || diasemana($i,$mes,$anio) == 'mi' || diasemana($i,$mes,$anio) == 'ju' || diasemana($i,$mes,$anio) == 'vi'){ $fechahora = $anio . "-" . $mes . "-" . $i . " " . "09:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "10:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "10:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "11:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "11:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "12:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "12:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "17:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "18:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "18:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "19:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "19:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "20:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "20:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } elseif(diasemana($i,$mes,$anio) == 'sa'){ $fechahora = $anio . "-" . $mes . "-" . $i . " " . "09:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "10:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "10:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "11:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "11:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "12:00:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $fechahora = $anio . "-" . $mes . "-" . $i . " " . "12:30:00"; $insertSQL = sprintf("INSERT INTO slc_stocksud_turno (fechahora, id, stockreserva) VALUES (%s, %s, %s)", GetSQLValueString($fechahora, "date"), GetSQLValueString('0', "text"), GetSQLValueString('0', "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } } } } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { $idturno = $_POST['idturno']; $cant = count ($idturno); for($i=0; $i<$cant; $i++){ $deleteSQL = sprintf("DELETE FROM slc_stocksud_turno WHERE idturno=%s", GetSQLValueString($idturno[$i], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script> function CloseWin(){ window.close(); } </script> </head> <body onLoad="CloseWin();"> </body> <file_sep>/modelos_facturacion_equivalencias_importador.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); ?> <?php $mensaje = ""; if ((isset($_POST["Importar"])) && ($_POST["Importar"] == "Importar")) { if($_FILES['pathArchivo']['name']!=''){ if($_FILES['pathArchivo']['size']){ $type = explode(".", $_FILES['pathArchivo']['name']); if($type[1] == 'csv'){ $fp = fopen ($_FILES['pathArchivo']['tmp_name'],"r"); if ($fp != false) { if(count(fgetcsv($fp,1000,',')) > 1) { $separador = ','; } elseif(count(fgetcsv($fp,1000,';')) > 1) { $separador = ';'; } } fclose ($fp); $fp = fopen ($_FILES['pathArchivo']['tmp_name'],"r"); if ($fp != false) { if( !ini_get('safe_mode') ){ set_time_limit(90); } $estableceri = 0; while ($data = fgetcsv ($fp, 1000, $separador)) { $i = 0; if($estableceri == 0) { foreach($data as $row) { switch (trim(strtolower($row))) { case 'modelo': $imodelo = $i; break; case 'modelo nuevo': $imodelonuevo = $i; break; } $i++ ; } $estableceri = 1; } else { $colname_modelo = trim($data[$imodelo]); mysql_select_db($database_config, $config); $query_modelo = sprintf("SELECT * FROM slc_stocksud_modelo WHERE modelo LIKE %s ", GetSQLValueString($colname_modelo, "text")); $modelo = mysql_query($query_modelo, $config) or die(mysql_error()); $row_modelo = mysql_fetch_assoc($modelo); $totalRows_modelo = mysql_num_rows($modelo); $colname_modelonuevo = trim($data[$imodelonuevo]); mysql_select_db($database_config, $config); $query_modelonuevo = sprintf("SELECT * FROM slc_stocksud_modelo WHERE modelo LIKE %s ", GetSQLValueString($colname_modelonuevo, "text")); $modelonuevo = mysql_query($query_modelonuevo, $config) or die(mysql_error()); $row_modelonuevo = mysql_fetch_assoc($modelonuevo); $totalRows_modelonuevo = mysql_num_rows($modelonuevo); if($totalRows_modelo > 0){ if($totalRows_modelonuevo > 0){ $colname_modeloexiste = trim($data[$imodelo]); mysql_select_db($database_config, $config); $query_modeloexiste = sprintf("SELECT * FROM slc_stocksud_modelofacturacionequivalencia WHERE modelo LIKE %s ", GetSQLValueString($colname_modeloexiste, "text")); $modeloexiste = mysql_query($query_modeloexiste, $config) or die(mysql_error()); $row_modeloexiste = mysql_fetch_assoc($modeloexiste); $totalRows_modeloexiste = mysql_num_rows($modeloexiste); if($totalRows_modeloexiste > 0) { $updateSQL = sprintf("UPDATE slc_stocksud_modelofacturacionequivalencia SET modelonuevo=%s WHERE modelo=%s", GetSQLValueString(trim($data[$imodelo]), "text"), GetSQLValueString(trim($data[$imodelonuevo]), "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $mensajemodeloact .= $data[$imodelo] . "-" . $data[$imodelonuevo] . "<br>"; } else { $insertSQL = sprintf("INSERT INTO slc_stocksud_modelofacturacionequivalencia (modelo, modelo_id, modelonuevo, modelonuevo_id) VALUES (%s, %s, %s, %s)", GetSQLValueString(trim($data[$imodelo]), "text"), GetSQLValueString($row_modelo['idmodelo'], "int"), GetSQLValueString(trim($data[$imodelonuevo]), "text"), GetSQLValueString($row_modelonuevo['idmodelo'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $mensajemodeloimp .= $data[$imodelo] . "-" . $data[$imodelonuevo] . "<br>"; } } else { $mensajemodelonuevonoimp .= $data[$imodelo] . "<br>"; } } else { $mensajemodelonoimp .= $data[$imodelo] . "<br>"; } } } fclose ($fp); } else { $mensaje="Error al abrir el archivo."; } } else { $mensaje="El archivo seleccionado debe ser CSV (delimitado por comas)."; } } else { $mensaje="El archivo seleccionado no es correcto."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } </style> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD </span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>MODELOS DE FACTURACI&Oacute;N EQUIVALENCIAS</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td valign="top" bgcolor="#FFFFFF"><table width="100%" cellpadding="0" cellspacing="4"> <?php if($mensaje != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo $mensaje;?></td> </tr> <?php }?> <?php if($mensajemodeloact != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han actualizados, los siguientes modelos anteriores (modelo anterior - modelo nuevo): <br>" . $mensajemodeloact;?></td> </tr> <?php }?> <?php if($mensajemodeloimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, los siguientes registros (modelo anterior - modelo nuevo): <br>" . $mensajemodeloimp;?></td> </tr> <?php }?> <?php if($mensajemodelonuevonoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, los registros que contienen los modelos nuevos siguientes, porque estos modelos no se encuentran en la base de datos de modelos: <br>" . $mensajemodelonuevonoimp;?></td> </tr> <?php }?> <?php if($mensajemodelonoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, los registros que contienen los modelos anteriores siguientes, porque estos modelos no se encuentran en la base de datos de modelos: <br>" . $mensajemodelonoimp;?></td> </tr> <?php }?> </table> </td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); mysql_free_result($modelo); ?> <file_sep>/reporte_consultastock_exportar.php <?php require_once('Connections/config.php'); ?> <?php include("mysql2csv.php"); ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo, nombre FROM slc_stock_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $fieldseparator = ';'; $col_names_query = "ORD.".$fieldseparator. "MES" .$fieldseparator. " AŅO".$fieldseparator . " PROGRAMACION".$fieldseparator. "FACTURA N°".$fieldseparator. "SUCURSAL".$fieldseparator. "DEPOSITO" .$fieldseparator . "SUCURSAL DE VENTA" .$fieldseparator. "CHASIS".$fieldseparator. "MODELO".$fieldseparator. "COLOR".$fieldseparator. "CERTIFICADO". $fieldseparator. "MODELO CERTIFICADO". $fieldseparator. "IMPORTE".$fieldseparator. "RESERVA".$fieldseparator. "OBS.RESERVA".$fieldseparator. "CLIENTE".$fieldseparator. "FECHA SOLICITUD".$fieldseparator. "ENTREGA".$fieldseparator. "FECHA ENTREGA".$fieldseparator. "PRECIO VENTA".$fieldseparator. "INTERESES".$fieldseparator. "ACCESORIOS".$fieldseparator. "TOTAL".$fieldseparator. "VENDEDOR ".$fieldseparator. "COMISION".$fieldseparator. "USADO".$fieldseparator. "BANCO".$fieldseparator. "\n"; $values_query= str_replace('\\','',$_POST['query_stock']); $fieldseparator=';'; //excel needs comma rather than semi colon $download_file=1; //should the file be downloaded from browser(1) or saved to the server(0)? $filename = "consulta_stock"; //contains name of download file or (depending on $download_file) the path to save csv file without file extension. exportCSV($values_query, $col_names_query, $col_count=28, $fieldseparator=';', $filename, $download_file); die(); mysql_free_result($usuario_sesion); ?><file_sep>/reportes_historialasignaciones2.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session session_start(); // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles session_unregister('MM_Username'); session_unregister('MM_UserGroup'); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php //session_start(); $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $colname_stock = "-1"; if (isset($_POST['chasis'])) { $colname_stock = $_POST['chasis']; } mysql_select_db($database_config, $config); if(isset($_POST['chasis']) && ($_POST['chasis'] != '')) { $query_stock = sprintf("SELECT * FROM slc_stocksud_asignacion LEFT JOIN slc_stocksud_stock ON slc_stocksud_asignacion.idstock = slc_stocksud_stock.idstock LEFT JOIN slc_stocksud_usuario ON slc_stocksud_asignacion.idUsuario = slc_stocksud_usuario.idUsuario WHERE chasis LIKE %s ORDER BY fechahora", GetSQLValueString( '%' . $colname_stock . '%', "text")); } else { $query_stock = "SELECT * FROM slc_stocksud_asignacion LEFT JOIN slc_stocksud_stock ON slc_stocksud_asignacion.idstock = slc_stocksud_stock.idstock LEFT JOIN slc_stocksud_usuario ON slc_stocksud_asignacion.idUsuario = slc_stocksud_usuario.idUsuario ORDER BY fechahora"; } $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } .Estilo3 {color: #FF0000} --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><BR> <table width="99%" height="82" border="1" align="center" cellpadding="4" cellspacing="0" bordercolor="#CCCCCC" id="ppal"> <tr class="Estilo1"> <td height="20" colspan="5" class="Estilo2"><div align="center"><strong>REPORTE DE HISTORIAL DE ASIGNACIONES</strong></div></td> </tr> <tr class="Estilo1"> <td height="20" class="Estilo2">ORD.</td> <td><span class="Estilo2">MES A&Ntilde;O</span></td> <td><span class="Estilo2">CHASIS</span></td> <td><span class="Estilo2">USUARIO</span></td> <td><span class="Estilo2">FECHA HORA</span></td> <?php if(($row_usuario_sesion['idGrupo'] == 1) || ($row_usuario_sesion['idGrupo'] == 2)){ ?> <?php } ?> </tr> <?php do { ?> <tr class="Estilo1"> <td height="20"><?php echo $row_stock['orden']; ?>&nbsp;</td> <td><?php echo $row_stock['mes']; ?> <?php echo $row_stock['anio']; ?>&nbsp;</td> <td>&nbsp;<?php echo $row_stock['chasis']; ?></td> <td><?php echo $row_stock['usuario']; ?></td> <td><?php echo fecha($row_stock['fechahora'],0); ?></td> <?php } while ($row_stock = mysql_fetch_assoc($stock)); ?> </table> <blockquote class="Estilo1"> <div align="right">Cantidad de Registros <?php echo $totalRows_stock ?></div> <div align="left"> <?php echo date('d-m-Y H:i');?> </div> <div align="right"><a href="#"><img src="img/imprimir.gif" alt="Imprimir" width="26" height="23" border="0" onClick="MM_callJS('window.print();')"></a></div> </blockquote> </body> </html> <?php mysql_free_result($stock); mysql_free_result($usuario_sesion); ?> <file_sep>/descuentos_especiales.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $currentPage = $_SERVER["PHP_SELF"]; if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { $updateSQL = sprintf("UPDATE slc_stocksud_stock SET descuentoespweb=%s, descuentoespsalon=%s WHERE idstock=%s", GetSQLValueString($_POST['descuentoespweb'], "text"), GetSQLValueString($_POST['descuentoespsalon'], "text"), GetSQLValueString($_POST['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $maxRows_stock = 20; $pageNum_stock = 0; if (isset($_GET['pageNum_stock'])) { $pageNum_stock = $_GET['pageNum_stock']; } $startRow_stock = $pageNum_stock * $maxRows_stock; $colname_stock = ""; if (isset($_GET['chasis'])) { $colname_stock = $_GET['chasis']; } $colname2_stock = ""; if (isset($_GET['descuentoespweb'])) { $colname2_stock = $_GET['descuentoespweb']; } $colname3_stock = ""; if (isset($_GET['descuentoespsalon'])) { $colname3_stock = $_GET['descuentoespsalon']; } mysql_select_db($database_config, $config); if($row_usuario_sesion['idGrupo'] == '3') { $query_stock .= sprintf("SELECT slc_stocksud_stock.idstock, slc_stocksud_stock.chasis, slc_stocksud_stock.modelo, slc_stocksud_stock.color, slc_stocksud_stock.descuentoespweb, slc_stocksud_stock.descuentoespsalon FROM slc_stocksud_stock LEFT JOIN slc_stocksud_descuento_vendedor ON slc_stocksud_descuento_vendedor.idstock = slc_stocksud_stock.idstock WHERE slc_stocksud_stock.idCliente = 0 AND (slc_stocksud_stock.reserva IS NULL OR slc_stocksud_stock.reserva = 0) AND slc_stocksud_stock.chasis LIKE %s AND slc_stocksud_descuento_vendedor.idvendedor = %s ", GetSQLValueString("%" . $colname_stock . "%", "text"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); if($colname2_stock == '0'){ $query_stock .= " AND descuentoespweb = 0 "; } if($colname2_stock == '1'){ $query_stock .= " AND descuentoespweb > 0 "; } if($colname3_stock == '0'){ $query_stock .= " AND descuentoespsalon = 0 "; } if($colname3_stock == '1'){ $query_stock .= " AND descuentoespsalon > 0 "; } $query_stock .= " ORDER BY slc_stocksud_stock.chasis "; } else { $query_stock = sprintf("SELECT slc_stocksud_stock.idstock, slc_stocksud_stock.chasis, slc_stocksud_stock.modelo, slc_stocksud_stock.color, slc_stocksud_stock.descuentoespweb, slc_stocksud_stock.descuentoespsalon FROM slc_stocksud_stock WHERE slc_stocksud_stock.idCliente = 0 AND (slc_stocksud_stock.reserva IS NULL OR slc_stocksud_stock.reserva = 0) AND slc_stocksud_stock.chasis LIKE %s ", GetSQLValueString("%" . $colname_stock . "%", "text")); if($colname2_stock == '0'){ $query_stock .= " AND descuentoespweb = 0 "; } if($colname2_stock == '1'){ $query_stock .= " AND descuentoespweb > 0 "; } if($colname3_stock == '0'){ $query_stock .= " AND descuentoespsalon = 0 "; } if($colname3_stock == '1'){ $query_stock .= " AND descuentoespsalon > 0 "; } $query_stock .= " ORDER BY slc_stocksud_stock.chasis "; } $query_limit_stock = sprintf("%s LIMIT %d, %d", $query_stock, $startRow_stock, $maxRows_stock); $stock = mysql_query($query_limit_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); if (isset($_GET['totalRows_stock'])) { $totalRows_stock = $_GET['totalRows_stock']; } else { $all_stock = mysql_query($query_stock); $totalRows_stock = mysql_num_rows($all_stock); } $totalPages_stock = ceil($totalRows_stock/$maxRows_stock)-1; $queryString_stock = ""; if (!empty($_SERVER['QUERY_STRING'])) { $params = explode("&", $_SERVER['QUERY_STRING']); $newParams = array(); foreach ($params as $param) { if (stristr($param, "pageNum_stock") == false && stristr($param, "totalRows_stock") == false) { array_push($newParams, $param); } } if (count($newParams) != 0) { $queryString_stock = "&" . htmlentities(implode("&", $newParams)); } } $queryString_stock = sprintf("&totalRows_stock=%d%s", $totalRows_stock, $queryString_stock); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo21 {color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> function MM_validateForm() { //v4.0 if (document.getElementById){ var i,p,q,nm,tl,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); tl=val.title; if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- El '+tl+' es requerido.\n'; } } if (errors) alert('Error:\n'+errors); document.MM_returnValue = (errors == ''); } } </script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD</span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>DESCUENTOS ESPECIALES</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td height="220" valign="top" bgcolor="#FFFFFF"><table width="100%" height="100%" cellpadding="0" cellspacing="0"> <tr> <td valign="top" class="Estilo11"><table width="100%" align="center" cellpadding="2" cellspacing="0"> <tr> <td><table width="100%" cellpadding="0"><MM_HIDDENREGION><MM:DECORATION OUTLINE="Mostrar%20si..." OUTLINEID=1><MM_REPEATEDREGION SOURCE="@@rs@@"><MM:DECORATION OUTLINE="Repetir" OUTLINEID=2> <tr valign="middle"></tr></MM:DECORATION></MM_REPEATEDREGION></MM:DECORATION></MM_HIDDENREGION> </table> <table width="100%" align="center" cellpadding="2" cellspacing="0"> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="22" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="0"> <tr> <td height="10" valign="middle" bgcolor="#EFEFEF" class="Estilo11"><form action="descuentos_especiales.php" method="GET" name="formBuscar" id="formBuscar"> <span class="Estilo21">CHASIS</span> <input name="chasis" type="text" class="Estilo11" id="chasis" value="<?php if(isset($_GET['chasis'])) { echo $_GET['chasis'];}?>" size="20" maxlength="100" onFocus="this.value=''"> &nbsp;<span class="Estilo21">DESCUENTO ESPECIAL WEB <select name="descuentoespweb" class="Estilo11" id="descuentoespweb"> <option value="" <?php if (!(strcmp("", $_GET['descuentoespweb']))) {echo "selected=\"selected\"";} ?>></option> <option value="0" <?php if (!(strcmp(0, $_GET['descuentoespweb']))) {echo "selected=\"selected\"";} ?>>Sin descuento</option> <option value="1" <?php if (!(strcmp(1, $_GET['descuentoespweb']))) {echo "selected=\"selected\"";} ?>>Con descuento</option> </select> &nbsp;DESCUENTO ESPECIAL SALON <select name="descuentoespsalon" class="Estilo11" id="descuentoespsalon"> <option value="" <?php if (!(strcmp("", $_GET['descuentoespsalon']))) {echo "selected=\"selected\"";} ?>></option> <option value="0" <?php if (!(strcmp(0, $_GET['descuentoespsalon']))) {echo "selected=\"selected\"";} ?>>Sin descuento</option> <option value="1" <?php if (!(strcmp(1, $_GET['descuentoespsalon']))) {echo "selected=\"selected\"";} ?>>Con descuento</option> </select> </span> <input name="buscar" type="submit" class="Estilo11" id="buscar" value="Buscar"> </form></td> </tr> </table> </td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="22" bgcolor="#FFFFFF" class="Estilo11"> <table width="100%" cellpadding="0"> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" class="Estilo11"><span class="Estilo21"> CHASIS</span></td> <td class="Estilo11"><span class="Estilo21">MODELO</span></td> <td class="Estilo11"><span class="Estilo21">COLOR</span></td> <td align="right" class="Estilo11"><span class="Estilo21">DESCUENTO ESPECIAL WEB</span></td> <td align="right" class="Estilo11"><span class="Estilo21">DESCUENTO ESPECIAL SALON</span></td> <td colspan="2" class="Estilo11"><span class="Estilo21">VENDEDORES</span></td> <td colspan="3" align="right" class="Estilo11">&nbsp;</td> </tr> <?php if ($totalRows_stock > 0) { // Show if recordset not empty ?> <?php $i = 0; ?> <?php do { ?> <?php $colname_vendedores = $row_stock['idstock']; mysql_select_db($database_config, $config); $query_vendedores = sprintf("SELECT slc_stocksud_descuento_vendedor.idvendedor, slc_stocksud_usuario.nombre FROM slc_stocksud_descuento_vendedor LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_descuento_vendedor.idvendedor WHERE slc_stocksud_descuento_vendedor.idstock = %s", GetSQLValueString($colname_vendedores, "int")); $vendedores = mysql_query($query_vendedores, $config) or die(mysql_error()); $row_vendedores = mysql_fetch_assoc($vendedores); $totalRows_vendedores = mysql_num_rows($vendedores); ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="formGuardar<?php echo $i;?>" target="_parent" id="formGuardar<?php echo $i;?>"> <tr valign="middle"> <td height="20" class="Estilo11"><?php echo $row_stock['chasis']; ?></td> <td height="20" class="Estilo11"><?php echo $row_stock['modelo']; ?></td> <td height="20" class="Estilo11"><?php echo $row_stock['color']; ?></td> <td align="right" class="Estilo11"><a href="#" onClick="document.formGuardar<?php echo $i;?>.submit();"> <input name="idstock" type="hidden" id="idstock" value="<?php echo $row_stock['idstock']; ?>"> </a> <input name="descuentoespweb" type="text" class="Estilo11" id="descuentoespweb" value="<?php echo $row_stock['descuentoespweb']; ?>" size="15" maxlength="10" <?php if(($row_usuario_sesion['idGrupo'] == '2') || ($row_usuario_sesion['idGrupo'] == '3')){ echo "readonly";}?>> </td> <td align="right" class="Estilo11"><input name="descuentoespsalon" type="text" class="Estilo11" id="descuentoespsalon" value="<?php echo $row_stock['descuentoespsalon']; ?>" size="15" maxlength="10" <?php if(($row_usuario_sesion['idGrupo'] == '2') || ($row_usuario_sesion['idGrupo'] == '3')){ echo "readonly";}?>></td> <td class="Estilo11"> <?php if ($totalRows_vendedores > 0) { // Show if recordset not empty ?> <?php do { ?> <?php if($row_vendedores['idvendedor'] == 0) { echo "Todos"; } else { ?> <?php echo $row_vendedores['nombre']; ?>&nbsp; <?php } ?> <?php } while ($row_vendedores = mysql_fetch_assoc($vendedores)); ?> <?php } // Show if recordset not empty ?> </td> <td height="18" align="right" class="Estilo11"> <?php if($row_usuario_sesion['idGrupo'] == '1') { ?> <?php if($row_stock['descuentoespsalon'] > 0) { ?> <a href="#"><img src="img/editar.gif" alt="Modificar" width="18" height="18" border="0" onClick="window.open('descuentos_especiales_editar.php?idstock=<?php echo $row_stock['idstock']; ?>','Stock','scrollbars=yes,resizable=yes,width=400,height=500')"></a> <?php } ?> <?php } ?> </td> <td class="Estilo11"> <?php if($row_usuario_sesion['idGrupo'] == '1') { ?> <a href="#" onClick="document.formGuardar<?php echo $i;?>.submit();"><img src="img/save_f2.png" alt="Guardar" width="15" height="15" border="0" onClick="#"> <input name="MM_update" type="hidden" id="MM_update" value="formGuardar"> </a> <?php } ?> </td> </tr> </form> <?php $i++; ?> <?php } while ($row_stock = mysql_fetch_assoc($stock)); ?> <?php } // Show if recordset not empty ?> </table> </td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="2" colspan="22" bgcolor="#FFFFFF"></td> </tr> <?php if ($totalRows_stock > 0) { // Show if recordset not empty ?> <tr valign="middle"> <td height="20" colspan="7" valign="bottom" bgcolor="#EFEFEF" class="Estilo11"><?php if ($pageNum_stock > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_stock=%d%s", $currentPage, 0, $queryString_stock); ?>">|&lt;</a> <a href="<?php printf("%s?pageNum_stock=%d%s", $currentPage, max(0, $pageNum_stock - 1), $queryString_stock); ?>">&lt;&lt;</a> <?php } // Show if not first page ?> <?php if ($pageNum_stock < $totalPages_stock) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_stock=%d%s", $currentPage, min($totalPages_stock, $pageNum_stock + 1), $queryString_stock); ?>">&gt;&gt;</a> <a href="<?php printf("%s?pageNum_stock=%d%s", $currentPage, $totalPages_stock, $queryString_stock); ?>">&gt;|</a> <?php } // Show if not last page ?></td> <td width="82%" height="20" colspan="15" align="right" valign="bottom" bgcolor="#EFEFEF" class="Estilo11"><?php echo ($startRow_stock + 1) ?> - <?php echo min($startRow_stock + $maxRows_stock, $totalRows_stock) ?> / <?php echo $totalRows_stock ?></td> </tr> <?php } // Show if recordset not empty ?> </table> <table width="100%" cellpadding="0"> </table></td> </tr> </table></td> </tr> </table></td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); mysql_free_result($stock); ?> <file_sep>/planes_propios_sesiones_buscar_titulares.php <?php require_once('Connections/config.php'); ?> <?php require_once('funciones.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_clientes = "-1"; if (isset($_GET['q'])) { $colname_clientes = utf8_encode($_GET['q']); } else { return; } mysql_select_db($database_config, $config); $query_clientes = sprintf("SELECT idCliente, apellidoynombre, dni FROM slc_stock_cliente WHERE vigente = '1' AND apellidoynombre LIKE %s ", GetSQLValueString("%" . $colname_clientes . "%", "text")); $clientes = mysql_query($query_clientes, $config) or die(mysql_error()); $row_clientes = mysql_fetch_assoc($clientes); $totalRows_clientes = mysql_num_rows($clientes); if ($totalRows_clientes > 0) { // Show if recordset not empty do { echo utf8_encode($row_clientes['apellidoynombre']). "(DNI " . $row_clientes['dni'] . ")" . "|" . utf8_encode($row_clientes['apellidoynombre']) . "|" . $row_clientes['idCliente'] . "\n"; } while ($row_clientes = mysql_fetch_assoc($clientes)); } // Show if recordset not empty mysql_free_result($clientes); ?> <file_sep>/turnos_asignar.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $currentPage = $_SERVER["PHP_SELF"]; $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idGrupo, nombre FROM slc_stock_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } ?> <?php require ("calendario_asignar.php"); if(isset($_GET['nuevo_mes']) && isset($_GET['nuevo_ano']) && isset($_GET['dia'])) { $mes = $_GET['nuevo_mes']; $ano = $_GET['nuevo_ano']; $dia = $_GET['dia']; $fecha=$ano . "-" . $mes . "-" . $dia; $tiempo_actual = time(); $anoActual = $_GET['nuevo_ano']; }else { $tiempo_actual = time(); $mes = date("n", $tiempo_actual); $ano = date("Y", $tiempo_actual); $anoActual = date("Y", $tiempo_actual); $dia=date("d"); $fecha=$ano . "-" . $mes . "-" . $dia; } $mes_hoy=date("m"); $ano_hoy=date("Y"); $dia_hoy=date("d"); $id = $_GET['id']; $stockreserva = $_GET['stockreserva']; $colname_stock = $id ; mysql_select_db($database_config, $config); if($stockreserva == 1){ $query_stock = sprintf("SELECT slc_stocksud_stock.idstock AS id, slc_stock_cliente.apellidoynombre AS cliente, slc_stocksud_stock.modelo, slc_stocksud_usuario.usuario AS vendedor, slc_stocksud_stock.chasis AS vin, slc_stocksud_banco.banco, slc_stocksud_banco.documentacion, 1 AS stockreserva, slc_stocksud_stock.importeaprobado FROM slc_stocksud_stock LEFT JOIN slc_stock_cliente ON slc_stocksud_stock.idCliente = slc_stock_cliente.idCliente LEFT JOIN slc_stocksud_usuario ON slc_stocksud_stock.idvendedor = slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_banco ON slc_stocksud_stock.idbanco = slc_stocksud_banco.idbanco WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); } else { $query_stock = sprintf("SELECT slc_stocksud_reserva.idreserva AS id, slc_stocksud_reserva.cliente, slc_stocksud_modelo.modelo, slc_stocksud_usuario.usuario AS vendedor, slc_stocksud_reserva.VIN AS vin, slc_stocksud_banco.banco, slc_stocksud_banco.documentacion, 2 AS stockreserva, slc_stocksud_reserva.importeaprobado FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_modelo ON slc_stocksud_reserva.idmodelo = slc_stocksud_modelo.idmodelo LEFT JOIN slc_stocksud_usuario ON slc_stocksud_reserva.idvendedor = slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_banco ON slc_stocksud_reserva.idbanco = slc_stocksud_banco.idbanco WHERE idreserva = %s", GetSQLValueString($colname_stock, "int")); } $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; f.action = 'turnos_guardar.php'; f.submit(); } function selectall(form) { var formulario = eval(form) for (var i=0, len=formulario.elements.length; i<len ; i++) { if ( formulario.elements[i].type == "checkbox" ) formulario.elements[i].checked = formulario.elements[0].checked } } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <table width="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top"> <div align="center"> <table width="100%" cellpadding="0" cellspacing="4"> <tr> <td> <table width="100%" cellspacing="0" cellpadding="0"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo1"><strong>TURNOS Seleccionar fecha y hora</strong></td> </tr></table> </td> </tr> <tr> <td valign="top" class="Estilo11"><table width="100%" height="250" align="center" cellpadding="0" cellspacing="0"> <tr valign="middle" bgcolor="#EFEFEF"> <td height="3" align="center" bgcolor="#FFFFFF" class="Estilo1"> <table width="100%" border="0" cellspacing="0" cellpadding="0" align="center"> <tr> <td class="Estilo1"><table width="600" border="1" align="center" cellpadding="3" cellspacing="0"> <tr bgcolor="#EFEFEF" class="Estilo1"> <td height="25" colspan="4"><strong>DATOS DEL CLIENTE </strong></td> </tr> <tr> <td width="16%" height="20" class="Estilo1"><strong>Cliente</strong></td> <td width="34%" class="Estilo1"><?php echo $row_stock['cliente']; ?></td> <td width="20%" class="Estilo1"><strong>Modelo</strong></td> <td width="30%" class="Estilo1"><?php echo $row_stock['modelo']; ?></td> </tr> <tr> <td height="20" class="Estilo1"><strong>Banco</strong></td> <td class="Estilo1"><?php echo $row_stock['banco']; ?></td> <td class="Estilo1"><strong>VIN</strong></td> <td class="Estilo1"><?php echo $row_stock['vin']; ?></td> </tr> <tr> <td height="20" class="Estilo1"><strong>Importe Aprobado</strong></td> <td class="Estilo1"><?php echo $row_stock['importeaprobado']; ?></td> <td class="Estilo1">&nbsp;</td> <td class="Estilo1">&nbsp;</td> </tr> <tr> <td height="20" class="Estilo1"><strong>Requisitos</strong></td> <td colspan="3" class="Estilo1"><?php echo $row_stock['documentacion']; ?></td> </tr> </table> <br><br></td> </tr> <tr> <td class="Estilo1"><?php mostrar_calendario($dia,$mes,$ano,$i,$diasEventos,$id,$stockreserva);?></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </div></td> </tr> </table> </body> </html> <file_sep>/reservas_buscar_vin.php <?php require_once('Connections/config.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_chasis = "-1"; if (isset($_GET['q'])) { $colname_chasis = $_GET['q']; } mysql_select_db($database_config, $config); $query_chasis = sprintf("(SELECT comision2, chasis, modelo, color, 0 AS stocknofacturado, 'Facturado' AS tipostock FROM slc_stocksud_stock WHERE chasis LIKE %s AND idCliente = '0') UNION (SELECT comision2, chasis, modelo, color, 1 AS stocknofacturado, 'No Facturado' AS tipostock FROM slc_stocksud_stocknofacturado WHERE chasis LIKE %s AND idCliente = '0') ORDER BY chasis ASC", GetSQLValueString("%" . $colname_chasis . "%", "text"), GetSQLValueString("%" . $colname_chasis . "%", "text")); $chasis = mysql_query($query_chasis, $config) or die(mysql_error()); $row_chasis = mysql_fetch_assoc($chasis); $totalRows_chasis = mysql_num_rows($chasis); if ($totalRows_chasis > 0) { // Show if recordset not empty do { echo $row_chasis['chasis'] . " modelo:" . $row_chasis['modelo'] . " color:" . $row_chasis['color'] . " " . $row_chasis['tipostock'] . "|" . $row_chasis['chasis'] . "|" . $row_chasis['stocknofacturado'] . "|" . $row_chasis['comision2'] . "\n"; } while ($row_chasis = mysql_fetch_assoc($chasis)); } // Show if recordset not empty mysql_free_result($chasis); ?> <file_sep>/reservas_guardar.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { mysql_select_db($database_config, $config); $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET fecha=%s, cliente=%s, idmodelo=%s, idvendedor=%s, idcolor1=%s, idcolor2=%s, idcolor3=%s, VIN=%s, comision2=%s, importe=%s, idbanco=%s, idcuota=%s, importesolicitado=%s WHERE idreserva=%s", GetSQLValueString(fecha($_POST['fecha']), "date"), GetSQLValueString($_POST['cliente'], "text"), GetSQLValueString($_POST['idmodelo'], "int"), GetSQLValueString($_POST['idvendedor'], "int"), GetSQLValueString($_POST['idcolor1'], "int"), GetSQLValueString($_POST['idcolor2'], "int"), GetSQLValueString($_POST['idcolor3'], "int"), GetSQLValueString($_POST['VIN'], "text"), GetSQLValueString($_POST['comision2'], "int"), GetSQLValueString($_POST['importe'], "double"), GetSQLValueString($_POST['idbanco'], "int"), GetSQLValueString($_POST['idcuota'], "int"), GetSQLValueString($_POST['importesolicitado'], "double"), GetSQLValueString($_POST['idreserva'], "int")); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); if((isset($_POST['VIN']) && ($_POST['VIN'] != '')) || (isset($_POST['comision2']) && ($_POST['comision2'] != ''))){ if(isset($_POST['stocknofacturado']) &&($_POST['stocknofacturado'] == '0')){ $colname_stock = $_POST['VIN']; $colname2_stock = $_POST['comision2']; $query_stock = sprintf("SELECT idstock FROM slc_stocksud_stock WHERE chasis = %s OR comision2 = %s", GetSQLValueString($colname_stock, "text"), GetSQLValueString($colname2_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if($totalRows_stock > 0){ if(isset($_POST['idSolicitud']) && ($_POST['idSolicitud'] != '0')){ header("Location: stock_solicitud.php?idstock=" . $row_stock['idstock'] . "&idSolicitud=". $_POST['idSolicitud'] . "&idreserva=" . $_POST['idreserva']); exit; } else { $mensaje = "La reserva se guardó, pero no se puede asignar al stock porque no tiene una solicitud de reserva asociada."; } } } elseif(isset($_POST['stocknofacturado']) && ($_POST['stocknofacturado'] == '1')){ $colname_stock = $_POST['VIN']; $colname2_stock = $_POST['comision2']; $query_stock = sprintf("SELECT idstock FROM slc_stocksud_stocknofacturado WHERE chasis = %s OR comision2 = %s", GetSQLValueString($colname_stock, "text"), GetSQLValueString($colname2_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if($totalRows_stock > 0){ if(isset($_POST['idSolicitud']) && ($_POST['idSolicitud'] != '0')){ header("Location: stock_nofacturado_solicitud.php?idstock=" . $row_stock['idstock'] . "&idSolicitud=". $_POST['idSolicitud'] . "&idreserva=" . $_POST['idreserva']); exit; } else { $mensaje = "La reserva se guardó, pero no se puede asignar al stock porque no tiene una solicitud de reserva asociada."; } } } } } if ((isset($_POST["MM_delete"])) && ($_POST["MM_delete"] == "formGuardar")) { mysql_select_db($database_config, $config); $colname_reserva = $_POST['idreserva']; $query_reserva = sprintf("SELECT idSolicitud FROM slc_stocksud_reserva WHERE idreserva = %s", GetSQLValueString($colname_reserva, "int")); $reserva = mysql_query($query_reserva, $config) or die(mysql_error()); $row_reserva = mysql_fetch_assoc($reserva); $totalRows_reserva = mysql_num_rows($reserva); $updateSQL = sprintf("UPDATE slc_solicitudreserva SET reserva=%s WHERE idSolicitud=%s", GetSQLValueString('0', "int"), GetSQLValueString($row_reserva['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); mysql_select_db($database_config, $config); $deleteSQL = sprintf("DELETE FROM slc_stocksud_reserva WHERE idreserva=%s", GetSQLValueString($_POST['idreserva'], "int")); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_agenda SET estado=%s, cerradopor=%s WHERE estado<>%s AND idtipoevento=%s AND idSolicitud = %s", GetSQLValueString('1', "int"), GetSQLValueString('3', "int"), GetSQLValueString('1', "int"), GetSQLValueString('2', "int"), GetSQLValueString($_POST['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI GM</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script> function CloseWin(){ window.opener.location.reload(); window.close(); } </script> </head> <body <?php if($mensaje == '') { ?>onLoad="CloseWin();"<?php } ?> onUnload="CloseWin();"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>RESERVAS </strong></td> </tr> </table></td> </tr> <tr valign="middle"> <td class="Estilo1"><?php if($mensaje != '') { echo $mensaje; } ?></td> </tr> <tr valign="middle"> <td align="center" valign="middle" class="Estilo1"><input name="Cancelar" type="button" class="Estilo1" id="Cancelar" onClick="window.close()" value="Cerrar"></td> </tr> <tr valign="middle"> <td align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> </div></td> </tr> </table> </body> <file_sep>/reportes_historialanulaciones.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session session_start(); // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles session_unregister('MM_Username'); session_unregister('MM_UserGroup'); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo21 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script> <!-- function buscar(){ f=document.formBuscar; f.target = '_blank'; f.method = 'POST'; f.action = 'reportes_historialanulaciones2.php'; f.submit(); } //--> </script> <!-- Calendario Pou up --> <link rel=stylesheet href="xc2/css/xc2_default.css" type="text/css"> <style type="text/css"> .weekend { font-family:verdana; font-size:11px; line-height:14px; width:23px; text-align:center; color:#cc0000; background-color:#f0f0f0; border:1px solid #f0f0f0; padding:1px; cursor:pointer; } </style> <script language="javascript" src="xc2/config/xc2_default.js"></script> <script language="javascript"> xcDateFormat="dd-mm-yyyy"; xcArrowPosition=1; xcFootTagSwitch=[1, 0, 0, 0, 0, 0, 0, 0]; //xcMods[1].order=1; xcMods[2].order=1; </script> <script language="javascript" src="xc2/script/xc2_inpage.js"></script> <script language="javascript"> <!-- //setRange("1", daysAfter(0),daysAfter(45)); setLoopWeek("1", "weekend", "", 1, 1, "Sat", "Sun"); //--> </script> <!-- /Calendario Pou up --> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD</span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top" ><table width="100%" cellpadding="0" cellspacing="0"> <tr> <td height="30" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>REPORTE DE HISTORIAL DE ANULACIONES</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td height="220" valign="top"> <form method="post" id="formBuscar" name="formBuscar"> <table width="100%" height="0%" align="left" cellpadding="2" cellspacing="0"> <tr valign="middle" bgcolor="#EFEFEF"> <td width="9%" align="left" valign="middle" class="Estilo11"><p class="Estilo21">Chasis o VIN</p></td> <td width="11%" align="left" valign="middle" class="Estilo11"><label for="chasis"></label> <input name="chasis" type="text" class="Estilo11" id="chasis" size="20" maxlength="50" onClick="this.value='';"></td> <td width="80%" align="left" valign="middle" class="Estilo11"><input name="button" type="button" class="Estilo11" id="button" value="Buscar" onClick="buscar();"></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td colspan="3" align="center" class="Estilo11">&nbsp;</td> </tr> </table> </form> </td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); ?> <file_sep>/opcionales_vehiculos.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $currentPage = $_SERVER["PHP_SELF"]; $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); mysql_select_db($database_config, $config); $query_registros = "SELECT idfamilia, familia FROM slc_stocksud_familia ORDER BY familia ASC"; $registros = mysql_query($query_registros, $config) or die(mysql_error()); $row_registros = mysql_fetch_assoc($registros); $totalRows_registros = mysql_num_rows($registros); $colname_registros2 = ""; if (isset($_GET['idfamilia'])) { $colname_registros2 = $_GET['idfamilia']; } mysql_select_db($database_config, $config); $query_registros2 = sprintf("SELECT slc_stocksud_subfamilia.idsubfamilia, slc_stocksud_subfamilia.subfamilia FROM slc_stocksud_familia_subfamilia LEFT JOIN slc_stocksud_subfamilia ON slc_stocksud_subfamilia.idsubfamilia = slc_stocksud_familia_subfamilia.idsubfamilia WHERE slc_stocksud_familia_subfamilia.idfamilia = %s", GetSQLValueString($colname_registros2, "int")); $registros2 = mysql_query($query_registros2, $config) or die(mysql_error()); $row_registros2 = mysql_fetch_assoc($registros2); $totalRows_registros2 = mysql_num_rows($registros2); $colname_registros3 = ""; if (isset($_GET['idfamilia'])) { $colname_registros3 = $_GET['idfamilia']; } $colname2_registros3 = ""; if (isset($_GET['idsubfamilia'])) { $colname2_registros3 = $_GET['idsubfamilia']; } mysql_select_db($database_config, $config); $query_registros3 = "SELECT slc_stocksud_familia.idfamilia, slc_stocksud_familia.familia, slc_stocksud_subfamilia.idsubfamilia, slc_stocksud_subfamilia.subfamilia FROM slc_stocksud_familia_subfamilia LEFT JOIN slc_stocksud_familia ON slc_stocksud_familia.idfamilia = slc_stocksud_familia_subfamilia.idfamilia LEFT JOIN slc_stocksud_subfamilia ON slc_stocksud_subfamilia.idsubfamilia = slc_stocksud_familia_subfamilia.idsubfamilia "; if($colname_registros3 != ""){ $query_registros3 .= sprintf(" WHERE slc_stocksud_familia_subfamilia.idfamilia = %s", GetSQLValueString($colname_registros3, "int")); $where = 1; } if($colname2_registros3 != ""){ $query_registros3 .= sprintf(" AND slc_stocksud_familia_subfamilia.idSUBfamilia = %s", GetSQLValueString($colname2_registros3, "int")); } $query_registros3 .= " ORDER BY slc_stocksud_familia.familia, slc_stocksud_subfamilia.subfamilia"; $registros3 = mysql_query($query_registros3, $config) or die(mysql_error()); $row_registros3 = mysql_fetch_assoc($registros3); $totalRows_registros3 = mysql_num_rows($registros3); if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { $id = $_POST['id']; for($i=0;$i<count($id);$i++) { $ocpional = explode("-",$id[$i]); $deleteSQL = sprintf("DELETE FROM slc_stocksud_familia_sub_opcional WHERE idfamilia = %s AND idsubfamilia = %s", GetSQLValueString($ocpional[0], "int"), GetSQLValueString($ocpional[1], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); } for($i=0;$i<count($id);$i++) { $ocpional = explode("-",$id[$i]); $insertSQL = sprintf("INSERT INTO slc_stocksud_familia_sub_opcional (idfamilia, idsubfamilia, idopcional) VALUES (%s, %s, %s)", GetSQLValueString($ocpional[0], "int"), GetSQLValueString($ocpional[1], "int"), GetSQLValueString($ocpional[2], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } mysql_select_db($database_config, $config); $query_registros5 = "SELECT pr, descripcion FROM slc_stocksud_opcional"; $registros5 = mysql_query($query_registros5, $config) or die(mysql_error()); $row_registros5 = mysql_fetch_assoc($registros5); $totalRows_registros5 = mysql_num_rows($registros5); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI GM</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo21 {color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD</span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>OPCIONALES DE LOS VEHICULOS</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td height="220" valign="top" bgcolor="#FFFFFF"><table width="100%" height="100%" cellpadding="0" cellspacing="4"> <tr> <td valign="top" class="Estilo11"> <table width="100%" align="left" cellpadding="0" cellspacing="2"> <form action="opcionales_vehiculos.php" method="GET" name="formBuscar" id="formBuscar"> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="8" class="Estilo11"><table width="100%" cellspacing="0" cellpadding="0"> <tr> <td valign="middle" class="Estilo11"> <span class="Estilo21">FAMILIA</span> <select name="idfamilia" class="Estilo11" id="idfamilia" onChange="document.formBuscar.submit();"> <option value="" <?php if (!(strcmp("", $_GET['idfamilia']))) {echo "selected=\"selected\"";} ?>>Todas</option> <?php do { ?> <option value="<?php echo $row_registros['idfamilia']?>"<?php if (!(strcmp($row_registros['idfamilia'], $_GET['idfamilia']))) {echo "selected=\"selected\"";} ?>><?php echo $row_registros['familia']?></option> <?php } while ($row_registros = mysql_fetch_assoc($registros)); $rows = mysql_num_rows($registros); if($rows > 0) { mysql_data_seek($registros, 0); $row_registros = mysql_fetch_assoc($registros); } ?> </select> <span class="Estilo21">SUBFAMILIA</span> <select name="idsubfamilia" class="Estilo11" id="idsubfamilia"> <option value="" <?php if (!(strcmp("", $_GET['idsubfamilia']))) {echo "selected=\"selected\"";} ?>>Todas</option> <?php if ($totalRows_registros2 > 0) { // Show if recordset not empty ?> <?php do { ?> <option value="<?php echo $row_registros2['idsubfamilia']?>"<?php if (!(strcmp($row_registros2['idsubfamilia'], $_GET['idsubfamilia']))) {echo "selected=\"selected\"";} ?>><?php echo $row_registros2['subfamilia']?></option> <?php } while ($row_registros2 = mysql_fetch_assoc($registros2)); $rows = mysql_num_rows($registros2); if($rows > 0) { mysql_data_seek($registros2, 0); $row_registros2 = mysql_fetch_assoc($registros2); } ?> <?php } // Show if recordset not empty ?> </select> <input name="Submit" type="submit" class="Estilo11" value="Buscar"> </td> </tr> </table> </td> </tr> </form> <tr valign="middle" bgcolor="#EFEFEF"> <td height="2" colspan="8" bgcolor="#FFFFFF"></td> </tr> <form action="<?php echo $editFormAction; ?>" method="POST" name="formGuardar" target="_parent" id="formGuardar"> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" rowspan="2" class="Estilo11"><span class="Estilo21">FAMILIA</span></td> <td rowspan="2" class="Estilo11"><span class="Estilo21">SUBFAMILIA </span></td> <td colspan="<?php echo $totalRows_registros5;?>" class="Estilo11"><span class="Estilo21">OPCIONALES<a href="#" onClick="document.formGuardar.MM_update.value='formGuardar'; document.formGuardar.submit();"><img src="img/save_f2.png" alt="Guardar" width="15" height="15" border="0" onClick="#"> <input name="MM_update" type="hidden" id="MM_update" value=""> </a></span></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <?php if ($totalRows_registros5 > 0) { // Show if recordset not empty ?> <?php do { ?> <td class="Estilo11"><?php echo $row_registros5['pr'];?></td> <?php } while ($row_registros5 = mysql_fetch_assoc($registros5)); ?> <?php } // Show if recordset not empty ?> </tr> <?php if ($totalRows_registros3 > 0) { // Show if recordset not empty ?> <?php $i=0; ?> <?php do { ?> <?php $colname_registros4 = $row_registros3['idfamilia']; $colname2_registros4 = $row_registros3['idsubfamilia']; mysql_select_db($database_config, $config); $query_registros4 = sprintf("SELECT slc_stocksud_familia_sub_opcional.idfamiliasubopcional, slc_stocksud_opcional.idopcional, slc_stocksud_opcional.pr, slc_stocksud_opcional.descripcion FROM slc_stocksud_opcional LEFT JOIN slc_stocksud_familia_sub_opcional ON (slc_stocksud_familia_sub_opcional.idopcional = slc_stocksud_opcional.idopcional AND slc_stocksud_familia_sub_opcional.idfamilia = %s AND slc_stocksud_familia_sub_opcional.idsubfamilia = %s)", GetSQLValueString($colname_registros4, "int"), GetSQLValueString($colname2_registros4, "int")); $registros4 = mysql_query($query_registros4, $config) or die(mysql_error()); $row_registros4 = mysql_fetch_assoc($registros4); $totalRows_registros4 = mysql_num_rows($registros4); ?> <tr valign="middle"> <td height="20" class="Estilo11"><?php echo $row_registros3['familia']; ?></td> <td height="20" class="Estilo11"><?php echo $row_registros3['subfamilia']; ?></td> <?php if ($totalRows_registros4 > 0) { // Show if recordset not empty ?> <?php do { ?> <td height="20" class="Estilo11" align="left"> <input name="id[]" type="checkbox" id="id[]" title="<?php echo $row_registros4['descripcion']; ?>-<?php echo $row_registros3['idsubfamilia']; ?>-<?php echo $row_registros4['idopcional']; ?>" value="<?php echo $row_registros3['idfamilia']; ?>-<?php echo $row_registros3['idsubfamilia']; ?>-<?php echo $row_registros4['idopcional']; ?>" <?php if ($row_registros4['idfamiliasubopcional'] != '') {echo "checked=\"checked\"";} ?>> </td> <?php } while ($row_registros4 = mysql_fetch_assoc($registros4)); ?> <?php } // Show if recordset not empty ?> </tr> <tr valign="middle"> <td height="1" colspan="<?php echo ($totalRows_registros5+2);?>" bgcolor="#CCCCCC" class="Estilo11"></td> </tr> <?php } while ($row_registros3 = mysql_fetch_assoc($registros3)); ?> <?php } // Show if recordset not empty ?> </form> <tr valign="middle"> <td height="20" valign="bottom" bgcolor="#EFEFEF" class="Estilo11">&nbsp;<?php echo $totalRows_registros3 ?> registros</td> <td height="20" valign="bottom" bgcolor="#EFEFEF" class="Estilo11">&nbsp;</td> <td height="20" colspan="<?php echo $totalRows_registros5;?>" valign="bottom" bgcolor="#EFEFEF" class="Estilo11">&nbsp;</td> </tr> </table> </td> </tr> </table> </td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); mysql_free_result($registros); mysql_free_result($registros4); mysql_free_result($registros3); mysql_free_result($registros2); ?> <file_sep>/index.php <?php require_once('Connections/config.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['usuario'])) { $loginUsername=$_POST['usuario']; $password=<PASSWORD>('<PASSWORD>', md5($_POST['clave'])); $MM_fldUserAuthorization = "<PASSWORD>"; $MM_redirectLoginSuccess = "index2.php"; $MM_redirectLoginFailed = "index.php"; $MM_redirecttoReferrer = false; mysql_select_db($database_config, $config); $LoginRS__query=sprintf("SELECT usuario, clave, idGrupo FROM slc_stocksud_usuario WHERE usuario=%s AND clave=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $config) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = mysql_result($LoginRS,0,'idGrupo'); if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es un dato requerido.\n'; } } if (errors) alert('Error:\n'+errors); document.MM_returnValue = (errors == ''); } //--> </script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD</span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td height="250" align="center" valign="middle"><form ACTION="<?php echo $loginFormAction; ?>" METHOD="POST" name="formIngresar" id="formIngresar" onSubmit="MM_validateForm('usuario','','R','clave','','R');return document.MM_returnValue"> <table cellspacing="0" cellpadding="0"> <tr> <td width="59" class="Estilo1">usuario <span class="Estilo2">*</span> </td> <td width="90"><input name="usuario" type="text" id="usuario" size="15" maxlength="30"></td> </tr> <tr> <td class="Estilo1">clave <span class="Estilo2">*</span> </td> <td><input name="clave" type="password" id="clave" size="15" maxlength="30"></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="Submit" value="Ingresar"></td> </tr> </table> </form> </td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <file_sep>/planes_propios_sesiones_nuevo.php <?php require_once('Connections/config.php'); ?> <?php require_once('funciones.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } mysql_select_db($database_config, $config); $query_tipogastos = "SELECT * FROM slc_tipogasto ORDER BY tipogasto ASC"; $tipogastos = mysql_query($query_tipogastos, $config) or die(mysql_error()); $row_tipogastos = mysql_fetch_assoc($tipogastos); $totalRows_tipogastos = mysql_num_rows($tipogastos); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "formGuardar")) { $insertSQL = sprintf("INSERT INTO slc_planes_propios_sud_sesiones (fecha, idplanpropio, idtitularanterior) VALUES (%s, %s, %s)", GetSQLValueString(fecha($_POST['fecha']), "date"), GetSQLValueString($_POST['idplanpropio'], "int"), GetSQLValueString($_POST['idtitularanterior'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>TERRITORIO YACOPINI</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> function MM_validateForm() { //v4.0 if (document.getElementById){ var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' debe contener un valor numérico.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es requerido.\n'; } } if (errors) alert('Error:\n'+errors); document.MM_returnValue = (errors == ''); } } function MM_goToURL() { //v3.0 var i, args=MM_goToURL.arguments; document.MM_returnValue = false; for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'"); } </script> <!-- Calendario Pou up --> <link rel=stylesheet href="xc2/css/xc2_default.css" type="text/css"> <style type="text/css"> .weekend { font-family:verdana; font-size:11px; line-height:14px; width:23px; text-align:center; color:#cc0000; background-color:#f0f0f0; border:1px solid #f0f0f0; padding:1px; cursor:pointer; } #rojo { color: #F00; } </style> <script language="javascript" src="xc2/config/xc2_default.js"></script> <script language="javascript"> xcDateFormat="dd-mm-yyyy"; xcArrowPosition=1; xcFootTagSwitch=[1, 0, 0, 1, 0, 0, 0, 0]; //xcMods[1].order=1; xcMods[2].order=1; </script> <script language="javascript" src="xc2/script/xc2_inpage.js"></script> <script language="javascript"> //setRange("1", daysAfter(0),daysAfter(45)); setLoopWeek("1", "weekend", "", 1, 1, "Sat", "Sun"); </script> <!-- /Calendario Pou up --> <!--ajax-autocomplete --> <script type="text/javascript" src="ajax-autocomplete/jquery.js"></script> <script type='text/javascript' src='ajax-autocomplete/jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="ajax-autocomplete/jquery.autocomplete.css" /> <script type="text/javascript"> $().ready(function() { $("#apellidoynombre").autocomplete("planes_propios_sesiones_buscar_titulares.php", { width: 325, matchContains: true, //mustMatch: true, //minChars: 0, //multiple: true, //highlight: false, //multipleSeparator: ",", selectFirst: false }); $("#apellidoynombre").result(function(event, data, formatted) { $("#apellidoynombre").val(data[1]); $("#idtitularanterior").val(data[2]); }); }); </script> <!--ajax-autocomplete --> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onUnload="window.opener.location.reload();"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar" onSubmit="MM_validateForm('fecha','','R','importe','','RisNum');return document.MM_returnValue"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="4" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>SESIONES DEL PLAN PROPIO Nuevo</strong></td> </tr> </table></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td colspan="4" class="Estilo1"><span class="Estilo2">DATOS</span></td> </tr> <?php if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "formGuardar")) { ?> <tr valign="middle"> <td colspan="4" class="Estilo1">La sesi&oacute;n ha sido guardadada.</td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1"><input name="Cerrar" type="button" class="Estilo1" id="Cerrar" onClick="MM_goToURL('parent','planes_propios_sesiones.php?idplanpropio=<?php echo $_POST['idplanpropio'];?>');return document.MM_returnValue" value="Cerrar"></td> </tr> <?php } else { ?> <tr valign="middle"> <td width="16%" class="Estilo1"><strong>FECHA</strong></td> <td width="34%" class="Estilo1"><input name="fecha" type="text" class="Estilo1" id="fecha" value="<?php echo fecha('hoy'); ?>" onFocus="showCalendar('1',this,this,'','holder',0,10,1);" size="10" maxlength="10" /> <img src="img/calendario.gif" alt="Calendario" width="14" height="16" onClick="showCalendar('1',document.formGuardar.fecha,document.formGuardar.fecha,'','holder',0,10,1)"> <input name="idplanpropio" type="hidden" id="idplanpropio" value="<?php echo $_GET['idplanpropio']; ?>"></td> <td width="19%" class="Estilo1"><strong>TITULAR ANTERIOR</strong></td> <td width="31%" class="Estilo1"><input name="apellidoynombre" type="text" class="Estilo1" id="apellidoynombre" placeholder="<NAME>" value="" size="40" maxlength="255"> <input name="idtitularanterior" type="hidden" id="idtitularanterior"></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1"><input name="Guardar" type="submit" class="Estilo1" id="Guardar" value="Guardar"> </td> </tr> <?php } ?> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input type="hidden" name="MM_insert" value="formGuardar"> </form> </td> </tr> </table> </body> </html> <file_sep>/reportes_reserva2.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session session_start(); // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles session_unregister('MM_Username'); session_unregister('MM_UserGroup'); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php session_start(); $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); $colname_reserva = ""; if (isset($_POST['fechadesde'])) { $colname_reserva = fecha($_POST['fechadesde']); } $colname2_reserva = ""; if (isset($_POST['fechahasta'])) { $colname2_reserva = fecha($_POST['fechahasta']); } $colname3_reserva = ""; if (isset($_POST['idmodelo'])) { $colname3_reserva = $_POST['idmodelo']; } $colname4_reserva = ""; if (isset($_POST['idvendedor'])) { $colname4_reserva = $_POST['idvendedor']; } $colname5_reserva = ""; if (isset($_POST['idcolor'])) { $colname5_reserva = $_POST['idcolor']; } $colname6_reserva = ""; if (isset($_POST['todos'])) { $colname6_reserva = $_POST['todos']; } $colname7_reserva = ""; if (isset($_POST['cliente'])) { $colname7_reserva = $_POST['cliente']; } mysql_select_db($database_config, $config); if($colname6_reserva == 1) { if($row_usuario_sesion['idGrupo'] == 3) { $query_reserva = sprintf("SELECT slc_stocksud_reserva.fecha, slc_stocksud_reserva.cliente, slc_stocksud_reserva.programacionpendiente, slc_stocksud_reserva.comision2, slc_stocksud_modelo.modelo, slc_stocksud_usuario.usuario, slc_stocksud_reserva.idcolor1, slc_stocksud_reserva.idcolor2, slc_stocksud_reserva.idcolor3, slc_stocksud_reserva.importe, slc_solicitudreserva.grupo, slc_solicitudreserva.orden FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_usuario ON slc_stocksud_reserva.idvendedor=slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_modelo ON slc_stocksud_modelo.idmodelo = slc_stocksud_reserva.idmodelo LEFT JOIN slc_solicitudreserva ON slc_solicitudreserva.idSolicitud = slc_stocksud_reserva.idSolicitud WHERE slc_stocksud_reserva.asignado = 0 AND idvendedor = %s ORDER BY fecha", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } else { $query_reserva = "SELECT slc_stocksud_reserva.fecha, slc_stocksud_reserva.cliente, slc_stocksud_reserva.programacionpendiente, slc_stocksud_reserva.comision2, slc_stocksud_modelo.modelo, slc_stocksud_usuario.usuario, slc_stocksud_reserva.idcolor1, slc_stocksud_reserva.idcolor2, slc_stocksud_reserva.idcolor3, slc_stocksud_reserva.importe, slc_solicitudreserva.grupo, slc_solicitudreserva.orden FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_usuario ON slc_stocksud_reserva.idvendedor=slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_modelo ON slc_stocksud_modelo.idmodelo = slc_stocksud_reserva.idmodelo LEFT JOIN slc_solicitudreserva ON slc_solicitudreserva.idSolicitud = slc_stocksud_reserva.idSolicitud WHERE slc_stocksud_reserva.asignado = 0 ORDER BY fecha"; } } else { $query_reserva = "SELECT slc_stocksud_reserva.fecha, slc_stocksud_reserva.cliente, slc_stocksud_reserva.programacionpendiente, slc_stocksud_reserva.comision2, slc_stocksud_modelo.modelo, slc_stocksud_usuario.usuario, slc_stocksud_reserva.idcolor1, slc_stocksud_reserva.idcolor2, slc_stocksud_reserva.idcolor3, slc_stocksud_reserva.importe, slc_solicitudreserva.grupo, slc_solicitudreserva.orden FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_usuario ON slc_stocksud_reserva.idvendedor=slc_stocksud_usuario.idUsuario LEFT JOIN slc_stocksud_modelo ON slc_stocksud_modelo.idmodelo = slc_stocksud_reserva.idmodelo LEFT JOIN slc_solicitudreserva ON slc_solicitudreserva.idSolicitud = slc_stocksud_reserva.idSolicitud WHERE slc_stocksud_reserva.asignado = 0 "; if(($colname_reserva != "") && ($colname2_reserva != "")) { $query_reserva .= sprintf(" AND slc_stocksud_reserva.fecha BETWEEN %s AND %s ", GetSQLValueString($colname_reserva, "date"), GetSQLValueString($colname2_reserva, "date")); $where = 1; } if($row_usuario_sesion['idGrupo'] == 3) { if($where == 1){ $query_reserva .= sprintf(" AND slc_stocksud_reserva.idvendedor = %s", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } else { $query_reserva .= sprintf(" WHERE slc_stocksud_reserva.idvendedor = %s", GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); } } if($colname7_reserva != "") { if($where == 1){ $query_reserva .= sprintf(" AND slc_stocksud_reserva.cliente LIKE %s ", GetSQLValueString('%' . $colname7_reserva . '%', "text")); } else { $query_reserva .= sprintf(" WHERE slc_stocksud_reserva.cliente LIKE %s ", GetSQLValueString('%' . $colname7_reserva . '%', "text")); } } if($colname3_reserva != "0") { if($where == 1){ $query_reserva .= sprintf(" AND slc_stocksud_reserva.idmodelo = %s ", GetSQLValueString($colname3_reserva, "int")); } else { $query_reserva .= sprintf(" WHERE slc_stocksud_reserva.idmodelo = %s ", GetSQLValueString($colname3_reserva, "int")); } } if($colname4_reserva != "0") { if($where == 1){ $query_reserva .= sprintf(" AND slc_stocksud_reserva.idvendedor = %s ", GetSQLValueString($colname4_reserva, "int")); } else { $query_reserva .= sprintf(" WHERE slc_stocksud_reserva.idvendedor = %s ", GetSQLValueString($colname4_reserva, "int")); } } if($colname5_reserva != "0") { if($where == 1){ $query_reserva .= sprintf(" AND (slc_stocksud_reserva.idcolor1 = %s OR slc_stocksud_reserva.idcolor2 = %s OR slc_stocksud_reserva.idcolor3 = %s) ", GetSQLValueString($colname5_reserva, "int"), GetSQLValueString($colname5_reserva, "int"), GetSQLValueString($colname5_reserva, "int")); } else { $query_reserva .= sprintf(" WHERE (slc_stocksud_reserva.idcolor1 = %s OR slc_stocksud_reserva.idcolor2 = %s OR slc_stocksud_reserva.idcolor3 = %s) ", GetSQLValueString($colname5_reserva, "int"), GetSQLValueString($colname5_reserva, "int"), GetSQLValueString($colname5_reserva, "int")); } } $query_reserva .= " ORDER BY fecha"; } $reserva = mysql_query($query_reserva, $config) or die(mysql_error()); $row_reserva = mysql_fetch_assoc($reserva); $totalRows_reserva = mysql_num_rows($reserva); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } .Estilo3 {color: #FF0000} .Estilo11 {font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function MM_openBrWindow(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><BR> <table width="99%" height="82" border="1" align="center" cellpadding="4" cellspacing="0" bordercolor="#CCCCCC" id="ppal"> <tr class="Estilo1"> <td height="20" colspan="13" class="Estilo2"><div align="center">CONSULTA DE RESERVAS <?php if (isset($_POST['fechadesde']) && isset($_POST['fechahasta'])) { echo " DESDE " . $_POST['fechadesde'] . " HASTA " . $_POST['fechahasta']; } ?> </div></td> </tr> <tr class="Estilo1"> <td height="20" class="Estilo2"><span class="Estilo2">FECHA</span></td> <td><span class="Estilo2">MODELO</span></td> <td><span class="Estilo2">GRUPO</span></td> <td><span class="Estilo2">ORDEN</span></td> <td><span class="Estilo2">CLIENTE</span></td> <td><span class="Estilo2">VENDEDOR</span></td> <td><span class="Estilo2">PROGRAMACION PENDIENTE</span></td> <td><span class="Estilo2">PROGRAMACION</span></td> <td><span class="Estilo2">COLOR 1</span></td> <td><span class="Estilo2">COLOR 2</span></td> <td><span class="Estilo2">COLOR 3</span></td> <td><span class="Estilo2">IMPORTE</span></td> </tr> <?php do { ?> <?php $colname_color1 = $row_reserva['idcolor1']; mysql_select_db($database_config, $config); $query_color1 = sprintf("SELECT color FROM slc_stocksud_color WHERE idcolor = %s", GetSQLValueString($colname_color1, "int")); $color1 = mysql_query($query_color1, $config) or die(mysql_error()); $row_color1 = mysql_fetch_assoc($color1); $totalRows_color1 = mysql_num_rows($color1); $colname_color2 = $row_reserva['idcolor2']; mysql_select_db($database_config, $config); $query_color2 = sprintf("SELECT color FROM slc_stocksud_color WHERE idcolor = %s", GetSQLValueString($colname_color2, "int")); $color2 = mysql_query($query_color2, $config) or die(mysql_error()); $row_color2 = mysql_fetch_assoc($color2); $totalRows_color2 = mysql_num_rows($color2); $colname_color3 = $row_reserva['idcolor3']; mysql_select_db($database_config, $config); $query_color3 = sprintf("SELECT color FROM slc_stocksud_color WHERE idcolor = %s", GetSQLValueString($colname_color3, "int")); $color3 = mysql_query($query_color3, $config) or die(mysql_error()); $row_color3 = mysql_fetch_assoc($color3); $totalRows_color3 = mysql_num_rows($color3); ?> <tr class="Estilo1"> <td height="20"><?php echo fecha($row_reserva['fecha']); ?></td> <td><?php echo $row_reserva['modelo']; ?></td> <td><?php echo $row_reserva['grupo']; ?></td> <td><?php echo $row_reserva['orden']; ?></td> <td><?php echo $row_reserva['cliente']; ?></td> <td><?php echo $row_reserva['usuario']; ?></td> <td><?php echo $row_reserva['programacionpendiente']; ?></td> <td><?php echo $row_reserva['comision2']; ?></td> <td><?php echo $row_color1['color']; ?></td> <td><?php echo $row_color2['color']; ?></td> <td><?php echo $row_color3['color']; ?></td> <td colspan="2"><?php echo $row_reserva['importe']; ?></td> <?php } while ($row_reserva = mysql_fetch_assoc($reserva)); ?> </table> <blockquote class="Estilo1"> <div align="right">Cantidad de Registros <?php echo $totalRows_reserva ?></div> <div align="left"> <?php echo date('d-m-Y H:i');?> </div> <div align="right"><a href="#"><img src="img/imprimir.gif" alt="Imprimir" width="26" height="23" border="0" onClick="MM_callJS('window.print();')"></a>&nbsp;&nbsp;<form action="reporte_reserva_generar_excel.php" method="post" name="formexcel" target="_blank" id="formexcel"><a href="#"> <img src="img/xls.png" alt="Exportar a Excel" width="26" height="26" border="0" onClick="document.formexcel.submit(); "></a> <input name="query_reserva" type="hidden" id="query_reserva" value="<?php echo $query_reserva;?>"> </form></div> </blockquote> </body> </html> <?php mysql_free_result($reserva); mysql_free_result($usuario_sesion); mysql_free_result($color1); ?> <file_sep>/mysql2csv.php <?php /* mySQL2CSV functions - updated 2nd oct 2009::::::: These functions were patched together by <NAME> at blog.crondesign.com. There may be bugs/problems as these functions were not heavily tested. No copyright restrictions whatsoever - Use them however you see fit! Please let me know (<EMAIL>) if you improve on this stuff! //////////////////////////EXPORT CSV:::::::::::::::::::::::::: // EXPLANATION OF PARAMETERS WITH SAMPLE VALUES: //A standard mqSQL query that returns the data to be saved (REQUIRED) $values_query="SELECT addinID,'-1' AS instanceID, name, friendlyname, description, type, value, longvalue, dependantname, dependantvalue, editable, required, orderindex, defaultvalue FROM addins WHERE addinID='1';"; //Include column names in first row of CSV? If so, specify lookup query (good for excluding some fields from export) $col_names_query="SHOW COLUMNS FROM addins WHERE Field!='id' AND Field!='authorID' AND Field!='publishdate';"; //How many columns to include in CSV?(REQUIRED if $col_names_query=0) $col_count=14; //Use ',' for Excel but ';' is generally safer $fieldseparator=';'; //should the file be downloaded from browser or saved to the server? $download_file=0; //contains name of download file or (depending on $download_file) the path to save csv file without .csv file extension. $filename = "settings"; */ function exportCSV($values_query, $col_names_query=0, $col_count=1, $fieldseparator=';', $filename='exportedCSV', $download_file=0){ $lineseparator = "\n"; //GET COLUMNS:::::: /*if($col_names_query){ $result = mysql_query($col_names_query) or die($col_names_query."<br />".mysql_error()); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].$fieldseparator." "; $i++; } } $csv_output .= "\n"; }else{ $i=$col_count; }*/ $csv_output = $col_names_query; $i= $col_count; //GET VALUES::::::::::::::: $values = mysql_query($values_query) or die($values_query."<br />".mysql_error()); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= utf8_decode(trim($rowr[$j]).$fieldseparator); } //$csv_output=trim($csv_output,$fieldseparator." "); //trim trailing ; from end of line (disrupts import functions $csv_output .= $lineseparator; } //OUTPUT RESULTS:::::::::::::: if($download_file){ //DOWNLOAD: header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); echo $csv_output; }else{//SAVE TO SERVER: $fh = fopen($filename.'.csv', 'w') or die("can't open file"); fwrite($fh, $csv_output); fclose($fh); if(file_exists($filename.'.csv')){return (1);}else{return(0);} } } /*////////////////////////IMPORT CSV::::::::::::::::::::::::: //EXPLANATION OF PARAMETERS WITH SAMPLE VALUES: //existing table to import the CSV data to (REQUIRED) $import_to_table = "news"; //Use ',' for Excel but ';' is generally safer $fieldseparator=';'; //Name of the file on the server to import (use $_FILES["uploadfile"]["tmp_name"] for uploaded file) (REQUIRED) $importfilename = "newnews.csv"; // 1 if the first row of your CSV contains column names. 0 if it does not. $has_field_names = 1; //Merge existing rows with duplicates? (CSV file must contain at least one index for this to work) $merge_on_duplicate = 1; //offset the imported values if first column in sql table is an auto increment column (auto ID number). Should only be used with $has_field_names = 0 $skip_first_col = 0; //should the csv file be removed from the server after import? $delete_after_import=1; //save all generated queries to a file after import? to what filename? $outputfile="output.sql"; */ function importCSV($importfilename, $fieldseparator=';', $import_to_table, $has_field_names=0, $merge_on_duplicate=1, $skip_first_col=1, $delete_after_import=1, $outputfile=0){ $lineseparator = "\n"; if(!file_exists($importfilename)) { echo "ERROR: File not found. Make sure you specified the correct path.\n"; exit; } $file = fopen($importfilename,"r"); if(!$file) { echo "ERROR: opening data file.\n"; exit; } $size = filesize($importfilename); if(!$size) { echo "ERROR: File is empty.\n"; exit; } $csvcontent = fread($file,$size); fclose($file); $csvcontent=trim($csvcontent,$lineseparator); $lines = 0; $queries = ""; $linearray = array(); $fieldnames= ""; foreach(split($lineseparator,$csvcontent) as $line) { $lines++; $line = trim($line," \t"); $line = rtrim($line,$fieldseparator); $line = str_replace("\r","",$line); $line = str_replace("'","\'",$line); //escapes the special character. remove it if entries are already escaped in the csv file $linearray = explode($fieldseparator,$line); array_walk($linearray, 'trim_value'); //trims the array $linemysql=substr(implode("','",$linearray),0,-3); if($has_field_names && $lines==1){//1ST ROW: $fieldnames="(`".substr(implode("`,`",$linearray),0,-2).")"; if($merge_on_duplicate){ //get index of distinct column name $fieldnamesarray=$linearray; //save column names for all future queries } }else{//ALL OTHER ROWS: if($merge_on_duplicate){ if(!$fieldnamesarray){ //if field names are not in CSV, get them from table: $fieldnamesarray=mysql_fetch_array(mysql_query("SHOW COLUMNS FROM $import_to_table;")); } $v=""; foreach($linearray as $index => $val){ if($fieldnamesarray[$index]){ if($skip_first_col && $index==0){}//If not skipping the first column: else{$v.="`".trim($fieldnamesarray[$index])."`='".$val."',";} //add this field=value pair to the $updatequery statement } } $v=trim($v,','); $updatequery= "ON duplicate KEY UPDATE $v"; }else{ $updatequery=""; } if($skip_first_col){ $query= "INSERT INTO $import_to_table $fieldnames VALUES('','$linemysql') $updatequery;"; }else{ $query = "INSERT INTO $import_to_table $fieldnames VALUES('$linemysql') $updatequery;"; } $queries .= $query . "\n"; mysql_query($query) or die($query.'<br />'.mysql_error()); } } //echo "<br /><br />",$queries; //for testing if($outputfile){ //save queries to a file: if(!is_writable($outputfile)) { echo "File is not writable, check permissions.\n"; }else{ $file2 = fopen($outputfile,"w"); if(!$file2) { echo "Error writing to the output file.\n"; }else{ fwrite($file2,$queries); fclose($file2); } } } if($delete_after_import){@unlink($importfilename);} return (1); } //internal function: function trim_value(&$value){ $value = trim($value); } ?><file_sep>/turnos_asignar_guardar.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } ?> <?php require("class.phpmailer.php"); if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET["id"])) && ($_GET["id"] != "")) { $campos = explode('-', $_GET['id']); mysql_select_db($database_config, $config); $updateSQL = sprintf("UPDATE slc_stocksud_turno SET id=%s, stockreserva=%s WHERE idturno =%s", GetSQLValueString($campos[0], "int"), GetSQLValueString($campos[1], "int"), GetSQLValueString($campos[2], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); if($campos[1] == '1'){ $colname_stock =$campos[0]; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT slc_stock_cliente.apellidoynombre, slc_stock_cliente.email, slc_stocksud_usuario.mail, slc_stocksud_banco.banco, slc_stocksud_banco.documentacion FROM slc_stocksud_stock LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_stock.idvendedor LEFT JOIN slc_stock_cliente ON slc_stocksud_stock.idCliente = slc_stock_cliente.idCliente LEFT JOIN slc_stocksud_banco ON slc_stocksud_stock.idbanco = slc_stocksud_banco.idbanco WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); $colname_turnosel = $campos[2]; mysql_select_db($database_config, $config); $query_turnosel = sprintf("SELECT * FROM slc_stocksud_turno WHERE idturno = %s", GetSQLValueString($colname_turnosel, "int")); $turnosel = mysql_query($query_turnosel, $config) or die(mysql_error()); $row_turnosel = mysql_fetch_assoc($turnosel); $totalRows_turnosel = mysql_num_rows($turnosel); $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 12px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<p align="center"><img src="http://172.16.17.32/intranet/entregas/fotos/yacopinisud.png" width="640" height="137" /></p>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= $row_stock['apellidoynombre']; $cuerpo .= ': <br><br> Le recordamos que su turno para gestionar el cr&eacute;dito es el '; $cuerpo .= fecha($row_turnosel['fechahora'],0); $cuerpo .= '<br><br>A continuaci&oacute;n le detallamos la documentaci&oacute;n que deber&aacute; presentar:<br><br>'; $cuerpo .= $row_stock['documentacion']; $cuerpo .= '<br><br><strong>Territorio Yacopini</strong>'; $cuerpo .= '<br>0810 666 1033'; $cuerpo .= '<br><a href="http:\\\www.territorioyacopini.com.ar">www.territorioyacopini.com.ar </a>'; $cuerpo .= '<br>San Mart&iacute;n Sur 600 Godoy Cruz Mendoza</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $mail->AddAddress($row_stock['email']); $mail->Subject = 'TURNO PARA GESTIONAR CREDITO'; $mail->Body = $cuerpo; $mail->Send(); } else { $colname_stock =$campos[0]; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT slc_stocksud_usuario.mail, slc_stocksud_banco.banco, slc_stocksud_banco.documentacion FROM slc_stocksud_reserva LEFT JOIN slc_stocksud_usuario ON slc_stocksud_usuario.idUsuario = slc_stocksud_reserva.idvendedor LEFT JOIN slc_stocksud_banco ON slc_stocksud_reserva.idbanco = slc_stocksud_banco.idbanco WHERE idreserva = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 12px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; $cuerpo .= '<p align="center"><img src="http://188.138.106.137/intranet/entregas/fotos/yacopinisud.png" width="640" height="137" /></p>'; $cuerpo .= '<div class="Estilo1">'; $cuerpo .= $row_stock['apellidoynombre']; $cuerpo .= ': <br><br> Le recordamos que su turno para gestionar el cr&eacute;dito es el'; $cuerpo .= fecha($row_turnosel['fechahora'],0); $cuerpo .= '<br><br>A continuaci&oacute;n le detallamos la documentaci&oacute; que deber&aacute; presentar:<br><br>'; $cuerpo .= $row_stock['documentacion']; $cuerpo .= '<br><br><strong>Territorio Yacopini</strong>'; $cuerpo .= '<br>0810 666 1033'; $cuerpo .= '<br><a href="http:\\\www.territorioyacopini.com.ar">www.territorioyacopini.com.ar </a>'; $cuerpo .= '<br>San Mart&iacute;n Sur 600 Godoy Cruz Mendoza</div>'; $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "mail.yacopini.com.ar"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>$"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName = $FromName; $mail->From = $From; $mail->AddAddress($row_stock['mail']); $mail->AddAddress($row_stock['email']); $mail->Subject = 'TURNO PARA GESTIONAR CREDITO '; $mail->Body = $cuerpo; $mail->Send(); } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script> function CloseWin(){ window.opener.location.reload(); window.close(); } </script> </head> <body onLoad="CloseWin();"> </body> <file_sep>/comisiones_escalas_editar.php <?php require_once('Connections/config.php'); ?> <?php require_once('funciones.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_registro = "-1"; if (isset($_GET['id'])) { $colname_registro = $_GET['id']; } mysql_select_db($database_config, $config); $query_registro = sprintf("SELECT * FROM slc_comision_vw_escalas WHERE id = %s", GetSQLValueString($colname_registro, "int")); $registro = mysql_query($query_registro, $config) or die(mysql_error()); $row_registro = mysql_fetch_assoc($registro); $totalRows_registro = mysql_num_rows($registro); if(!isset($_POST['id'])){ $colname_registros = "-1"; if (isset($_GET['id'])) { $colname_registros = $_GET['id']; } mysql_select_db($database_config, $config); $query_registros = sprintf("SELECT slc_comision_vw_variables.id, slc_comision_vw_variables.nombre FROM slc_comision_vw_escala_variable LEFT JOIN slc_comision_vw_variables ON slc_comision_vw_variables.id = slc_comision_vw_escala_variable.idvariable WHERE idescala = %s", GetSQLValueString($colname_registros, "int")); $registros = mysql_query($query_registros, $config) or die(mysql_error()); $row_registros = mysql_fetch_assoc($registros); $totalRows_registros = mysql_num_rows($registros); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; if(f.nombre.value == ''){ alert("Debe ingresar el nombre"); f.nombre.focus; return (0); } if(f.vigenciadesde.value == ''){ alert("Debe ingresar la vigencia"); f.vigenciadesde.focus; return (0); } f.target = '_parent'; f.method = 'POST'; f.action = 'comisiones_escalas_guardar.php'; f.submit(); } function agregarvariable() { f=document.formGuardar; if(f.idvariable_agregar.value == ''){ alert("Debe seleccionar una variable."); f.idvariable_agregar.focus; return (0); } f.target = '_parent'; f.method = 'POST'; f.action = 'comisiones_escalas_editar.php'; f.submit(); } //--> </script> <!-- Calendario Pou up --> <link rel=stylesheet href="xc2/css/xc2_default.css" type="text/css"> <style type="text/css"> .weekend { font-family:verdana; font-size:11px; line-height:14px; width:23px; text-align:center; color:#cc0000; background-color:#f0f0f0; border:1px solid #f0f0f0; padding:1px; cursor:pointer; } #rojo { color: #F00; } </style> <script language="javascript" src="xc2/config/xc2_default.js"></script> <script language="javascript"> xcDateFormat="dd-mm-yyyy"; xcArrowPosition=1; xcFootTagSwitch=[1, 0, 0, 1, 0, 0, 0, 0]; //xcMods[1].order=1; xcMods[2].order=1; </script> <script language="javascript" src="xc2/script/xc2_inpage.js"></script> <script language="javascript"> //setRange("1", daysAfter(0),daysAfter(45)); setLoopWeek("1", "weekend", "", 1, 1, "Sat", "Sun"); </script> <!-- /Calendario Pou up --> <!--ajax-autocomplete --> <script type="text/javascript" src="ajax-autocomplete/jquery.js"></script> <script type='text/javascript' src='ajax-autocomplete/jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="ajax-autocomplete/jquery.autocomplete.css" /> <script type="text/javascript"> $().ready(function() { $("#nombre_agregar").autocomplete("comisiones_buscar_variable.php", { width: 325, matchContains: true, //mustMatch: true, //minChars: 0, //multiple: true, //highlight: false, //multipleSeparator: ",", selectFirst: false }); $("#nombre_agregar").result(function(event, data, formatted) { $("#nombre_agregar2").val(data[1]); $("#idvariable_agregar").val(data[2]); }); }); </script> <!--ajax-autocomplete --> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="4" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>ESCALAS DE COMISIONES Modificar </strong></td> </tr> </table></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="4" class="Estilo1"><span class="Estilo2">DATOS DE LA ESCALA DE COMISI&Oacute;N</span></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Nombre</strong></td> <td class="Estilo1"><input name="nombre" type="text" class="Estilo1" id="nombre" value="<?php if(isset($_POST['nombre'])) { echo $_POST['nombre']; } else { echo $row_registro['nombre'];} ?>" size="50" maxlength="100"> <input name="id" type="hidden" id="id" value="<?php if(isset($_POST['id'])) { echo $_POST['id']; } else {echo $row_registro['id'];} ?>"></td> <td class="Estilo1"><strong>Vigencia desde</strong></td> <td class="Estilo1"><input name="vigenciadesde" type="text" class="Estilo1" id="vigenciadesde" onFocus="showCalendar('1',this,this,'','holder',0,10,1);" value="<?php if(isset($_POST['vigenciadesde'])) { echo $_POST['vigenciadesde']; } else { echo fecha($row_registro['vigenciadesde']);} ?>" size="10" maxlength="10" /> <img src="img/calendario.gif" alt="Calendario" width="14" height="16" onClick="showCalendar('1',document.formGuardar.vigenciadesde,document.formGuardar.vigenciadesde,'','holder',0,10,1)"></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td height="20" colspan="4" class="Estilo1"><span class="Estilo2">VARIABLES DE LA ESCALA DE COMISI&Oacute;N</span></td> </tr> <tr valign="middle"> <td colspan="4" class="Estilo1"> <table width="100%" border="0" cellpadding="4"> <tbody> <tr> <td><strong><span class="Estilo1">Nombre</span></strong></td> <td>&nbsp;</td> </tr> <tr> <td><input name="nombre_agregar" type="text" class="Estilo1" id="nombre_agregar" size="50" maxlength="100"> <input type="hidden" name="idvariable_agregar" id="idvariable_agregar"> <input type="hidden" name="nombre_agregar2" id="nombre_agregar2"></td> <td><input name="btnagregar" type="button" class="Estilo1" id="btnagregar" value="Agregar" onClick="agregarvariable()"> <input name="variableborrar" type="hidden" id="variableborrar"></td> </tr> <?php if (isset($_POST['variable_id']) && $_POST['variable_id']!='') { $variable_id = $_POST['variable_id']; $variable_nombre = $_POST['variable_nombre']; } if (isset($_POST['idvariable_agregar']) && $_POST['idvariable_agregar']!='') { $variable_id[] = $_POST['idvariable_agregar']; $variable_nombre[] = $_POST['nombre_agregar2']; } for ($i=0;$i<count($variable_nombre);$i++) { if(($_POST['variableborrar'] == '') || ($_POST['variableborrar'] != $i)) { ?> <tr> <td><input name="variable_nombre[]" type="text" class="Estilo1" id="variable_nombre[]" value="<?php echo $variable_nombre[$i];?>" size="50" maxlength="100"> <input type="hidden" name="variable_id[]" id="variable_id[]" value="<?php echo $variable_id[$i];?>" ></td> <td><input name="btnborrar" type="button" class="Estilo1" id="btnborrar" value="Borrar" onClick="document.formGuardar.variableborrar.value='<?php echo $i;?>'; document.formGuardar.submit();"></td> </tr> <?php } ?> <?php } ?> <?php if ($totalRows_registros > 0) { // Show if recordset not empty ?> <?php $i=0;?> <?php do { ?> <tr> <td><input name="variable_nombre[]" type="text" class="Estilo1" id="variable_nombre[]" value="<?php echo $row_registros['nombre']; ?>" size="50" maxlength="100"> <input type="hidden" name="variable_id[]" id="variable_id[]" value="<?php echo $row_registros['id']; ?>" ></td> <td><input name="btnborrar" type="button" class="Estilo1" id="btnborrar" value="Borrar" onClick="document.formGuardar.variableborrar.value='<?php echo $i;?>'; document.formGuardar.submit();"></td> </tr> <?php $i++;?> <?php } while ($row_registros = mysql_fetch_assoc($registros)); ?> <?php } // Show if recordset not empty ?> </td> </tbody> </table> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1"><input name="Guardar" type="button" class="Estilo1" id="Guardar" value="Guardar" onClick="guardar();"> &nbsp;&nbsp; <input name="Cancelar" type="button" class="Estilo1" id="Cancelar" onClick="window.close()" value="Cancelar"></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input name="MM_update" type="hidden" id="MM_update" value="formGuardar"> </form> </div></td> </tr> </table> </body> </html> <?php mysql_free_result($registro); mysql_free_result($registros); mysql_free_result($consultores); ?> <file_sep>/funciones.php <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } ?><file_sep>/cron_quitar_reservas.php <?php require_once('Connections/config.php'); ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } function n_dias($fecha_desde,$fecha_hasta) { $dias= (strtotime($fecha_desde)-strtotime($fecha_hasta))/86400; $dias = abs($dias); $dias = floor($dias); return $dias; } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_config, $config); $query_reservas = sprintf("SELECT slc_stocksud_stock.idstock, slc_stocksud_stock.periodoreserva, slc_stocksud_stock.fechareserva FROM slc_stocksud_stock WHERE slc_stocksud_stock.periodoreserva > 0 AND slc_stocksud_stock.reserva = 1 AND ( slc_stocksud_stock.fechareserva IS NOT NULL AND slc_stocksud_stock.fechareserva <> '' AND slc_stocksud_stock.fechareserva <> '0000-00-00')"); $reservas = mysql_query($query_reservas, $config) or die(mysql_error()); $row_reservas = mysql_fetch_assoc($reservas); $totalRows_reservas = mysql_num_rows($reservas); if($totalRows_reservas > 0){ do { $cantdias = n_dias(date("d-m-Y"), fecha($row_reservas['fechareserva'])) ; if($cantdias > $row_reservas['periodoreserva'] ){ $updateSQL = sprintf("UPDATE slc_stocksud_stock SET fechareserva=%s, reserva=%s, periodoreserva=%s WHERE idstock=%s", GetSQLValueString("0000-00-00", "date"), GetSQLValueString('0', "int"), GetSQLValueString('0', "int"), GetSQLValueString($row_reservas['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } } while ($row_reservas = mysql_fetch_assoc($reservas)); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>YACOPINI</title> </head> <body> </body> </html> <?php mysql_free_result($reservas); ?> <file_sep>/stock_actualizarBORRAR.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { $colname_cliente = "-1"; if (isset($_POST['dni']) && ($_POST['dni'] != '')) { $colname_cliente = $_POST['dni']; } mysql_select_db($database_config, $config); $query_cliente = sprintf("SELECT * FROM slc_stock_cliente WHERE dni = %s", GetSQLValueString($colname_cliente, "text")); $cliente = mysql_query($query_cliente, $config) or die(mysql_error()); $row_cliente = mysql_fetch_assoc($cliente); $totalRows_cliente = mysql_num_rows($cliente); if (($totalRows_cliente == 0) && (isset($_POST['dni'])) && ($_POST['dni'] != '')) { $insertSQL = sprintf("INSERT INTO slc_stock_cliente (dni, apellidoynombre) VALUES (%s, %s)", GetSQLValueString($_POST['dni'], "text"), GetSQLValueString($_POST['apellidoynombre'], "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idCliente = mysql_insert_id($config); } elseif (isset($_POST['idCliente'])) { $idCliente = $_POST['idCliente']; } else { $idCliente = 0; } if(($idCliente != $_POST['idClienteanterior']) && ($idCliente != 0)) { $insertSQL = sprintf("INSERT INTO slc_stocksud_asignacion (idUsuario, idstock, fechahora) VALUES (%s, %s, %s)", GetSQLValueString($_POST['idUsuario'], "int"), GetSQLValueString($_POST['idstock'], "int"), GetSQLValueString($_POST['fechahora'], "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } $total = $_POST['precioventa'] + $_POST['intereses'] + $_POST['accesorios']; $deuda = $total - $_POST['pagado']; $updateSQL = sprintf("UPDATE slc_stocksud_stock SET idCliente=%s, fechareserva=%s, fechasolicitud=%s, fechaestimadaentrega=%s, precioventa=%s, intereses=%s, accesorios=%s, idvendedor=%s, idbanco=%s, idcuota=%s, pagado=%s, observaciones=%s, promocion=%s, usadopatente=%s, usadopreciodetoma=%s, usadofechaventa=%s, usadoprecioventa=%s, usadocliente=%s, usadoidvendedor=%s, usadocomision=%s, total=%s, deuda=%s WHERE idstock=%s", GetSQLValueString($idCliente, "int"), GetSQLValueString(fecha($_POST['fechareserva']), "date"), GetSQLValueString(fecha($_POST['fechasolicitud']), "date"), GetSQLValueString(fecha($_POST['fechaestimadaentrega']), "date"), GetSQLValueString($_POST['precioventa'], "double"), GetSQLValueString($_POST['intereses'], "double"), GetSQLValueString($_POST['accesorios'], "double"), GetSQLValueString($_POST['idvendedor'], "int"), GetSQLValueString($_POST['idbanco'], "int"), GetSQLValueString($_POST['idcuota'], "int"), GetSQLValueString($_POST['pagado'], "double"), GetSQLValueString($_POST['observaciones'], "text"), GetSQLValueString($_POST['promocion'], "text"), GetSQLValueString($_POST['usadopatente'], "text"), GetSQLValueString($_POST['usadopreciodetoma'], "double"), GetSQLValueString(fecha($_POST['usadofechaventa']), "date"), GetSQLValueString($_POST['usadoprecioventa'], "double"), GetSQLValueString($_POST['usadocliente'], "text"), GetSQLValueString($_POST['usadoidvendedor'], "int"), GetSQLValueString($_POST['usadocomision'], "text"), GetSQLValueString($total, "double"), GetSQLValueString($deuda, "double"), GetSQLValueString($_POST['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); header("location: stock_editar.php?idstock=" . $_POST['idstock']); } ?><file_sep>/listas_precios_guardar.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "formGuardar")) { $colname_lista_precio = "-1"; if (isset($_POST['lista'])) { $colname_lista_precio = $_POST['lista']; } $colname2_lista_precio = "-1"; if (isset($_POST['modelo'])) { $colname2_lista_precio = $_POST['modelo']; } mysql_select_db($database_config, $config); $query_lista_precio = sprintf("SELECT * FROM slc_stocksud_listaprecio WHERE lista LIKE %s AND modelo LIKE %s", GetSQLValueString($colname_lista_precio, "text"), GetSQLValueString($colname2_lista_precio, "text")); $lista_precio = mysql_query($query_lista_precio, $config) or die(mysql_error()); $row_lista_precio = mysql_fetch_assoc($lista_precio); $totalRows_lista_precio = mysql_num_rows($lista_precio); if($totalRows_lista_precio == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_listaprecio (lista, modelo, fechavigencia, preciolista, gastosentrega, gastospatentamiento, gastosretiro, derechoadjudicacion, iva, bonificacionweb, bonificacionsalon, precioagencia) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['lista'], "text"), GetSQLValueString($_POST['modelo'], "text"), GetSQLValueString(fecha($_POST['fechavigencia']), "date"), GetSQLValueString($_POST['preciolista'], "double"), GetSQLValueString($_POST['gastosentrega'], "double"), GetSQLValueString($_POST['gastospatentamiento'], "double"), GetSQLValueString($_POST['gastosretiro'], "double"), GetSQLValueString($_POST['derechoadjudicacion'], "double"), GetSQLValueString($_POST['iva'], "float"), GetSQLValueString($_POST['bonificacionweb'], "double"), GetSQLValueString($_POST['bonificacionsalon'], "double"), GetSQLValueString($_POST['precioagencia'], "double")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "formGuardar")) { $updateSQL = sprintf("UPDATE slc_stocksud_listaprecio SET preciolista=%s, gastosentrega=%s, gastospatentamiento=%s, gastosretiro=%s, derechoadjudicacion=%s, iva=%s, bonificacionweb=%s, bonificacionsalon=%s, precioagencia=%s WHERE idlista=%s", GetSQLValueString($_POST['preciolista'], "double"), GetSQLValueString($_POST['gastosentrega'], "double"), GetSQLValueString($_POST['gastospatentamiento'], "double"), GetSQLValueString($_POST['gastosretiro'], "double"), GetSQLValueString($_POST['derechoadjudicacion'], "double"), GetSQLValueString($_POST['iva'], "float"), GetSQLValueString($_POST['bonificacionweb'], "double"), GetSQLValueString($_POST['bonificacionsalon'], "double"), GetSQLValueString($_POST['precioagencia'], "double"), GetSQLValueString($_POST['idlista'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } if ((isset($_POST["MM_delete"])) && ($_POST["MM_delete"] == "formGuardar")) { $deleteSQL = sprintf("DELETE FROM slc_stocksud_listaprecio WHERE idlista=%s", GetSQLValueString($_POST['idlista'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script> function CloseWin(){ window.opener.location.reload(); window.close(); } </script> </head> <body onLoad="CloseWin();"> </body><file_sep>/usuarios_editar.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario = "-1"; if (isset($_GET['idUsuario'])) { $colname_usuario = $_GET['idUsuario']; } mysql_select_db($database_config, $config); $query_usuario = sprintf("SELECT * FROM slc_stocksud_usuario WHERE idUsuario = %s", GetSQLValueString($colname_usuario, "int")); $usuario = mysql_query($query_usuario, $config) or die(mysql_error()); $row_usuario = mysql_fetch_assoc($usuario); $totalRows_usuario = mysql_num_rows($usuario); mysql_select_db($database_config, $config); $query_consultores = "SELECT * FROM slc_consultor ORDER BY consultor ASC"; $consultores = mysql_query($query_consultores, $config) or die(mysql_error()); $row_consultores = mysql_fetch_assoc($consultores); $totalRows_consultores = mysql_num_rows($consultores); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; if(f.usuario.value == ''){ alert("Debe ingresar el usuario"); f.usuario.focus; return (0); } f.target = '_parent'; f.method = 'POST'; f.action = 'usuarios_guardar.php'; f.submit(); } function mostrarconsultor() { f=document.formGuardar; if((f.idGrupo.value == '1') || (f.idGrupo.value == '2') || (f.idGrupo.value == '3')) { document.getElementById('idconsultor').style.display='block'; document.getElementById('labelconsultor').style.display='block'; } else { document.getElementById('idconsultor').style.display='none'; document.getElementById('labelconsultor').style.display='none'; f.idconsultor.value = ''; } } //--> </script> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onLoad="mostrarconsultor();"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="4" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>USUARIOS Modificar</strong></td> </tr> </table></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td width="16%" class="Estilo1"><span class="Estilo2">DATOS</span></td> <td width="34%" class="Estilo1">&nbsp; </td> <td width="19%" class="Estilo1">&nbsp;</td> <td width="31%" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Usuario</strong></td> <td class="Estilo1"><input name="usuario" type="text" class="Estilo1" id="usuario" value="<?php echo $row_usuario['usuario']; ?>" size="40" maxlength="50"> <input name="idUsuario" type="hidden" id="idUsuario" value="<?php echo $row_usuario['idUsuario']; ?>"></td> <td class="Estilo1"><strong>Clave</strong></td> <td class="Estilo1"><input name="clave" type="password" class="Estilo1" id="clave" size="40" maxlength="50"></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Grupo</strong></td> <td class="Estilo1"><select name="idGrupo" class="Estilo1" id="idGrupo" onChange="mostrarconsultor();"> <option value="1" selected <?php if (!(strcmp(1, $row_usuario['idGrupo']))) {echo "selected=\"selected\"";} ?>>Administrador</option> <option value="2" <?php if (!(strcmp(2, $row_usuario['idGrupo']))) {echo "selected=\"selected\"";} ?>>Gerente</option> <option value="3" <?php if (!(strcmp(3, $row_usuario['idGrupo']))) {echo "selected=\"selected\"";} ?>>Vendedor</option> <option value="4" <?php if (!(strcmp(4, $row_usuario['idGrupo']))) {echo "selected=\"selected\"";} ?>>Credito</option> </select></td> <td class="Estilo1"><strong>Nombre</strong></td> <td class="Estilo1"><input name="nombre" type="text" class="Estilo1" id="nombre" value="<?php echo $row_usuario['nombre']; ?>" size="40" maxlength="50"></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Mail</strong></td> <td class="Estilo1"><input name="mail" type="text" class="Estilo1" id="mail" value="<?php echo $row_usuario['mail']; ?>" size="50" maxlength="255"></td> <td class="Estilo1"><label id="labelconsultor"><strong>Consultor</strong></label></td> <td class="Estilo1"><select name="idconsultor" class="Estilo1" id="idconsultor"> <option value="" <?php if (!(strcmp("", $row_usuario['idconsultor']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_consultores['idConsultor']?>"<?php if (!(strcmp($row_consultores['idConsultor'], $row_usuario['idconsultor']))) {echo "selected=\"selected\"";} ?>><?php echo $row_consultores['consultor']?></option> <?php } while ($row_consultores = mysql_fetch_assoc($consultores)); $rows = mysql_num_rows($consultores); if($rows > 0) { mysql_data_seek($consultores, 0); $row_consultores = mysql_fetch_assoc($consultores); } ?> </select></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Consultor para usados</strong></td> <td class="Estilo1"><select name="idconsultorusado" class="Estilo1" id="idconsultorusado"> <option value="" <?php if (!(strcmp("", $row_usuario['idconsultorusado']))) {echo "selected=\"selected\"";} ?>></option> <?php do { ?> <option value="<?php echo $row_consultores['idConsultor']?>"<?php if (!(strcmp($row_consultores['idConsultor'], $row_usuario['idconsultorusado']))) {echo "selected=\"selected\"";} ?>><?php echo $row_consultores['consultor']?></option> <?php } while ($row_consultores = mysql_fetch_assoc($consultores)); $rows = mysql_num_rows($consultores); if($rows > 0) { mysql_data_seek($consultores, 0); $row_consultores = mysql_fetch_assoc($consultores); } ?> </select></td> <td class="Estilo1">&nbsp;</td> <td class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1"><input name="Guardar" type="button" class="Estilo1" id="Guardar" value="Guardar" onClick="guardar();"> &nbsp;&nbsp; <input name="Cancelar" type="button" class="Estilo1" id="Cancelar" onClick="window.close()" value="Cancelar"></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input type="hidden" name="MM_update" value="formGuardar"> </form> </div></td> </tr> </table> </body> </html> <?php mysql_free_result($usuario); ?> <file_sep>/stock_nofacturado_anular.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); if(isset($_POST['MM_update']) && ($_POST['MM_update'] == 'formGuardar')){ $mensaje = ''; $colname_stock = "-1"; if (isset($_POST['idstock'])) { $colname_stock = $_POST['idstock']; } mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT * FROM slc_stocksud_stocknofacturado WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if($row_stock['chasis'] != "") { $vin = $row_stock['chasis']; } else { $vin = $row_stock['comision2']; } $colname_entrega = $vin; mysql_select_db($database_config, $config); $query_entrega = sprintf("SELECT idEntrega, baja FROM slc_entrega WHERE VIN = %s", GetSQLValueString($colname_entrega, "text")); $entrega = mysql_query($query_entrega, $config) or die(mysql_error()); $row_entrega = mysql_fetch_assoc($entrega); $totalRows_entrega = mysql_num_rows($entrega); if($totalRows_entrega == 0) { $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET asignado=%s WHERE idSolicitud=%s", GetSQLValueString("0", "int"), GetSQLValueString($row_stock['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); if($Result1) { if($row_stock['fechareserva'] != '0000-00-00') { $fechareserva = $row_stock['fechareserva']; } else { $fechareserva = ''; } $insertSQL = sprintf("INSERT INTO slc_stocksud_anulado (chasis, modelo, color, idCliente, fechareserva, reserva, periodoreserva, fechasolicitud, fechaestimadaentrega, precioventa, intereses, accesorios, total, idvendedor, promocion, idbanco, idcuota, pagado, deuda, observaciones, comision, usadomodelo, usadopatente, usadopreciodetoma, usadofechaventa, usadoprecioventa, usadocliente, usadoidvendedor, usadocomision, idusuarioanula) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($row_stock['chasis'], "text"), GetSQLValueString($row_stock['modelo'], "text"), GetSQLValueString($row_stock['color'], "text"), GetSQLValueString($row_stock['idCliente'], "int"), GetSQLValueString($fechareserva, "date"), GetSQLValueString($row_stock['reserva'], "int"), GetSQLValueString($row_stock['periodoreserva'], "int"), GetSQLValueString($row_stock['fechasolicitud'], "date"), GetSQLValueString($row_stock['fechaestimadaentrega'], "date"), GetSQLValueString($row_stock['precioventa'], "double"), GetSQLValueString($row_stock['intereses'], "double"), GetSQLValueString($row_stock['accesorios'], "double"), GetSQLValueString($row_stock['total'], "double"), GetSQLValueString($row_stock['idvendedor'], "int"), GetSQLValueString($row_stock['promocion'], "text"), GetSQLValueString($row_stock['idbanco'], "int"), GetSQLValueString($row_stock['idcuota'], "int"), GetSQLValueString($row_stock['pagado'], "double"), GetSQLValueString($row_stock['deuda'], "double"), GetSQLValueString($row_stock['observaciones'], "text"), GetSQLValueString($row_stock['comision'], "text"), GetSQLValueString($row_stock['usadomodelo'], "text"), GetSQLValueString($row_stock['usadopatente'], "text"), GetSQLValueString($row_stock['usadopreciodetoma'], "double"), GetSQLValueString($row_stock['usadofechaventa'], "date"), GetSQLValueString($row_stock['usadoprecioventa'], "double"), GetSQLValueString($row_stock['usadocliente'], "text"), GetSQLValueString($row_stock['usadoidvendedor'], "int"), GetSQLValueString($row_stock['usadocomision'], "text"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_stocksud_stocknofacturado SET idSolicitud=%s,idCliente=%s, fechareserva=%s, fechasolicitud=%s, fechaestimadaentrega=%s, precioventa=%s, comision=%s, intereses=%s, accesorios=%s, idvendedor=%s, idbanco=%s, idcuota=%s, importesolicitado=%s, pagado=%s, observaciones=%s, idpromocion=%s, usadopatente=%s, usadopreciodetoma=%s, usadofechaventa=%s, usadoprecioventa=%s, usadocliente=%s, usadoidvendedor=%s, usadocomision=%s, usadomodelo=%s, total=%s, deuda=%s WHERE idstock=%s", GetSQLValueString(0, "int"), GetSQLValueString(0, "int"), GetSQLValueString('', "date"), GetSQLValueString('', "date"), GetSQLValueString('', "date"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString(0, "int"), GetSQLValueString(0, "int"), GetSQLValueString(0, "int"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString('', "text"), GetSQLValueString(0, "int"), GetSQLValueString('', "text"), GetSQLValueString(0, "double"), GetSQLValueString('', "date"), GetSQLValueString(0, "double"), GetSQLValueString('', "text"), GetSQLValueString(0, "int"), GetSQLValueString('', "text"), GetSQLValueString('', "text"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString($_POST['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } else { $mensaje = "No se puedo anular."; } } elseif(($totalRows_entrega > 0) && ($row_entrega['baja'] == '1')) { $updateSQL = sprintf("UPDATE slc_stocksud_reserva SET asignado=%s WHERE idSolicitud=%s", GetSQLValueString("0", "int"), GetSQLValueString($row_stock['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); if($Result1) { if($row_stock['fechareserva'] != '0000-00-00') { $fechareserva = $row_stock['fechareserva']; } else { $fechareserva = ''; } $insertSQL = sprintf("INSERT INTO slc_stocksud_anulado (chasis, modelo, color, idCliente, fechareserva, reserva, periodoreserva, fechasolicitud, fechaestimadaentrega, precioventa, intereses, accesorios, total, idvendedor, promocion, idbanco, idcuota, pagado, deuda, observaciones, comision, usadomodelo, usadopatente, usadopreciodetoma, usadofechaventa, usadoprecioventa, usadocliente, usadoidvendedor, usadocomision, idusuarioanula) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($row_stock['chasis'], "text"), GetSQLValueString($row_stock['modelo'], "text"), GetSQLValueString($row_stock['color'], "text"), GetSQLValueString($row_stock['idCliente'], "int"), GetSQLValueString($fechareserva, "date"), GetSQLValueString($row_stock['reserva'], "int"), GetSQLValueString($row_stock['periodoreserva'], "int"), GetSQLValueString($row_stock['fechasolicitud'], "date"), GetSQLValueString($row_stock['fechaestimadaentrega'], "date"), GetSQLValueString($row_stock['precioventa'], "double"), GetSQLValueString($row_stock['intereses'], "double"), GetSQLValueString($row_stock['accesorios'], "double"), GetSQLValueString($row_stock['total'], "double"), GetSQLValueString($row_stock['idvendedor'], "int"), GetSQLValueString($row_stock['promocion'], "text"), GetSQLValueString($row_stock['idbanco'], "int"), GetSQLValueString($row_stock['idcuota'], "int"), GetSQLValueString($row_stock['pagado'], "double"), GetSQLValueString($row_stock['deuda'], "double"), GetSQLValueString($row_stock['observaciones'], "text"), GetSQLValueString($row_stock['comision'], "text"), GetSQLValueString($row_stock['usadomodelo'], "text"), GetSQLValueString($row_stock['usadopatente'], "text"), GetSQLValueString($row_stock['usadopreciodetoma'], "double"), GetSQLValueString($row_stock['usadofechaventa'], "date"), GetSQLValueString($row_stock['usadoprecioventa'], "double"), GetSQLValueString($row_stock['usadocliente'], "text"), GetSQLValueString($row_stock['usadoidvendedor'], "int"), GetSQLValueString($row_stock['usadocomision'], "text"), GetSQLValueString($row_usuario_sesion['idUsuario'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_stocksud_stocknofacturado SET idSolicitud=%s,idCliente=%s, fechareserva=%s, fechasolicitud=%s, fechaestimadaentrega=%s, precioventa=%s, comision=%s, intereses=%s, accesorios=%s, idvendedor=%s, idbanco=%s, idcuota=%s, importesolicitado=%s, pagado=%s, observaciones=%s, idpromocion=%s, usadopatente=%s, usadopreciodetoma=%s, usadofechaventa=%s, usadoprecioventa=%s, usadocliente=%s, usadoidvendedor=%s, usadocomision=%s, usadomodelo=%s, total=%s, deuda=%s WHERE idstock=%s", GetSQLValueString(0, "int"), GetSQLValueString(0, "int"), GetSQLValueString('', "date"), GetSQLValueString('', "date"), GetSQLValueString('', "date"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString(0, "int"), GetSQLValueString(0, "int"), GetSQLValueString(0, "int"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString('', "text"), GetSQLValueString(0, "int"), GetSQLValueString('', "text"), GetSQLValueString(0, "double"), GetSQLValueString('', "date"), GetSQLValueString(0, "double"), GetSQLValueString('', "text"), GetSQLValueString(0, "int"), GetSQLValueString('', "text"), GetSQLValueString('', "text"), GetSQLValueString(0, "double"), GetSQLValueString(0, "double"), GetSQLValueString($_POST['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } else { $mensaje = "No se puedo anular."; } } else { $mensaje = "No se puede anular, deber primero anular la entrega."; } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; f.anular.value = 1; f.target = '_parent'; f.method = 'POST'; f.action = 'stock_nofacturado_anular.php'; f.submit(); } //--> </script> <script> function CloseWin(){ window.opener.location.reload(); window.close(); } </script> </head> <body <?php if((isset($_POST['MM_update']) && ($_POST['MM_update'] == 'formGuardar')) && ($mensaje == '')){ ?> onLoad="CloseWin();" <?php } ?> > <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>STOCK NO FACTURADO Anular</strong></td> </tr> </table></td> </tr> <?php if($mensaje != '') { ?> <tr valign="middle"> <td align="center" class="Estilo1"><?php echo $mensaje;?></td> </tr> <tr valign="middle"> <td align="center" class="Estilo1"><input name="Cerrar" type="button" class="Estilo1" id="Cerrar" onClick="window.close()" value="Cerrar"></td> </tr> <?php } else { ?> <tr valign="middle"> <td align="center" class="Estilo1"><input name="anular" type="hidden" id="anular"> <input name="idstock" type="hidden" id="idstock" value="<?php echo $_GET['idstock'];?>"> &iquest;Est&aacute; seguro que desea anular el item asignado al cliente <?php echo $_GET['cliente'];?>?</td> </tr> <tr valign="middle"> <td align="center" valign="middle" class="Estilo1"><input name="Si" type="button" class="Estilo1" id="Si" value="Si" onClick="guardar();"> &nbsp;&nbsp; <input name="No" type="button" class="Estilo1" id="No" onClick="window.close()" value="No"></td> </tr> <?php } ?> <tr valign="middle"> <td align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input name="MM_update" type="hidden" id="MM_update" value="formGuardar"> </form> </div></td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); ?> <file_sep>/reporte_objetivos_generar_excel.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session session_start(); // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles session_unregister('MM_Username'); session_unregister('MM_UserGroup'); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php session_start(); $MM_authorizedUsers = "1,2,3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if($fechaHora[1]){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idUsuario, idGrupo, nombre FROM slc_stock_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); mysql_select_db($database_config, $config); $query_objetivos = $_POST['query_objetivos']; $query_objetivos = str_replace("\'", "'", $query_objetivos); $objetivos = mysql_query($query_objetivos, $config) or die(mysql_error()); $row_objetivos = mysql_fetch_assoc($objetivos); $totalRows_objetivos = mysql_num_rows($objetivos); $template_1 = "reporte_objetivos_cabecera.inc"; $template_2 = "reporte_objetivos_pie.inc"; // Se abre y extrae la cabecera del XML if ($gestor = fopen($template_1, "r")){ $header = fread($gestor, filesize($template_1)); fclose($gestor); } // Se genera el contenido aņadiendo 10 filas $rows = ""; do { $colname_importefactura = $row_objetivos['modelo']; mysql_select_db($database_config, $config); $query_importefactura = sprintf("SELECT importefactcompra FROM slc_stock_stock WHERE modelo LIKE %s ORDER BY idstock DESC", GetSQLValueString("%" . $colname_importefactura . "%", "text")); $importefactura = mysql_query($query_importefactura, $config) or die(mysql_error()); $row_importefactura = mysql_fetch_assoc($importefactura); $totalRows_importefactura = mysql_num_rows($importefactura); $colname_facturado = $row_objetivos['modelo']; $colname2_facturado = $row_objetivos['mes']; $colname3_facturado = $row_objetivos['anio']; mysql_select_db($database_config, $config); $query_facturado = sprintf("SELECT COUNT(idstock) AS cantidad FROM slc_stock_stock WHERE slc_stock_stock.modelo LIKE %s AND slc_stock_stock.pedido = 'CONCESIONARIOS' AND slc_stock_stock.mes = %s AND slc_stock_stock.anio = %s", GetSQLValueString($colname_facturado, "text"), GetSQLValueString($colname2_facturado, "int"), GetSQLValueString($colname3_facturado, "int")); $facturado = mysql_query($query_facturado, $config) or die(mysql_error()); $row_facturado = mysql_fetch_assoc($facturado); $totalRows_facturado = mysql_num_rows($facturado); $diferencia = $row_objetivos['objetivo']-$row_facturado['cantidad']; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"Number\">".$row_objetivos['mes']."</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">".$row_objetivos['anio']."</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">".utf8_encode($row_objetivos['modelo'])."</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">".$row_objetivos['objetivo']."</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">".$row_facturado['cantidad']."</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">".$diferencia."</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">".number_format($row_importefactura['importefactcompra'],0)."</Data></Cell>"; $rows .= "</Row>"; } while ($row_objetivos = mysql_fetch_assoc($objetivos)); // Se abre y extrae el pie del XML if ($gestor = fopen($template_2, "r")){ $footer = fread($gestor, filesize($template_2)); fclose($gestor); } // Se juntan las partes resultantes $content = $header . $rows . $footer; // Se envia el archivo al navegador header ("Content-type: application/x-msexcel"); header ("Content-Disposition: attachment; filename=\"reporte_objetivos.xls\"" ); print $content; mysql_free_result($usuario_sesion); ?><file_sep>/cron_lista_precio.php <?php require_once('Connections/config.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $template_1 = "cron_lista_precio_cabecera.inc"; $template_2 = "cron_lista_precio_pie.inc"; if ($gestor = fopen($template_1, "r")){ $header = fread($gestor, filesize($template_1)); fclose($gestor); } $colname_registro = date("Y-m-d"); mysql_select_db($database_config, $config); $query_registro = sprintf("SELECT * FROM slc_stocksud_listaprecio WHERE fechavigencia <= %s ORDER BY fechavigencia DESC LIMIT 1", GetSQLValueString($colname_registro, "date")); $registro = mysql_query($query_registro, $config) or die(mysql_error()); $row_registro = mysql_fetch_assoc($registro); $totalRows_registro = mysql_num_rows($registro); $colname_registros = $row_registro['lista']; mysql_select_db($database_config, $config); $query_registros = sprintf("SELECT * FROM slc_stocksud_listaprecio WHERE lista LIKE %s ORDER BY modelo ASC", GetSQLValueString($colname_registros, "date")); $registros = mysql_query($query_registros, $config) or die(mysql_error()); $row_registros = mysql_fetch_assoc($registros); $totalRows_registros = mysql_num_rows($registros); $rows = ""; if ($totalRows_registros > 0) { // Show if recordset not empty do { $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['preciolista'] . "</Data></Cell>"; $rows .= "</Row>"; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . 'gastos de entrega ' . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['gastosentrega'] . "</Data></Cell>"; $rows .= "</Row>"; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . 'gastos de patentamiento ' . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['gastospatentamiento'] . "</Data></Cell>"; $rows .= "</Row>"; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . 'gastos de retiro ' . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['gastosretiro'] . "</Data></Cell>"; $rows .= "</Row>"; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . 'derecho de adjudicación ' . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['derechoadjudicacion'] . "</Data></Cell>"; $rows .= "</Row>"; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . 'bonificación web ' . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['bonificacionweb'] . "</Data></Cell>"; $rows .= "</Row>"; $rows .= "<Row>\n"; $rows .= "<Cell><Data ss:Type=\"String\">" . $row_registros['idlista'] . "-" . $row_registros['lista'] . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"String\">" . 'bonificación ' . utf8_encode($row_registros['modelo']) . "</Data></Cell>"; $rows .= "<Cell><Data ss:Type=\"Number\">" . $row_registros['bonificacionsalon'] . "</Data></Cell>"; $rows .= "</Row>"; } while ($row_registros = mysql_fetch_assoc($registros)); } // Show if recordset not empty if ($gestor = fopen($template_2, "r")){ $footer = fread($gestor, filesize($template_2)); fclose($gestor); } $content = $header . $rows . $footer; file_put_contents("vw - catalogo de productos.xls", $content); ?> <?php mysql_free_result($registros); ?> <file_sep>/modelos_importador.php <?php require_once('Connections/config.php'); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); ?> <?php $mensaje = ""; if ((isset($_POST["Importar"])) && ($_POST["Importar"] == "Importar")) { if($_FILES['pathArchivo']['name']!=''){ if($_FILES['pathArchivo']['size']){ $type = explode(".", $_FILES['pathArchivo']['name']); if($type[1] == 'csv'){ $fp = fopen ($_FILES['pathArchivo']['tmp_name'],"r"); if ($fp != false) { if(count(fgetcsv($fp,1000,',')) > 1) { $separador = ','; } elseif(count(fgetcsv($fp,1000,';')) > 1) { $separador = ';'; } } fclose ($fp); $fp = fopen ($_FILES['pathArchivo']['tmp_name'],"r"); if ($fp != false) { if( !ini_get('safe_mode') ){ set_time_limit(90); } $estableceri = 0; while ($data = fgetcsv ($fp, 1000, $separador)) { $i = 0; if($estableceri == 0) { foreach($data as $row) { switch (trim(strtolower($row))) { case 'version': $iversion = $i; break; case 'familia': $ifamilia = $i; break; case 'subfamilia': $isubfamilia = $i; break; case 'puerta': $ipuerta = $i; break; case 'modelo': $imodelo = $i; break; case 'catalogo': $icatalogo = $i; break; } $i++ ; } $estableceri = 1; } else { $pr = explode(" ", $data[$icatalogo]); array_multisort($pr) ; $prsel = trim(implode(' ',$pr)); for($k=0; $k<count($pr); $k++){ if(trim(trim($pr[$k])) != '') { mysql_select_db($database_config, $config); $query_pr2 = sprintf("SELECT pr FROM slc_stocksud_pr WHERE pr = %s ", GetSQLValueString(trim($pr[$k]), "text")); $pr2 = mysql_query($query_pr2, $config) or die(mysql_error()); $row_pr2 = mysql_fetch_assoc($pr2); $totalRows_pr2 = mysql_num_rows($pr2); if($totalRows_pr2 == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_pr (pr) VALUES (%s)", GetSQLValueString(trim($pr[$k]), "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $mensajeprimp .= trim($pr[$k]) . ", "; } else { $mensajeprnoimp .= trim($pr[$k]) . ", "; } } } mysql_select_db($database_config, $config); $query_version = sprintf("SELECT * FROM slc_stocksud_version WHERE version = %s", GetSQLValueString($data[$iversion], "text")); $version = mysql_query($query_version, $config) or die(mysql_error()); $row_version = mysql_fetch_assoc($version); $totalRows_version = mysql_num_rows($version); if($totalRows_version == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_version (version) VALUES (%s)", GetSQLValueString(trim($data[$iversion]), "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $mensajeversionimp .= $data[$iversion] . ", "; } else { $mensajeversionnoimp .= $data[$iversion] . ", "; } $colname_familia = trim($data[$ifamilia]); $query_familia = sprintf("SELECT idfamilia FROM slc_stocksud_familia WHERE familia LIKE TRIM(%s)", GetSQLValueString($colname_familia, "text")); $familia = mysql_query($query_familia, $config) or die(mysql_error()); $row_familia = mysql_fetch_assoc($familia); $totalRows_familia = mysql_num_rows($familia); $colname_subfamilia = trim($data[$isubfamilia]); $query_subfamilia = sprintf("SELECT idsubfamilia FROM slc_stocksud_subfamilia WHERE subfamilia LIKE TRIM(%s)", GetSQLValueString($colname_subfamilia, "text")); $subfamilia = mysql_query($query_subfamilia, $config) or die(mysql_error()); $row_subfamilia = mysql_fetch_assoc($subfamilia); $totalRows_subfamilia = mysql_num_rows($subfamilia); $colname_puerta = $data[$ipuerta]; $query_puerta = sprintf("SELECT idpuerta FROM slc_stocksud_puerta WHERE puerta LIKE TRIM(%s)", GetSQLValueString($colname_puerta, "text")); $puerta = mysql_query($query_puerta, $config) or die(mysql_error()); $row_puerta = mysql_fetch_assoc($puerta); $totalRows_puerta = mysql_num_rows($puerta); if($totalRows_familia == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_familia (familia) VALUES (%s)", GetSQLValueString(trim($data[$ifamilia]), "text")); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $mensajefamiliaimp .= $data[$ifamilia] . ", "; $idfamilia = mysql_insert_id($config); } else { $mensajefamilianoimp .= $data[$ifamilia] . ", "; $idfamilia = $row_familia['idfamilia']; } if($totalRows_subfamilia == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_subfamilia (subfamilia) VALUES (%s)", GetSQLValueString(trim($data[$isubfamilia]), "text")); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $mensajesubfamiliaimp .= $data[$isubfamilia] . ", "; $idsubfamilia = mysql_insert_id($config); } else { $mensajesubfamilianoimp .= $data[$isubfamilia] . ", "; $idsubfamilia = $row_subfamilia['idsubfamilia']; } if($totalRows_puerta == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_puerta (puerta) VALUES (%s)", GetSQLValueString(trim($data[$ipuerta]), "text")); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $mensajepuertaimp .= $data[$ipuerta] . ", "; $idpuerta = mysql_insert_id($config); } else { $mensajepuertanoimp .= $data[$ipuerta] . ", "; $idpuerta = $row_puerta['idpuerta']; } $colname_modelo = $data[$iversion]; $colname2_modelo = $prsel; $colname3_modelo = $idfamilia; mysql_select_db($database_config, $config); $query_modelo = sprintf("SELECT * FROM slc_stocksud_modelo WHERE version = %s AND pr = %s AND idfamilia = %s", GetSQLValueString($colname_modelo, "text"), GetSQLValueString($colname2_modelo, "text"), GetSQLValueString($colname3_modelo, "int")); $modelo = mysql_query($query_modelo, $config) or die(mysql_error()); $row_modelo = mysql_fetch_assoc($modelo); $totalRows_modelo = mysql_num_rows($modelo); if($totalRows_modelo == 0){ $insertSQL = sprintf("INSERT INTO slc_stocksud_modelo (modelo, idfamilia, idsubfamilia, idpuerta, publicarweb, publicarprecio, version) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString(trim($data[$imodelo]), "text"), GetSQLValueString($idfamilia, "int"), GetSQLValueString($idsubfamilia, "int"), GetSQLValueString($idpuerta, "int"), GetSQLValueString('1', "int"), GetSQLValueString('1', "int"), GetSQLValueString($data[$iversion], "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idmodelo = mysql_insert_id($config); for($k=0; $k<count($pr); $k++){ if(trim(trim($pr[$k])) != '') { $insertSQL = sprintf("INSERT INTO slc_stocksud_modelopr (idmodelo, pr) VALUES (%s, %s)", GetSQLValueString($idmodelo, "int"), GetSQLValueString(trim($pr[$k]), "text")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } $updateSQL = sprintf("UPDATE slc_stocksud_modelo SET pr=%s WHERE idmodelo=%s", GetSQLValueString($prsel, "text"), GetSQLValueString($idmodelo, "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $mensajemodeloimp .= $data[$imodelo] . ", "; } else { $mensajemodelonoimp .= $data[$imodelo] . ", "; } } } fclose ($fp); } else { $mensaje="Error al abrir el archivo."; } } else { $mensaje="El archivo seleccionado debe ser CSV (delimitado por comas)."; } } else { $mensaje="El archivo seleccionado no es correcto."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } </style> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD </span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>MODELOS</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td height="220" valign="top" bgcolor="#FFFFFF"><table width="100%" height="100%" cellpadding="0" cellspacing="4"> <?php if($mensaje != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo $mensaje;?></td> </tr> <?php }?> <?php if($mensajeprimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, los siguientes pr: <br>" . $mensajeprimp;?></td> </tr> <?php }?> <?php if($mensajeprnoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, los siguientes pr: <br>" . $mensajeprnoimp;?></td> </tr> <?php }?> <?php if($mensajeversionimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, las siguientes versiones: <br>" . $mensajeversionimp;?></td> </tr> <?php }?> <?php if($mensajeversionnoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, las siguientes versiones: <br>" . $mensajeversionnoimp;?></td> </tr> <?php }?> <?php if($mensajefamiliaimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, las siguientes familias: <br>" . $mensajefamiliaimp;?></td> </tr> <?php }?> <?php if($mensajefamilianoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, las siguientes familias: <br>" . $mensajefamilianoimp;?></td> </tr> <?php }?> <?php if($mensajesubfamiliaimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, las siguientes subfamilias: <br>" . $mensajesubfamiliaimp;?></td> </tr> <?php }?> <?php if($mensajesubfamilianoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, las siguientes subfamilias: <br>" . $mensajesubfamilianoimp;?></td> </tr> <?php }?> <?php if($mensajepuertaimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, las siguientes puertas: <br>" . $mensajepuertaimp;?></td> </tr> <?php }?> <?php if($mensajepuertanoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, las siguientes puertas: <br>" . $mensajepuertanoimp;?></td> </tr> <?php }?> <?php if($mensajemodeloimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "Se han agregado a la base de datos, los siguientes modelos: <br>" . $mensajemodeloimp;?></td> </tr> <?php }?> <?php if($mensajemodelonoimp != "") { ?> <tr> <td valign="top" class="Estilo1"><?php echo "No se han agregado a la base de datos, los siguientes modelos: <br>" . $mensajemodelonoimp;?></td> </tr> <tr> <td valign="top" class="Estilo1"><div align="right"><a href="#"><img src="img/imprimir.gif" alt="Imprimir" width="26" height="23" border="0" onClick="window.print();"></a>&nbsp;&nbsp;</div></td> </tr> <?php }?> </table> </td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); mysql_free_result($modelo); ?> <file_sep>/stock_importador - Copia.php <?php require_once('Connections/config.php'); ?> <?php require("PHPMailerAutoload.php"); ?> <?php //initialize the session if (!isset($_SESSION)) { session_start(); } // ** Logout the current user. ** $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true"; if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){ $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){ //to fully log out a visitor we need to clear the session varialbles $_SESSION['MM_Username'] = NULL; $_SESSION['MM_UserGroup'] = NULL; $_SESSION['PrevUrl'] = NULL; unset($_SESSION['MM_Username']); unset($_SESSION['MM_UserGroup']); unset($_SESSION['PrevUrl']); $logoutGoTo = "index.php"; if ($logoutGoTo) { header("Location: $logoutGoTo"); exit; } } ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_usuario_sesion = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_usuario_sesion = $_SESSION['MM_Username']; } mysql_select_db($database_config, $config); $query_usuario_sesion = sprintf("SELECT idGrupo, nombre FROM slc_stocksud_usuario WHERE usuario = %s", GetSQLValueString($colname_usuario_sesion, "text")); $usuario_sesion = mysql_query($query_usuario_sesion, $config) or die(mysql_error()); $row_usuario_sesion = mysql_fetch_assoc($usuario_sesion); $totalRows_usuario_sesion = mysql_num_rows($usuario_sesion); ?> <?php $mensaje = ""; if ((isset($_POST["Importar"])) && ($_POST["Importar"] == "Importar")) { if($_FILES['pathArchivo']['name']!=''){ if($_FILES['pathArchivo']['size']){ $type = explode(".", $_FILES['pathArchivo']['name']); if($type[1] == 'csv'){ $fp = fopen ($_FILES['pathArchivo']['tmp_name'],"r"); if ($fp != false) { if(count(fgetcsv($fp,1000,',')) > 1) { $separador = ','; } elseif(count(fgetcsv($fp,1000,';')) > 1) { $separador = ';'; } } fclose ($fp); $fp = fopen ($_FILES['pathArchivo']['tmp_name'],"r"); if ($fp != false) { if( !ini_get('safe_mode') ){ set_time_limit(90); } $estableceri = 0; while ($data = fgetcsv ($fp, 1000, $separador)) { $i = 0; if($estableceri == 0) { foreach($data as $row) { switch (trim(strtolower($row))) { case 'programacion': $icomision2 = $i; break; case 'sucursal': $isucursal = $i; break; case 'deposito': $ideposito = $i; break; case 'factura': $ifactura = $i; break; case 'fecha': $ifecha = $i; break; case 'vin': $ivin = $i; break; case 'version': $iversion = $i; break; case 'catalogo': $icatalogo = $i; break; case 'color': $icolor = $i; break; case 'motor': $imotor = $i; break; case 'importe': $iimporte = $i; break; } $i++ ; } $estableceri = 1; } else { $comision2[] = $data[$icomision2]; $factura[] = $data[$ifactura]; $fecha = $data[$ifecha]; $fecha = explode("/",$fecha); $mes[] = $fecha[1]; $anio[] = $fecha[2]; $vin[] = $data[$ivin]; $version[] = $data[$iversion]; $catalogo[] = $data[$icatalogo]; $pr = explode(" ", $data[$icatalogo]); array_multisort($pr) ; $prsel = trim(implode(' ',$pr)); $codigocolor[] = $data[$icolor]; $motor[] = $data[$imotor]; $importe[] = $data[$iimporte]; $colname_color = $data[$icolor]; mysql_select_db($database_config, $config); $query_color = sprintf("SELECT color FROM slc_stocksud_color WHERE codigo = %s ", GetSQLValueString($colname_color, "text")); $color = mysql_query($query_color, $config) or die(mysql_error()); $row_color = mysql_fetch_assoc($color); $totalRows_color = mysql_num_rows($color); if($totalRows_color == 0){ $mensajeColorNoExiste.=$colname_color . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $data[$ivin] . "<br>"; $color2[]=''; } else { $color2[]=$row_color['color']; } $colname_modelo = $data[$iversion]; $colname2_modelo = $prsel; mysql_select_db($database_config, $config); if($colname2_modelo == '') { $query_modelo = sprintf("SELECT * FROM slc_stocksud_modelo WHERE version LIKE %s AND ISNULL(pr)", GetSQLValueString($colname_modelo . "%", "text")); } else { $query_modelo = sprintf("SELECT * FROM slc_stocksud_modelo WHERE version LIKE %s AND pr = %s", GetSQLValueString($colname_modelo . "%", "text"), GetSQLValueString($colname2_modelo, "text")); } $modelo = mysql_query($query_modelo, $config) or die(mysql_error()); $row_modelo = mysql_fetch_assoc($modelo); $totalRows_modelo = mysql_num_rows($modelo); if($totalRows_modelo == 0){ $mensajeModeloNoExiste.=$colname_modelo . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $data[$ivin] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $colname2_modelo . "<br>"; $modelo2[] = ''; } else { $modelo2[]=$row_modelo['modelo']; $idfamilia[]=$row_modelo['idfamilia']; $idsubfamilia[]=$row_modelo['idsubfamilia']; } if($data[$isucursal] != "") { $colname_sucursal = $data[$isucursal]; mysql_select_db($database_config, $config); $query_sucursal = sprintf("SELECT * FROM slc_sucursal WHERE codigo = %s", GetSQLValueString($colname_sucursal, "int")); $sucursal = mysql_query($query_sucursal, $config) or die(mysql_error()); $row_sucursal = mysql_fetch_assoc($sucursal); $totalRows_sucursal = mysql_num_rows($sucursal); if($totalRows_sucursal == 0){ $mensajeSucursalNoExiste.=$colname_sucursal . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $data[$ivin] . "<br>"; $sucursal2[] = ''; } else { $sucursal2[]=$row_sucursal['id']; } } else { $mensajeSucursalVacio.= $data[$ivin] . ", "; $sucursal2[] = ''; } if($data[$ideposito] != "") { $colname_deposito = $data[$ideposito]; mysql_select_db($database_config, $config); $query_deposito = sprintf("SELECT * FROM slc_deposito WHERE codigo = %s", GetSQLValueString($colname_deposito, "int")); $deposito = mysql_query($query_deposito, $config) or die(mysql_error()); $row_deposito = mysql_fetch_assoc($deposito); $totalRows_deposito = mysql_num_rows($deposito); if($totalRows_deposito == 0){ $mensajeDepositoNoExiste.=$colname_deposito . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $data[$ivin] . "<br>"; $deposito2[] = ''; $deposito_codigo[] = ''; } else { $deposito2[]=$row_deposito['id']; $deposito_codigo[] = $data[$ideposito]; } } else { $deposito2[] = ''; $deposito_codigo[] = ''; } } } fclose ($fp); $colname_stock_orden = $anio[0]; $colname2_stock_orden = $mes[0]; mysql_select_db($database_config, $config); $query_stock_orden = sprintf("SELECT MAX(orden) AS maxorden FROM slc_stocksud_stock WHERE anio = %s AND mes = %s", GetSQLValueString($colname_stock_orden, "int"), GetSQLValueString($colname2_stock_orden, "int")); $stock_orden = mysql_query($query_stock_orden, $config) or die(mysql_error()); $row_stock_orden = mysql_fetch_assoc($stock_orden); $totalRows_stock_orden = mysql_num_rows($stock_orden); $orden=0; if($totalRows_stock_orden > 0) { $orden = $row_stock_orden['maxorden']; } else { $orden = 1; } $cant=count($vin); for ($i=0; $i<$cant; $i++){ if($comision2[$i] != '') { if($vin[$i] != '') { $colname_stock_VIN = $vin[$i]; mysql_select_db($database_config, $config); $query_stock_VIN = sprintf("SELECT * FROM slc_stocksud_stock WHERE chasis = %s", GetSQLValueString($colname_stock_VIN, "text")); $stock_VIN = mysql_query($query_stock_VIN, $config) or die(mysql_error()); $row_stock_VIN = mysql_fetch_assoc($stock_VIN); $totalRows_stock_VIN = mysql_num_rows($stock_VIN); $colname_stocknofacturado_VIN = $comision2[$i]; mysql_select_db($database_config, $config); $query_stocknofacturado_VIN = sprintf("SELECT * FROM slc_stocksud_stocknofacturado WHERE TRIM(comision2) = %s", GetSQLValueString($colname_stocknofacturado_VIN, "int")); $stocknofacturado_VIN = mysql_query($query_stocknofacturado_VIN, $config) or die(mysql_error()); $row_stocknofacturado_VIN = mysql_fetch_assoc($stocknofacturado_VIN); $totalRows_stocknofacturado_VIN = mysql_num_rows($stocknofacturado_VIN); if(($color2[$i] != '') && ($modelo2[$i] != '') && ($sucursal2[$i] != '')){ //color, modelo y sucursal existen if(($totalRows_stocknofacturado_VIN > 0) && ($totalRows_stock_VIN == 0)){ //se encuentra en stock no facturado y no en facturado $orden++; if($row_stocknofacturado_VIN['idCliente'] > 0) { //stock no facturado asignado $insertSQL = sprintf("INSERT INTO slc_stocksud_stock (orden, mes, anio, anioprogramacion, comision2, idsucursal, iddeposito, numfactura, chasis, idMarca, modelo, version, color, motor, importefactcompra, idpago, idCliente, fechasolicitud, fechaestimadaentrega, precioventa, intereses, accesorios, idvendedor, idbanco, idcuota, importesolicitado, pagado, observaciones, idpromocion, usadomodelo, usadopatente, usadopreciodetoma, usadofechaventa, usadoprecioventa, usadocliente, usadoidvendedor, usadocomision, total, deuda, idSolicitud) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($orden, "int"), GetSQLValueString($mes[$i], "int"), GetSQLValueString($anio[$i], "int"), GetSQLValueString($row_stocknofacturado_VIN['anio'], "int"), GetSQLValueString($comision2[$i], "int"), GetSQLValueString($sucursal2[$i], "int"), GetSQLValueString($deposito2[$i], "int"), GetSQLValueString($factura[$i], "text"), GetSQLValueString($vin[$i], "text"), GetSQLValueString('3', "int"), GetSQLValueString($modelo2[$i], "text"), GetSQLValueString($version[$i], "text"), GetSQLValueString($color2[$i], "text"), GetSQLValueString($motor[$i], "text"), GetSQLValueString($importe[$i], "double"), GetSQLValueString('0', "int"), GetSQLValueString($row_stocknofacturado_VIN['idCliente'], "int"), GetSQLValueString(date('Y-m-d'), "date"), GetSQLValueString($row_stocknofacturado_VIN['fechaestimadaentrega'], "date"), GetSQLValueString($row_stocknofacturado_VIN['precioventa'], "double"), GetSQLValueString($row_stocknofacturado_VIN['intereses'], "double"), GetSQLValueString($row_stocknofacturado_VIN['accesorios'], "double"), GetSQLValueString($row_stocknofacturado_VIN['idvendedor'], "int"), GetSQLValueString($row_stocknofacturado_VIN['idbanco'], "int"), GetSQLValueString($row_stocknofacturado_VIN['idcuota'], "int"), GetSQLValueString($row_stocknofacturado_VIN['importesolicitado'], "double"), GetSQLValueString($row_stocknofacturado_VIN['pagado'], "double"), GetSQLValueString($row_stocknofacturado_VIN['observaciones'], "text"), GetSQLValueString($row_stocknofacturado_VIN['idpromocion'], "int"), GetSQLValueString($row_stocknofacturado_VIN['usado'], "text"), GetSQLValueString($row_stocknofacturado_VIN['usadopatente'], "text"), GetSQLValueString($row_stocknofacturado_VIN['usadopreciodetoma'], "double"), GetSQLValueString($row_stocknofacturado_VIN['usadofechaventa'], "date"), GetSQLValueString($row_stocknofacturado_VIN['usadoprecioventa'], "double"), GetSQLValueString($row_stocknofacturado_VIN['usadocliente'], "text"), GetSQLValueString($row_stocknofacturado_VIN['usadoidvendedor'], "int"), GetSQLValueString($row_stocknofacturado_VIN['usadocomision'], "text"), GetSQLValueString($row_stocknofacturado_VIN['total'], "double"), GetSQLValueString($row_stocknofacturado_VIN['deuda'], "double"), GetSQLValueString($row_stocknofacturado_VIN['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idstock = mysql_insert_id($config); $pr = explode(" ", trim($catalogo[$i])); for($k=0;$k<count($pr);$k++){ $colname_opcional = $pr[$k]; $colname2_opcional = $idfamilia[$i]; $colname3_opcional = $idsubfamilia[$i]; mysql_select_db($database_config, $config); $query_opcional = sprintf("SELECT slc_stocksud_opcional.idopcional FROM slc_stocksud_opcional LEFT JOIN slc_stocksud_familia_sub_opcional ON slc_stocksud_familia_sub_opcional.idopcional = slc_stocksud_opcional.idopcional WHERE slc_stocksud_opcional.pr LIKE %s AND slc_stocksud_familia_sub_opcional.idfamilia = %s AND slc_stocksud_familia_sub_opcional.idsubfamilia = %s", GetSQLValueString($colname_opcional, "text"), GetSQLValueString($colname2_opcional, "int"), GetSQLValueString($colname3_opcional, "int")); $opcional = mysql_query($query_opcional, $config) or die(mysql_error()); $row_opcional = mysql_fetch_assoc($opcional); $totalRows_opcional = mysql_num_rows($opcional); if($totalRows_opcional>0) { $insertSQL = sprintf("INSERT INTO slc_stocksud_stock_opcional (idstock, idopcional) VALUES (%s, %s)", GetSQLValueString($idstock, "int"), GetSQLValueString($row_opcional['idopcional'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } $colname_entrega = $vin[$i]; $colname2_entrega = $comision2[$i]; mysql_select_db($database_config, $config); $query_entrega = sprintf("SELECT idEntrega, fechaHoraEntrega FROM slc_entrega WHERE VIN = %s OR VIN = %s", GetSQLValueString($colname_entrega, "text"), GetSQLValueString($colname2_entrega, "text")); $entrega = mysql_query($query_entrega, $config) or die(mysql_error()); $row_entrega = mysql_fetch_assoc($entrega); $totalRows_entrega = mysql_num_rows($entrega); $colname_solicitudreserva = $row_stocknofacturado_VIN['idSolicitud']; mysql_select_db($database_config, $config); $query_solicitudreserva = sprintf("SELECT slc_solicitudreserva.autoahorro, slc_solicitudreserva.fechaestimadaentrega, idMarca, slc_sucursal_venta.codigo, slc_sucursal_venta.sucursal FROM slc_solicitudreserva LEFT JOIN slc_sucursal_venta ON slc_sucursal_venta.id = slc_solicitudreserva.idsucursalventa WHERE idSolicitud = %s", GetSQLValueString($colname_solicitudreserva, "int")); $solicitudreserva = mysql_query($query_solicitudreserva, $config) or die(mysql_error()); $row_solicitudreserva = mysql_fetch_assoc($solicitudreserva); $totalRows_solicitudreserva = mysql_num_rows($solicitudreserva); if(($deposito_codigo[$i]!= '') && ($row_solicitudreserva['codigo']) && ($deposito_codigo[$i]!=$row_solicitudreserva['codigo'])) { $mensajedepositosucursal .= $vin[$i] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $deposito_codigo[$i] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $row_solicitudreserva['codigo']; } if($totalRows_entrega == 0){ $colname_usados = $row_stocknofacturado_VIN['idSolicitud']; mysql_select_db($database_config, $config); $query_usados = sprintf("SELECT usadodescripcion, usadoanio, usadodominio, usadoidtasacion, importe FROM slc_solicitudformapago WHERE idSolicitud = %s AND formapago = 'usado'", GetSQLValueString($colname_usados, "int")); $usados = mysql_query($query_usados, $config) or die(mysql_error()); $row_usados = mysql_fetch_assoc($usados); $totalRows_usados = mysql_num_rows($usados); if($totalRows_usados > 0) { $entrega_usados = 1; } else { $entrega_usados = 0; } $colname_accesorios = $row_stocknofacturado_VIN['idSolicitud']; mysql_select_db($database_config, $config); $query_accesorios = sprintf("SELECT idAccesorioTipo, importe FROM slc_solicitudaccesorio WHERE idSolicitud = %s", GetSQLValueString($colname_accesorios, "int")); $accesorios = mysql_query($query_accesorios, $config) or die(mysql_error()); $row_accesorios = mysql_fetch_assoc($accesorios); $totalRows_accesorios = mysql_num_rows($accesorios); if($totalRows_accesorios > 0) { $entrega_accesorios = 1; } else { $entrega_accesorios = 0; } $prendaPropia = 0; if($row_solicitudreserva['autoahorro'] == 1) { $idTipoEntrega = 2; } else { $idTipoEntrega = 3; } $colname_vendedor = $row_stocknofacturado_VIN['idvendedor']; mysql_select_db($database_config, $config); $query_vendedor = sprintf("SELECT usuario, idconsultor FROM slc_stocksud_usuario WHERE idUsuario = %s", GetSQLValueString($colname_vendedor, "text")); $vendedor = mysql_query($query_vendedor, $config) or die(mysql_error()); $row_vendedor = mysql_fetch_assoc($vendedor); $totalRows_vendedor = mysql_num_rows($vendedor); $colname_vendedor2 = $row_vendedor['usuario']; mysql_select_db($database_config, $config); $query_vendedor2 = sprintf("SELECT idUsuario FROM slc_usuario WHERE usuario LIKE %s", GetSQLValueString($colname_vendedor2, "text")); $vendedor2 = mysql_query($query_vendedor2, $config) or die(mysql_error()); $row_vendedor2 = mysql_fetch_assoc($vendedor2); $totalRows_vendedor2 = mysql_num_rows($vendedor2); $colname_consultor = $row_vendedor['idconsultor']; mysql_select_db($database_config, $config); $query_consultor = sprintf("SELECT idUsuario FROM slc_consultor WHERE idConsultor = %s", GetSQLValueString($colname_consultor, "int")); $consultor = mysql_query($query_consultor, $config) or die(mysql_error()); $row_consultor = mysql_fetch_assoc($consultor); $totalRows_consultor = mysql_num_rows($consultor); $colname_stock = $row_stocknofacturado_VIN['idstock']; mysql_select_db($database_config, $config); $query_stock = sprintf("SELECT idMarca, modelo FROM slc_stocksud_stock WHERE idstock = %s", GetSQLValueString($colname_stock, "int")); $stock = mysql_query($query_stock, $config) or die(mysql_error()); $row_stock = mysql_fetch_assoc($stock); $totalRows_stock = mysql_num_rows($stock); if($solicitudreserva['fechaestimadaentrega'] != "") { $fechaHoraEntrega = $solicitudreserva['fechaestimadaentrega']; $fechaHoraEntrega = fecha($fechaHoraEntrega,0); $fechaEntrega = fecha($fechaHoraEntrega); //obtiene fecha de caducidad de la encuesta temprana, es la fecha de entrega mas la caducidad que indica la encuesta. $colname_encuesta = $solicitudreserva['idMarca']; mysql_select_db($database_config, $config); $query_encuesta = sprintf("SELECT caducidad FROM slc_encuesta WHERE idtipo = 1 AND activa = 1 AND idMarca = %s ORDER BY idencuesta DESC ", GetSQLValueString($colname_encuesta, "int")); $encuesta = mysql_query($query_encuesta, $config) or die(mysql_error()); $row_encuesta = mysql_fetch_assoc($encuesta); $totalRows_encuesta = mysql_num_rows($encuesta); if(($totalRows_encuesta > 0) && ($row_encuesta['caducidad'] > 0)) { $caducidad = $row_encuesta['caducidad']; } else { $caducidad = 0; } $fechacaducidadenctemprana = sumardiasafecha($fechaEntrega,$caducidad); //obtiene fecha de caducidad de la encuesta llamado de cortesia, es la fecha de entrega mas la caducidad que indica la encuesta, excluyendo domingos y feriados. $colname_encuesta = $solicitudreserva['idMarca']; mysql_select_db($database_config, $config); $query_encuesta = sprintf("SELECT caducidad FROM slc_encuesta WHERE idtipo = 2 AND activa = 1 AND idMarca = %s ORDER BY idencuesta DESC ", GetSQLValueString($colname_encuesta, "int")); $encuesta = mysql_query($query_encuesta, $config) or die(mysql_error()); $row_encuesta = mysql_fetch_assoc($encuesta); $totalRows_encuesta = mysql_num_rows($encuesta); if(($totalRows_encuesta > 0) && ($row_encuesta['caducidad'] > 0)) { $caducidad = $row_encuesta['caducidad']; } else { $caducidad = 0; } $fechacaducidadenccortesia = $fechaEntrega; for($i=1; $i<=$caducidad; $i++) { do { $fechacaducidadenccortesia = strtotime('+1 day',strtotime($fechacaducidadenccortesia)); $fechacaducidadenccortesia = date ('Y-m-d',$fechacaducidadenccortesia); $colname_feriado = $fechacaducidadenccortesia; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } while (($totalRows_feriado > 0) || (date('w',strtotime($fechacaducidadenccortesia)) == 0)); } //obtiene fecha de caducidad de la encuesta call center, es la fecha de entrega mas la caducidad que indica la encuesta, excluyendo domingos y feriados. $colname_encuesta = $solicitudreserva['idMarca']; mysql_select_db($database_config, $config); $query_encuesta = sprintf("SELECT caducidad FROM slc_encuesta WHERE idtipo = 3 AND venta_postventa = 1 AND activa = 1 AND idMarca = %s ORDER BY idencuesta DESC ", GetSQLValueString($colname_encuesta, "int")); $encuesta = mysql_query($query_encuesta, $config) or die(mysql_error()); $row_encuesta = mysql_fetch_assoc($encuesta); $totalRows_encuesta = mysql_num_rows($encuesta); if(($totalRows_encuesta > 0) && ($row_encuesta['caducidad'] > 0)) { $caducidad = $row_encuesta['caducidad']; } else { $caducidad = 0; } $fechacaducidadenccallcenter = $fechacaducidadenccortesia; for($i=1; $i<=$caducidad; $i++) { do { $fechacaducidadenccallcenter = strtotime('+1 day',strtotime($fechacaducidadenccallcenter)); $fechacaducidadenccallcenter = date ('Y-m-d',$fechacaducidadenccallcenter); $colname_feriado = $fechacaducidadenccallcenter; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } while (($totalRows_feriado > 0) || (date('w',strtotime($fechacaducidadenccallcenter)) == 0)); } $insertSQL = sprintf("INSERT INTO slc_entrega (idCliente, idUsuarioCarga, fechaHoraCarga, idConsultor, idVendedor, idTipoEntrega, VIN, idMarca, modelo, observaciones, accesorios, usados, prendaPropia, idSolicitud, empresa, fechaHoraEntrega, fechacaducidadenctemprana, fechacaducidadenccortesia, fechacaducidadenccallcenter) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($row_stocknofacturado_VIN['idCliente'], "int"), GetSQLValueString('0', "int"), GetSQLValueString(date('Y-m-d h:i'), "date"), GetSQLValueString($row_vendedor['idconsultor'], "int"), GetSQLValueString($row_vendedor2['idUsuario'], "int"), GetSQLValueString($idTipoEntrega, "int"), GetSQLValueString($vin[$i], "text"), GetSQLValueString('3', "int"), GetSQLValueString($modelo2[$i], "text"), GetSQLValueString('', "text"), GetSQLValueString($entrega_accesorios, "int"), GetSQLValueString($entrega_usados, "int"), GetSQLValueString($prendaPropia, "int"), GetSQLValueString($row_stocknofacturado_VIN['idSolicitud'], "text"), GetSQLValueString('3', "int"), GetSQLValueString($solicitudreserva['fechaestimadaentrega'], "date"), GetSQLValueString($fechacaducidadenctemprana, "date"), GetSQLValueString($fechacaducidadenccortesia, "date"), GetSQLValueString($fechacaducidadenccallcenter, "date")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $insertSQL = sprintf("INSERT INTO slc_entrega (idCliente, idUsuarioCarga, fechaHoraCarga, idConsultor, idVendedor, idTipoEntrega, VIN, idMarca, modelo, observaciones, accesorios, usados, prendaPropia, idSolicitud, empresa) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($row_stocknofacturado_VIN['idCliente'], "int"), GetSQLValueString('0', "int"), GetSQLValueString(date('Y-m-d h:i'), "date"), GetSQLValueString($row_vendedor['idconsultor'], "int"), GetSQLValueString($row_vendedor2['idUsuario'], "int"), GetSQLValueString($idTipoEntrega, "int"), GetSQLValueString($vin[$i], "text"), GetSQLValueString('3', "int"), GetSQLValueString($modelo2[$i], "text"), GetSQLValueString('', "text"), GetSQLValueString($entrega_accesorios, "int"), GetSQLValueString($entrega_usados, "int"), GetSQLValueString($prendaPropia, "int"), GetSQLValueString($row_stocknofacturado_VIN['idSolicitud'], "text"), GetSQLValueString('3', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } $idEntrega = mysql_insert_id($config); if($totalRows_accesorios > 0){ // Show if recordset not empty do { $insertSQL = sprintf("INSERT INTO slc_entregaaccesorio(idEntrega, idAccesorioTipo, accesoriosimporte) VALUES (%s, %s, %s)", GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_accesorios['idAccesorioTipo'], "int"), GetSQLValueString($row_accesorios['importe'], "double")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } while ($row_accesorios = mysql_fetch_assoc($accesorios)); } // Show if recordset not empty if($totalRows_usados > 0){ // Show if recordset not empty do { $insertSQL = sprintf("INSERT INTO slc_entregausado(idEntrega, usadoModelo, usadoDominio, usadoAnio, usadoImporte, usadoidtasacion) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_usados['usadodescripcion'], "text"), GetSQLValueString($row_usados['usadodominio'], "text"), GetSQLValueString($row_usados['usadoanio'], "int"), GetSQLValueString($row_usados['importe'], "double"), GetSQLValueString($row_usados['usadoidtasacion'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } while ($row_usados = mysql_fetch_assoc($usados)); } // Show if recordset not empty //Agrega llamado de revisión de operación $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('+1 day',strtotime($fechacontacto)) ; $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('+1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('3', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de revision de operacion', "text"), GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); /*datos para enviar email llamado de revision de operacion*/ $colname_agenda = $idEntrega; mysql_select_db($database_config, $config); $query_agenda = sprintf("SELECT slc_agenda.idagenda, slc_agenda.fechahora, slc_usuario.nombre AS responsable, slc_marca.marca, slc_entrega.modelo, slc_entrega.fechaHoraEntrega AS fechaentrega, slc_entrega.VIN, slc_stock_cliente.apellidoynombre FROM slc_agenda LEFT JOIN slc_usuario ON slc_usuario.idUsuario = slc_agenda.idUsuario LEFT JOIN slc_entrega ON slc_entrega.idEntrega = slc_agenda.idEntrega LEFT JOIN slc_marca ON slc_marca.idMarca = slc_entrega.idMarca LEFT JOIN slc_stock_cliente ON slc_stock_cliente.idCliente = slc_entrega.idCliente WHERE idtipoevento = '3' AND slc_agenda.idEntrega = %s", GetSQLValueString($colname_agenda, "int")); $agenda = mysql_query($query_agenda, $config) or die(mysql_error()); $row_agenda = mysql_fetch_assoc($agenda); $totalRows_agenda = mysql_num_rows($agenda); $email_fechaproxcontacto[] = fecha($fechaproxcontacto, 0); $email_responsable[] = $row_agenda['responsable']; $email_marca[] = $row_agenda['marca']; $email_modelo[] = $row_agenda['modelo']; $email_apellidoynombre[] = $row_agenda['apellidoynombre']; $email_fechaentrega[] = fecha($row_agenda['fechaentrega'],0); $email_VIN[] = $row_agenda['VIN'] ; /*datos para enviar email llamado de revision de operacion*/ /*Cierra los contactos de agenda por facturación */ $updateSQL = sprintf("UPDATE slc_agenda SET idEntrega=%s, estado=%s, cerradopor=%s, stocknofacturado=%s WHERE idtipoevento<>%s AND estado=%s AND idSolicitud = %s", GetSQLValueString($idEntrega, "int"), GetSQLValueString('4', "int"), GetSQLValueString('1', "int"), GetSQLValueString('1', "int"), GetSQLValueString('3', "int"), GetSQLValueString('0', "int"), GetSQLValueString($row_stocknofacturado_VIN['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); //Alta a llamado de confirmación de entrega if($solicitudreserva['fechaestimadaentrega'] != "") { $datetime1 = new DateTime(date('Y-m-d')); $datetime2 = new DateTime($solicitudreserva['fechaestimadaentrega']); $interval = $datetime1->diff($datetime2); $dias = $interval->format('%R%a'); if($dias == 1) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-1 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } else if($dias >= 2) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-2 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-1 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-3 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('-1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $datetime1 = new DateTime(date('Y-m-d')); $datetime2 = new DateTime($fechaproxcontacto); $interval = $datetime1->diff($datetime2); $dias = $interval->format('%R%a'); if($dias > 0) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($idEntrega, "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } } } } } else { //totalRows_entrega == 0 $colname_vendedor = $row_stocknofacturado_VIN['idvendedor']; mysql_select_db($database_config, $config); $query_vendedor = sprintf("SELECT usuario, idconsultor FROM slc_stocksud_usuario WHERE idUsuario = %s", GetSQLValueString($colname_vendedor, "text")); $vendedor = mysql_query($query_vendedor, $config) or die(mysql_error()); $row_vendedor = mysql_fetch_assoc($vendedor); $totalRows_vendedor = mysql_num_rows($vendedor); $colname_vendedor2 = $row_vendedor['usuario']; mysql_select_db($database_config, $config); $query_vendedor2 = sprintf("SELECT idUsuario FROM slc_usuario WHERE usuario LIKE %s", GetSQLValueString($colname_vendedor2, "text")); $vendedor2 = mysql_query($query_vendedor2, $config) or die(mysql_error()); $row_vendedor2 = mysql_fetch_assoc($vendedor2); $totalRows_vendedor2 = mysql_num_rows($vendedor2); $colname_consultor = $row_vendedor['idconsultor']; mysql_select_db($database_config, $config); $query_consultor = sprintf("SELECT idUsuario FROM slc_consultor WHERE idConsultor = %s", GetSQLValueString($colname_consultor, "int")); $consultor = mysql_query($query_consultor, $config) or die(mysql_error()); $row_consultor = mysql_fetch_assoc($consultor); $totalRows_consultor = mysql_num_rows($consultor); //Busca si existe llamado de revisión de operación $colname_agenda = $row_entrega['idEntrega']; mysql_select_db($database_config, $config); $query_agenda = sprintf("SELECT estado FROM slc_agenda WHERE idEntrega = %s AND idtipoevento= '3'", GetSQLValueString($colname_agenda, "int")); $agenda = mysql_query($query_agenda, $config) or die(mysql_error()); $row_agenda = mysql_fetch_assoc($agenda); $totalRows_agenda = mysql_num_rows($agenda); if($totalRows_agenda == 0){ $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('+1 day',strtotime($fechacontacto)) ; $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('+1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('3', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de revision de operacion', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); /*datos para enviar email llamado de revision de operacion*/ $colname_agenda = $row_entrega['idEntrega']; mysql_select_db($database_config, $config); $query_agenda = sprintf("SELECT slc_agenda.idagenda, slc_agenda.fechahora, slc_usuario.nombre AS responsable, slc_marca.marca, slc_entrega.modelo, slc_entrega.fechaHoraEntrega AS fechaentrega, slc_entrega.VIN, slc_stock_cliente.apellidoynombre FROM slc_agenda LEFT JOIN slc_usuario ON slc_usuario.idUsuario = slc_agenda.idUsuario LEFT JOIN slc_entrega ON slc_entrega.idEntrega = slc_agenda.idEntrega LEFT JOIN slc_marca ON slc_marca.idMarca = slc_entrega.idMarca LEFT JOIN slc_stock_cliente ON slc_stock_cliente.idCliente = slc_entrega.idCliente WHERE idtipoevento = '3' AND slc_agenda.idEntrega = %s", GetSQLValueString($colname_agenda, "int")); $agenda = mysql_query($query_agenda, $config) or die(mysql_error()); $row_agenda = mysql_fetch_assoc($agenda); $totalRows_agenda = mysql_num_rows($agenda); $email_fechaproxcontacto[] = fecha($fechaproxcontacto, 0); $email_responsable[] = $row_agenda['responsable']; $email_marca[] = $row_agenda['marca']; $email_modelo[] = $row_agenda['modelo']; $email_apellidoynombre[] = $row_agenda['apellidoynombre']; $email_fechaentrega[] = fecha($row_agenda['fechaentrega'],0); $email_VIN[] = $vin[$i]; /*datos para enviar email llamado de revision de operacion*/ $datetime1 = new DateTime(date('Y-m-d')); $datetime2 = new DateTime($row_entrega['fechaHoraEntrega']); $interval = $datetime1->diff($datetime2); $dias = $interval->format('%R%a'); if($dias == 1) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-1 day',strtotime($row_entrega['fechaHoraEntrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } else if($dias >= 2) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-2 day',strtotime($row_entrega['fechaHoraEntrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-1 day',strtotime($row_entrega['fechaHoraEntrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-3 day',strtotime($row_entrega['fechaHoraEntrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('-1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $datetime1 = new DateTime(date('Y-m-d')); $datetime2 = new DateTime($fechaproxcontacto); $interval = $datetime1->diff($datetime2); $dias = $interval->format('%R%a'); if($dias > 0) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } } } /*Cierra los contactos de agenda por facturación */ $updateSQL = sprintf("UPDATE slc_agenda SET idEntrega=%s, estado=%s, cerradopor=%s, stocknofacturado=%s WHERE estado=%s AND idtipoevento=%s AND idSolicitud = %s", GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString('4', "int"), GetSQLValueString('1', "int"), GetSQLValueString('1', "int"), GetSQLValueString('0', "int"), GetSQLValueString('2', "int"), GetSQLValueString($_POST['idSolicitud'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); $updateSQL = sprintf("UPDATE slc_agenda SET estado=%s, cerradopor=%s, stocknofacturado=%s WHERE idtipoevento<>%s AND idtipoevento<>%s AND estado=%s AND idEntrega = %s", GetSQLValueString('4', "int"), GetSQLValueString('1', "int"), GetSQLValueString('1', "int"), GetSQLValueString('3', "int"), GetSQLValueString('5', "int"), GetSQLValueString('0', "int"), GetSQLValueString($row_entrega['idEntrega'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); } //totalRows_agenda == 0 //Actualiza entrega $updateSQL = sprintf("UPDATE slc_entrega SET VIN=%s, stocknofacturado=%s WHERE idEntrega = %s", GetSQLValueString($vin[$i], "text"), GetSQLValueString('0', "int"), GetSQLValueString($row_entrega['idEntrega'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($updateSQL, $config) or die(mysql_error()); //Alta a llamado de confirmación de entrega if($row_entrega['fechaHoraEntrega'] != "") { $datetime1 = new DateTime(date('Y-m-d')); $datetime2 = new DateTime($row_entrega['fechaHoraEntrega']); $interval = $datetime1->diff($datetime2); $dias = $interval->format('%R%a'); if($dias == 1) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-1 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } else if($dias >= 2) { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-2 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-1 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); if (($totalRows_feriado == 0) && (date('w',strtotime($fechaproxcontacto)) != 0)) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } else { $fechacontacto = date('Y-m-d h:i'); $fechaproxcontacto = strtotime('-3 day',strtotime($_POST['fechaestimadaentrega'])) ; $horaproxcontacto = date ('h:i',$fechaproxcontacto); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); while (($totalRows_feriado > 0) || (date('w',strtotime($fechaproxcontacto)) == 0)) { $fechaproxcontacto = strtotime('-1 day',strtotime($fechaproxcontacto)); $fechaproxcontacto = date ('Y-m-d',$fechaproxcontacto); $colname_feriado = $fechaproxcontacto; mysql_select_db($database_config, $config); $query_feriado = sprintf("SELECT * FROM slc_feriado WHERE fecha = %s", GetSQLValueString($colname_feriado, "date")); $feriado = mysql_query($query_feriado, $config) or die(mysql_error()); $row_feriado = mysql_fetch_assoc($feriado); $totalRows_feriado = mysql_num_rows($feriado); } $datetime1 = new DateTime(date('Y-m-d')); $datetime2 = new DateTime($fechaproxcontacto); $interval = $datetime1->diff($datetime2); $dias = $interval->format('%R%a'); if($dias > 0) { $fechaproxcontacto = $fechaproxcontacto . " " . $horaproxcontacto; $insertSQL = sprintf("INSERT INTO slc_agenda (idtipoevento, fechahoracontacto, fechahora, asunto, idEntrega, idUsuario, estado) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString('5', "int"), GetSQLValueString($fechacontacto, "date"), GetSQLValueString($fechaproxcontacto, "date"), GetSQLValueString('Llamado de confirmacion de entrega', "text"), GetSQLValueString($row_entrega['idEntrega'], "int"), GetSQLValueString($row_consultor['idUsuario'], "int"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } } } } } //totalRows_entrega == 0 } else { //stock no facturado no asignado row_stocknofacturado_VIN['idCliente'] > 0 $insertSQL = sprintf("INSERT INTO slc_stocksud_stock (orden, mes, anio, comision2, idsucursal, iddeposito, numfactura, chasis, idMarca, modelo, version, color, motor, importefactcompra, idpago) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($orden, "int"), GetSQLValueString($mes[$i], "int"), GetSQLValueString($anio[$i], "int"), GetSQLValueString($comision2[$i], "text"), GetSQLValueString($sucursal2[$i], "int"), GetSQLValueString($deposito2[$i], "int"), GetSQLValueString($factura[$i], "text"), GetSQLValueString($vin[$i], "text"), GetSQLValueString('3', "int"), GetSQLValueString($modelo2[$i], "text"), GetSQLValueString($version[$i], "text"), GetSQLValueString($color2[$i], "text"), GetSQLValueString($motor[$i], "text"), GetSQLValueString($importe[$i], "double"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idstock = mysql_insert_id($config); $pr = explode(" ", trim($catalogo[$i])); for($k=0;$k<count($pr);$k++){ $colname_opcional = $pr[$k]; $colname2_opcional = $idfamilia[$i]; $colname3_opcional = $idsubfamilia[$i]; mysql_select_db($database_config, $config); $query_opcional = sprintf("SELECT slc_stocksud_opcional.idopcional FROM slc_stocksud_opcional LEFT JOIN slc_stocksud_familia_sub_opcional ON slc_stocksud_familia_sub_opcional.idopcional = slc_stocksud_opcional.idopcional WHERE slc_stocksud_opcional.pr LIKE %s AND slc_stocksud_familia_sub_opcional.idfamilia = %s AND slc_stocksud_familia_sub_opcional.idsubfamilia = %s", GetSQLValueString($colname_opcional, "text"), GetSQLValueString($colname2_opcional, "int"), GetSQLValueString($colname3_opcional, "int")); $opcional = mysql_query($query_opcional, $config) or die(mysql_error()); $row_opcional = mysql_fetch_assoc($opcional); $totalRows_opcional = mysql_num_rows($opcional); if($totalRows_opcional>0) { $insertSQL = sprintf("INSERT INTO slc_stocksud_stock_opcional (idstock, idopcional) VALUES (%s, %s)", GetSQLValueString($idstock, "int"), GetSQLValueString($row_opcional['idopcional'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } } //row_stocknofacturado_VIN['idCliente'] > 0 $deleteSQL = sprintf("DELETE FROM slc_stocksud_stocknofacturado WHERE idstock=%s", GetSQLValueString($row_stocknofacturado_VIN['idstock'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($deleteSQL, $config) or die(mysql_error()); } elseif($totalRows_stock_VIN == 0){ // Guarda si el VIN o chasis no se encuentra en la BD $orden++; $insertSQL = sprintf("INSERT INTO slc_stocksud_stock (orden, mes, anio, comision2, idsucursal, iddeposito, numfactura, chasis, idMarca, modelo, version, color, motor, importefactcompra, idpago) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($orden, "int"), GetSQLValueString($mes[$i], "int"), GetSQLValueString($anio[$i], "int"), GetSQLValueString($comision2[$i], "int"), GetSQLValueString($sucursal2[$i], "int"), GetSQLValueString($deposito2[$i], "int"), GetSQLValueString($factura[$i], "text"), GetSQLValueString($vin[$i], "text"), GetSQLValueString('3', "int"), GetSQLValueString($modelo2[$i], "text"), GetSQLValueString($version[$i], "text"), GetSQLValueString($color2[$i], "text"), GetSQLValueString($motor[$i], "text"), GetSQLValueString($importe[$i], "double"), GetSQLValueString('0', "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); $idstock = mysql_insert_id($config); $pr = explode(" ", trim($catalogo[$i])); for($k=0;$k<count($pr);$k++){ $colname_opcional = $pr[$k]; $colname2_opcional = $idfamilia[$i]; $colname3_opcional = $idsubfamilia[$i]; mysql_select_db($database_config, $config); $query_opcional = sprintf("SELECT slc_stocksud_opcional.idopcional FROM slc_stocksud_opcional LEFT JOIN slc_stocksud_familia_sub_opcional ON slc_stocksud_familia_sub_opcional.idopcional = slc_stocksud_opcional.idopcional WHERE slc_stocksud_opcional.pr LIKE %s AND slc_stocksud_familia_sub_opcional.idfamilia = %s AND slc_stocksud_familia_sub_opcional.idsubfamilia = %s", GetSQLValueString($colname_opcional, "text"), GetSQLValueString($colname2_opcional, "int"), GetSQLValueString($colname3_opcional, "int")); $opcional = mysql_query($query_opcional, $config) or die(mysql_error()); $row_opcional = mysql_fetch_assoc($opcional); $totalRows_opcional = mysql_num_rows($opcional); if($totalRows_opcional>0) { $insertSQL = sprintf("INSERT INTO slc_stocksud_stock_opcional (idstock, idopcional) VALUES (%s, %s)", GetSQLValueString($idstock, "int"), GetSQLValueString($row_opcional['idopcional'], "int")); mysql_select_db($database_config, $config); $Result1 = mysql_query($insertSQL, $config) or die(mysql_error()); } } } else { // /Guarda si el VIN o chasis no se encuentra en la BD $mensajeVINduplicado .= $vin[$i] . ", "; } } //color y modelo existen } else { $mensajeVINVacio .= $comision2[$i] . ", "; } } else { $mensajeProgramacionVacio .= $vin[$i] . ", "; } } $mensaje="Los datos se importaron correctamente."; } else { $mensaje="Error al abrir el archivo."; } } else { $mensaje="El archivo seleccionado debe ser CSV (delimitado por comas)."; } } else { $mensaje="El archivo seleccionado no es correcto."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } } else { $mensaje="Debe seleccionar un archivo a importar."; } /*email llamado de revision de operacion*/ if(count($email_apellidoynombre) > 0){ $cuerpo = '<style type="text/css">'; $cuerpo .= '.Estilo1 {'; $cuerpo .= ' font-family: Arial, Helvetica, sans-serif;'; $cuerpo .= ' font-size: 12px;'; $cuerpo .= ' color: #333;'; $cuerpo .= '}'; $cuerpo .= '</style>'; for($i=0; $i<count($email_apellidoynombre);$i++) { $cuerpo .= '<div class="Estilo1">'; $cuerpo .= 'Fecha proximo contacto: ' . $email_fechaproxcontacto[$i] . '<br>'; $cuerpo .= 'Responsable: ' . $email_responsable[$i] . '<br>'; $cuerpo .= 'Marca: ' . $email_marca[$i] . '<br>'; $cuerpo .= 'Modelo: ' . $email_modelo[$i] . '<br>'; $cuerpo .= 'Cliente: ' . $email_apellidoynombre[$i] . '<br>'; $cuerpo .= 'Fecha de la entrega: ' . $email_fechaentrega[$i] . '<br><br>'; $cuerpo .= 'VIN: ' . $email_VIN[$i] . '<br><br><br>'; $cuerpo .= '</div>'; } mysql_select_db($database_config, $config); $query_mailrevision = "SELECT revisionoperacion FROM slc_stocksud_mail WHERE idmail = 1"; $mailrevision = mysql_query($query_mailrevision, $config) or die(mysql_error()); $row_mailrevision = mysql_fetch_assoc($mailrevision); $totalRows_mailrevision = mysql_num_rows($mailrevision); //mando el correo... $FromName = 'YACOPINI SUD'; $From = '<EMAIL>'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "<EMAIL>"; $mail->Username = "<EMAIL>"; $mail->Password = "<PASSWORD>"; $mail->Port = 25; $mail->IsHTML(true); $mail->FromName ='<NAME>'; $mail->FromName = $FromName; $mail->From = $From; if($totalRows_mailrevision > 0) { $maailrevisionoperacion = explode(";",$row_mailrevision['revisionoperacion']); for($j=0;$j<count($maailrevisionoperacion);$j++) { $mail->AddAddress($maailrevisionoperacion[$j]); } } $mail->Subject = 'Asignaciones automáticas'; $mail->Body = $cuerpo; $mail->Send(); } /*email llamado de revision de operacion*/ ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #666666; } .Estilo2 {color: #FF0000} .Yacopini { color: #707175; font-family: Arial, Helvetica, sans-serif; font-size: 36px; font-weight: bold; } .Sistema { color: #336699; font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; } .Estilo11 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } </style> <script type="text/javascript" src="js/stmenu.js"></script> </head> <body topmargin="0"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td> <table width="100%" height="480" border="0" cellpadding="0" cellspacing="0" id="principaltabla"> <tr> <td height="100" valign="middle"> <table width="100%" align="center" cellpadding="20" cellspacing="0"> <tr> <td width="50%" height="100" align="left" valign="middle"><span class="Yacopini">YACOPINI SUD </span></td> <td width="50%" align="right" valign="middle" class="Sistema">SISTEMA DE STOCK</td> </tr> </table> </td> </tr> <tr> <td height="2" colspan="2" align="center" valign="middle" bgcolor="#707175"></td> </tr> <tr> <td colspan="2" valign="top"><table width="100%" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="34" valign="bottom" bgcolor="#FFFFFF"><?php include("menu.php");?></td> </tr> <tr> <td height="250" valign="top"><table width="100%" height="300" cellpadding="0" cellspacing="0"> <tr> <td height="30" bgcolor="#FFFFFF" class="Estilo11"><table width="100%" cellspacing="2" cellpadding="8"> <tr> <td height="30" bgcolor="#CDCDCD" class="Estilo11"><strong>STOCK</strong></td> <td width="95" align="center" bgcolor="#CDCDCD" class="Estilo11"><strong><?php echo $row_usuario_sesion['nombre']; ?></strong></td> </tr> </table></td> </tr> <tr> <td height="220" valign="top" bgcolor="#FFFFFF"><table width="100%" height="100%" cellpadding="0" cellspacing="4"> <tr> <td valign="top" class="Estilo1"><?php if($mensaje != "") {echo $mensaje;}?></td> </tr> <?php if($mensajeVINduplicado != ''){ ?> <tr> <td valign="top" class="Estilo1">Para los siguientes VIN o chasis no se agregaron los registros porque ya se encuentran en la base de datos: <?php echo $mensajeVINduplicado?></td> </tr> <?php } ?> <?php if($mensajeModeloNoExiste != ''){ ?> <tr> <td valign="top" class="Estilo1">Para los siguientes VIN o chasis no se agregaron los registros porque, los modelos no se encuentran en la base de datos: <br><strong>Version &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VIN &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PR</strong><br> <?php echo $mensajeModeloNoExiste;?></td> </tr> <?php } ?> <?php if($mensajeSucursalNoExiste != ''){ ?> <tr> <td valign="top" class="Estilo1">Para los siguientes VIN o chasis no se agregaron los registros porque, las sucursales no se encuentran en la base de datos: <br><?php echo $mensajeSucursalNoExiste;?></td> </tr> <?php } ?> <?php if($mensajeSucursalVacio != ''){ ?> <tr> <td valign="top" class="Estilo1">Para los siguientes VIN o chasis no se agregaron los registros porque, las sucursales se encuentran vacías: <br><?php echo $mensajeSucursalVacio;?></td> </tr> <?php } ?> <?php if($mensajeDepositoNoExiste != ''){ ?> <tr> <td valign="top" class="Estilo1">Para los siguientes VIN o chasis se agregaron los registros, pero sin los depósitos, porque no se encontraban en la base de datos: <br><?php echo $mensajeDepositoNoExiste;?></td> </tr> <?php } ?> <?php if($mensajeColorNoExiste != ''){ ?> <tr> <td valign="top" class="Estilo1">Los colores de los siguientes codigos no se encuentran en la base de datos: <br> <strong>COLOR &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VIN</strong><br> <?php echo $mensajeColorNoExiste;?> </td> </tr> <?php if($mensajeVINVacio != ''){ ?> <tr> <td valign="top" class="Estilo1">Los siguientes registros con el campo programacion detallado no se agregaron porque tenian vacio el VIN o chasis: <?php echo $mensajeVINVacio?></td> </tr> <?php } ?> <?php if($mensajeProgramacionVacio != ''){ ?> <tr> <td valign="top" class="Estilo1">Los siguientes registros con VIN o chasis detallados no se agregaron porque ya se encuentran tenia vacio el campo programacion: <?php echo $mensajeProgramacionVacio?></td> </tr> <?php } ?> <?php if($mensajedepositosucursal != ''){ ?> <tr> <td valign="top" class="Estilo1">Los siguientes registros con VIN o chasis detallados código de depósito y código de sucursal tienen distintos el depósito y la sucursal: <?php echo $mensajedepositosucursal?></td> </tr> <?php } ?> <tr> <td valign="top" class="Estilo1"><div align="right"><a href="#"><img src="img/imprimir.gif" alt="Imprimir" width="26" height="23" border="0" onClick="window.print();"></a>&nbsp;&nbsp;</div></td> </tr> <?php } ?> </table> </td> </tr> </table></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </body> </html> <?php mysql_free_result($usuario_sesion); mysql_free_result($stock_orden); mysql_free_result($modelo); ?> <file_sep>/reservas_nuevo.php <?php require_once('Connections/config.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "index.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_config, $config); $query_modelos = "SELECT * FROM slc_stocksud_modelo ORDER BY modelo ASC"; $modelos = mysql_query($query_modelos, $config) or die(mysql_error()); $row_modelos = mysql_fetch_assoc($modelos); $totalRows_modelos = mysql_num_rows($modelos); mysql_select_db($database_config, $config); $query_colores = "SELECT * FROM slc_stocksud_color ORDER BY color ASC"; $colores = mysql_query($query_colores, $config) or die(mysql_error()); $row_colores = mysql_fetch_assoc($colores); $totalRows_colores = mysql_num_rows($colores); mysql_select_db($database_config, $config); $query_vendedores = "SELECT * FROM slc_stocksud_usuario WHERE idGrupo = 1 OR idGrupo = 2 OR idGrupo = 3 ORDER BY usuario ASC"; $vendedores = mysql_query($query_vendedores, $config) or die(mysql_error()); $row_vendedores = mysql_fetch_assoc($vendedores); $totalRows_vendedores = mysql_num_rows($vendedores); function fecha($fecha='', $sinHora=1, $separadorDias='-', $separadorHoras=':') { if ($fecha!='hoy') { if ($fecha!=''){ if ($fecha!='0000'.$separadorDias.'00'.$separadorDias.'00 00'.$separadorHoras.'00'.$separadorHoras.'00' && $fecha!='0000'.$separadorDias.'00'.$separadorDias.'00') { $fechaHora = split(' ', $fecha); $dmy = split($separadorDias, $fechaHora[0]); $dias = $dmy[2].$separadorDias.$dmy[1].$separadorDias.$dmy[0]; if(isset($fechaHora[1])){ $hms = split($separadorHoras, $fechaHora[1]); $horas = ' '.$hms[0].$separadorHoras.$hms[1]; //.$separadorHoras.(($hms[2]!='')?($hms[2]):('00')); } else {$horas = '';} return $dias.(($sinHora!=1)?($horas):('')); } else {return '';} } else {return '';} } else {return (($sinHora==1)?(date('d-m-Y')):(date('d-m-Y H:i')));} } mysql_select_db($database_config, $config); $query_bancos = "SELECT * FROM slc_stocksud_banco ORDER BY banco ASC"; $bancos = mysql_query($query_bancos, $config) or die(mysql_error()); $row_bancos = mysql_fetch_assoc($bancos); $totalRows_bancos = mysql_num_rows($bancos); mysql_select_db($database_config, $config); $query_cuotas = "SELECT * FROM slc_stocksud_cuota ORDER BY cuota ASC"; $cuotas = mysql_query($query_cuotas, $config) or die(mysql_error()); $row_cuotas = mysql_fetch_assoc($cuotas); $totalRows_cuotas = mysql_num_rows($cuotas); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>YACOPINI VW</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- #fondotabla { background-color:#CCCCCC; background-repeat: no-repeat; background-position: center center; } .Estilo1 { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #666666; } .Estilo2 { color: #333333; font-weight: bold; } --> </style> <script type="text/javascript" src="js/stmenu.js"></script> <script type="text/javascript"> <!-- function MM_callJS(jsStr) { //v2.0 return eval(jsStr) } function guardar(){ f=document.formGuardar; if(f.fecha.value == ''){ alert("Debe ingresar la fecha"); f.fecha.focus; return (0); } if(f.cliente.value == ''){ alert("Debe ingresar el cliente"); f.cliente.focus; return (0); } if(f.VIN2.value != ''){ if(f.VIN.value == '') { alert("Debe seleccionar el VIN de la lista"); f.VIN2.focus; return (0); } } if(f.VIN2.value == ''){ f.VIN.value = ''; } f.action = 'reservas_guardar.php'; f.submit(); } //--> </script> <!-- Calendario Pou up --> <link rel=stylesheet href="xc2/css/xc2_default.css" type="text/css"> <style type="text/css"> .weekend { font-family:verdana; font-size:11px; line-height:14px; width:23px; text-align:center; color:#cc0000; background-color:#f0f0f0; border:1px solid #f0f0f0; padding:1px; cursor:pointer; } </style> <script language="javascript" src="xc2/config/xc2_default.js"></script> <script language="javascript"> xcDateFormat="dd-mm-yyyy"; xcArrowPosition=1; xcFootTagSwitch=[1, 0, 0, 0, 0, 0, 0, 0]; //xcMods[1].order=1; xcMods[2].order=1; </script> <script language="javascript" src="xc2/script/xc2_inpage.js"></script> <script language="javascript"> <!-- //setRange("1", daysAfter(0),daysAfter(45)); setLoopWeek("1", "weekend", "", 1, 1, "Sat", "Sun"); //--> </script> <!-- /Calendario Pou up --> <!--ajax-autocomplete --> <script type="text/javascript" src="ajax-autocomplete/jquery.js"></script> <script type='text/javascript' src='ajax-autocomplete/jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="ajax-autocomplete/jquery.autocomplete.css" /> <script type="text/javascript"> $().ready(function() { $("#VIN2").autocomplete("reservas_buscar_vin.php", { width: 400, matchContains: true, //mustMatch: true, //minChars: 0, //multiple: true, //highlight: false, //multipleSeparator: ",", selectFirst: false }); $("#VIN2").result(function(event, data, formatted) { $("#VIN").val(data[1]); $("#stocknofacturado").val(data[2]); }); }); </script> <!--ajax-autocomplete --> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" id="ppal"> <tr> <td align="center" valign="top" id="fondotabla"> <div align="center"> <form method="POST" enctype="multipart/form-data" name="formGuardar" id="formGuardar"> <table width="95%" height="100%" align="center" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF"> <tr valign="middle" bgcolor="#CACACA"> <td colspan="4" class="Estilo1"><table width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="Estilo1"><strong>RESERVAS Nuevo</strong></td> </tr> </table></td> </tr> <tr valign="middle" bgcolor="#EFEFEF"> <td width="13%" class="Estilo1"><span class="Estilo2">DATOS</span></td> <td width="37%" class="Estilo1">&nbsp;</td> <td width="10%" class="Estilo1">&nbsp;</td> <td width="40%" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Fecha</strong></td> <td class="Estilo1"><input name="fecha" type="text" class="Estilo1" id="fecha" onFocus="showCalendar('1',this,this,'','holder',0,10,1);" value="<?php echo fecha('hoy'); ?>" size="10" maxlength="10" /> <img src="img/calendario.gif" alt="Calendario" width="14" height="16" onClick="showCalendar('1',document.formGuardar.fecha,document.formGuardar.fecha,'','holder',0,10,1)"></td> <td class="Estilo1"><strong>Cliente</strong></td> <td class="Estilo1"><input name="cliente" type="text" class="Estilo1" id="cliente" size="50" maxlength="255"></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Modelo</strong></td> <td class="Estilo1"><label for="idmodelo"></label> <select name="idmodelo" class="Estilo1" id="idmodelo"> <?php do { ?> <option value="<?php echo $row_modelos['idmodelo']?>"><?php echo $row_modelos['modelo']?></option> <?php } while ($row_modelos = mysql_fetch_assoc($modelos)); $rows = mysql_num_rows($modelos); if($rows > 0) { mysql_data_seek($modelos, 0); $row_modelos = mysql_fetch_assoc($modelos); } ?> </select></td> <td class="Estilo1"><strong>Vendedor</strong></td> <td class="Estilo1"><select name="idvendedor" class="Estilo1" id="idvendedor"> <?php do { ?> <option value="<?php echo $row_vendedores['idUsuario']?>"><?php echo $row_vendedores['usuario']?></option> <?php } while ($row_vendedores = mysql_fetch_assoc($vendedores)); $rows = mysql_num_rows($vendedores); if($rows > 0) { mysql_data_seek($vendedores, 0); $row_vendedores = mysql_fetch_assoc($vendedores); } ?> </select></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Color 1</strong></td> <td class="Estilo1"><select name="idcolor1" class="Estilo1" id="idcolor1"> <?php do { ?> <option value="<?php echo $row_colores['idcolor']?>"><?php echo $row_colores['color']?></option> <?php } while ($row_colores = mysql_fetch_assoc($colores)); $rows = mysql_num_rows($colores); if($rows > 0) { mysql_data_seek($colores, 0); $row_colores = mysql_fetch_assoc($colores); } ?> </select></td> <td class="Estilo1"><strong>Color 2</strong></td> <td class="Estilo1"><select name="idcolor2" class="Estilo1" id="idcolor2"> <?php do { ?> <option value="<?php echo $row_colores['idcolor']?>"><?php echo $row_colores['color']?></option> <?php } while ($row_colores = mysql_fetch_assoc($colores)); $rows = mysql_num_rows($colores); if($rows > 0) { mysql_data_seek($colores, 0); $row_colores = mysql_fetch_assoc($colores); } ?> </select></td> </tr> <tr valign="middle"> <td class="Estilo1"><strong>Color 3</strong></td> <td class="Estilo1"><select name="idcolor3" class="Estilo1" id="idcolor3"> <?php do { ?> <option value="<?php echo $row_colores['idcolor']?>"><?php echo $row_colores['color']?></option> <?php } while ($row_colores = mysql_fetch_assoc($colores)); $rows = mysql_num_rows($colores); if($rows > 0) { mysql_data_seek($colores, 0); $row_colores = mysql_fetch_assoc($colores); } ?> </select></td> <td class="Estilo1"><strong>VIN</strong></td> <td class="Estilo1"><input name="VIN2" type="text" class="Estilo1" id="VIN2" size="100" maxlength="200"> <input name="VIN" type="hidden" id="VIN" value="<?php echo $row_reserva['VIN']; ?>"> <input name="stocknofacturado" type="hidden" id="stocknofacturado"></td> </tr> <tr valign="middle"> <td class="Estilo1">Importe</td> <td class="Estilo1"><input name="importe" type="text" class="Estilo1" id="importe" size="7" maxlength="7"></td> <td align="center" valign="middle" class="Estilo1">&nbsp;</td> <td align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> <tr valign="middle"> <td height="20" class="Estilo1"><strong>Cr&eacute;dito</strong></td> <td class="Estilo1"><select name="idbanco" class="Estilo1" id="idbanco"> <option value="0"></option> <?php do { ?> <option value="<?php echo $row_bancos['idbanco']?>"><?php echo $row_bancos['banco']?></option> <?php } while ($row_bancos = mysql_fetch_assoc($bancos)); $rows = mysql_num_rows($bancos); if($rows > 0) { mysql_data_seek($bancos, 0); $row_bancos = mysql_fetch_assoc($bancos); } ?> </select> <br> <strong>Banco</strong></td> <td valign="middle" class="Estilo1"><select name="idcuota" class="Estilo1" id="idcuota"> <option value="0"></option> <?php do { ?> <option value="<?php echo $row_cuotas['idcuota']?>"><?php echo $row_cuotas['cuota']?></option> <?php } while ($row_cuotas = mysql_fetch_assoc($cuotas)); $rows = mysql_num_rows($cuotas); if($rows > 0) { mysql_data_seek($cuotas, 0); $row_cuotas = mysql_fetch_assoc($cuotas); } ?> </select> <br> <strong>Cuotas</strong></td> <td valign="middle" class="Estilo1"><input name="importesolicitado" type="text" class="Estilo1" id="importesolicitado" size="10" maxlength="7" onBlur="actualizar();"> <br> <LABEL for="checkbox_row_13"><strong>Importe Solicitado</strong></LABEL></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1"><input name="Guardar" type="button" class="Estilo1" id="Guardar" value="Guardar" onClick="guardar();"> &nbsp;&nbsp; <input name="Cancelar" type="button" class="Estilo1" id="Cancelar" onClick="window.close()" value="Cancelar"></td> </tr> <tr valign="middle"> <td colspan="4" align="center" valign="middle" class="Estilo1">&nbsp;</td> </tr> </table> <input type="hidden" name="MM_insert" value="formGuardar"> </form> </div></td> </tr> </table> </body> </html> <?php mysql_free_result($modelos); mysql_free_result($colores); mysql_free_result($vendedores); ?>
a1264d6011906c488f604939ad95fe05ba14b547
[ "HTML", "PHP" ]
42
PHP
noracosta/stocksud
90fdf860f059a01cbc3cf951e67db992e8d6dbb0
6f33e6613ea249f3b938c8bc0dbee532bca7ec1d
refs/heads/master
<file_sep>//patient class public class Patient { private String patientID; private Name name; private int age; private String gender; private Address address; private HealthInfo pHealth; private Doctor doctor; public Patient(String patientID, String firstName, String lastName, String gender, Address address, int age, int h, int w) { this.patientID = patientID; name = new Name(firstName, lastName); this.gender = gender; this.address = address; this.age = age; pHealth = new HealthInfo(h, w); } public String getPatientID(){ return patientID; } public int getWeight(){ return pHealth.getWeight(); } public int getHeight(){ return pHealth.getHeight(); } public String getFullName(){ return name.getFullName(); } public String getGender(){ return gender; } public int getAge(){ return age; } public Doctor getDoctor(){ return doctor; } public void attendBy(Doctor doc){ doctor = doc; } } }<file_sep>public class Doctor { private String staffID; private Name name; public Doctor(String staffID,String firstName,String lastName){ this.staffID = staffID; name = new Name(firstName,lastName); } public String getName(){ return name.getName(); } }
aff28ebeed03db2d8cb37c665201cd882f3dcefc
[ "Java" ]
2
Java
edtimer/OOP-all-labs
b3d6b70485f298d72b11088b119fa2e9ebbf6fad
dbfd98a7fd0fe34b6546233e620a82bffaf4c898
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LifExp { static { //You should put your codes in this section Like 'Liferay_Windows_payload.txt' } }
ce2c13699cf997140b356a183a8693c43324b65d
[ "Java" ]
1
Java
1522402210/CVE-2020-7961-payloads
d6c8f1d74bc2fe2c7b9d9157e71139ea339770b1
b67dc6119977c6863fa9f977bbdaec93ab99c5e6
refs/heads/master
<file_sep>#include <stdio.h> #include <math.h> /** * @param inputSignal (int[]): An integer array representing the input signal. * Replaced by the output (real, imaginary) * on completion of the subroutine * * @param outputComponents : The output (first 64 bytes represent magnitude, * next 64 bytes represent phase). To be used for * displaying the output on a spectrogram (stem-plot) * * @param isInverseFFT : 0 indicates FFT (time-domain to frequency-domain) * 1 indicates iFFT (frequency-domain to time-domain) * * Given a window of an input signal, performs the Fast-Fourier Transform (FFT) * on it using bit-reversal and the Danielson-Lanzcos Algorithm. The input should * be interleaved, with the real and complex parts at the even and odd indices, * respectively. * * NOTE: Each sample consists of real (even indices) and imaginary (odd indices) * parts. As such, the length of the input vector should be twice the number of * samples. However, the length of the output vector is equal to the number of * samples */ void doFFT(int* inputSignal, int* outputComponents, int isInverseFFT) { // Variable declaration int numSamples = 1024; int n = numSamples << 1; int currentMax = 2; int j = 1; int i = 1; int k = 1; /* Run the bit-reversal method. This swaps the values of the input * between pairs of indices which are bit-wise mirrored. For instance, * swaps the values at (1010b | 0101b, for a 16-bit input)*/ for(i = 1; i < n; i = i+2) { // As long as indices haven't been repeated if(j > i) { // Swap the real part of the input signal double swap = inputSignal[i-1]; inputSignal[i-1] = inputSignal[j-1]; inputSignal[j-1] = swap; // Swap the imaginary part of the input signal (redundant, all 0s!) swap = inputSignal[i]; inputSignal[i] = inputSignal[j]; inputSignal[j] = swap; } /* When performing the inverse-FFT, normalize the coefficients of * the frequency components with the number of samples (as defined * in the DFT synthesis equation) */ if(isInverseFFT == 1) { // Normalize the real and imaginary parts inputSignal[i-1] = inputSignal[i-1] >> 7; inputSignal[i] = inputSignal[i] >> 7; } /* Reset the reference index. Note: Adjacent indices (j & j+1, for j even) * denote the SAME sample (real, complex), so bit-reversal must maintain * the integrity of the sample (should not separate its components) */ int m = numSamples; while(m >= 2 && j > m) { j = j - m; m = m >> 1; } // Increment the index j = j + m; } /* Performs the FFT in-place using the Danielson-Lanczos method (frequency- * domain synthesis. The outer two loops compute the DTFT and sub-DTFTs * respectively. The inner loop performs the butterfly calculation (basic * FFT element) */ while (n > currentMax) { // Variable declaration int step = currentMax * 2; /* Note: Theta must be positive to find the inverse FFT * x[n] = Sigma_k: X[k] * e^(j*w*k*n) */ double theta = -(2 * M_PI)/currentMax; if(isInverseFFT == 1) theta = (-theta); double wtemp = sin(theta/2.0); double wpr = -2.0 * wtemp * wtemp; double wpi = sin(theta); double wr = 1.0; double wi = 0.0; // Outer loop. Computes the sub-DFT for (k = 1; k < currentMax; k += 2) { /* Performs the butterfly calculation as described below: * WWW.DSPguide.com/CH12/2.HTM (Remove capitals!) */ for (i = k; i <= n; i += step) { j = i + currentMax; double tempr = wr * inputSignal[j-1] - wi * inputSignal[j]; double tempi = wr * inputSignal[j] + wi * inputSignal[j-1]; inputSignal[j-1] = inputSignal[i-1] - tempr; inputSignal[j] = inputSignal[i] - tempi; inputSignal[i-1] += tempr; inputSignal[i] += tempi; } wtemp = wr; wr += wr * wpr - wi * wpi; wi += wi * wpr + wtemp * wpi; } // Increment the max iteration (upto N) currentMax = step; } /* Populate the output (magnitude, phase) vector. This output vector is only * relevant for the FFT (not the inverse FFT) and is ordered as follows: * Mag(0), Phase(0), ..., Mag(numSamples/2 - 1), Phase(numSamples/2 - 1) */ for(i = 0; i < n; i += 2) { // Compute the magnitude (length of the component vector) outputComponents[i] = sqrt((double) inputSignal[i] * (double) inputSignal[i] + (double) inputSignal[i+1] * (double) inputSignal[i+1]); // Take the logarithm of the magnitude if(outputComponents[i] != 0) outputComponents[i] = 7 * log(outputComponents[i]); // Compute the phase outputComponents[i+1] = 0; } } // Given a pointer to a memory location, writes a vector correponding to a sin-wave input void writeSinWave(int* inputSignal) { int NUM_SAMPLES = 1024; int n = 2 * NUM_SAMPLES; int i = 0; // Signal parameters double phaseIncrement = 2 * M_PI * 5000/NUM_SAMPLES; double currentPhase = 0; for( i = 0; i < n; i += 2) { // Write the real component (sin) inputSignal[i] = 100.0 * sin(currentPhase); currentPhase += phaseIncrement; // Write the imaginary component (0) inputSignal[i+1] = 0; } }
dae403dcce50fa4e769a0e73efe1d97b7b0f23d1
[ "C" ]
1
C
MrKerfuffle/Spectogram
2832b5e712d7e0c7e67fc3dfa2dde8ed6737bf90
67a44692aae3d49b516cccfa967dacba5729842b
refs/heads/master
<file_sep>#!/usr/bin/env bash svn log -r $2:$3 | grep $1 - <file_sep>#!/bin/bash svn diff -r $1:$2 --summarize <file_sep>#!/bin/bash svn diff -r $1:HEAD --summarize
5310e2c8fe36649f049edd33300e231a93f72258
[ "Shell" ]
3
Shell
TheLonelyGhost/WorkstationScripts
bfc654ba8ddb75738f786d9580a1f1818b3e598e
026bf0c45c979f10fe51e5fe098ace2e5f1fe439
refs/heads/master
<repo_name>SalithaUCSC/ToDoApp<file_sep>/README.md # ToDoApp ## How to create a simple ToDo application using Laravel, Ajax, jQuery and Bootstrap. Tasks are stored in a MYSQL database. ### Instructions to setup 1. Download the zip file. 2. Extract it and rename as **ToDoApp**. 3. Run XAMPP or WAMP and go to "http://localhost/phpmyadmin". 4. Create a new database called **laravel_todo** and select it. 5. Then import the SQL file included in the project folder called **laravel_todo.sql**. 6. Navigate to "C:\xampp\htdocs" folder (if you are using XAMPP) or "C:\wamp\www" folder (if you are using WAMP). 7. Now move the **ToDoApp** folder into it. 8. Open a **cmd** and go into the project folder using : cd "C:\xampp\htdocs\ToDoApp 9. Type **php artisan serve** in cmd. 9. Open the web browser and type the URL for the project as - "http://localhost:8000". ![todo](https://user-images.githubusercontent.com/23145752/38751381-90d89a94-3f75-11e8-91ba-39fa47f5dd6a.png) ![todo1](https://user-images.githubusercontent.com/23145752/38751511-fbc1f8b4-3f75-11e8-8d8c-b2093d12ffc6.png) ![todo2](https://user-images.githubusercontent.com/23145752/38751732-932000b6-3f76-11e8-8bc5-df040aa62c93.png) <file_sep>/laravel_todo.sql -- phpMyAdmin SQL Dump -- version 4.7.7 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Apr 13, 2018 at 08:14 PM -- Server version: 10.1.30-MariaDB -- PHP Version: 7.2.2 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: `laravel_todo` -- -- -------------------------------------------------------- -- -- Table structure for table `items` -- CREATE TABLE `items` ( `id` int(10) UNSIGNED NOT NULL, `item` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `items` -- INSERT INTO `items` (`id`, `item`, `created_at`, `updated_at`) VALUES (1, 'Girlfriend\'s b\'day gift', '2018-04-13 10:13:53', '2018-04-13 12:17:34'), (2, 'Mother\'s medical appointment', '2018-04-13 10:17:45', '2018-04-13 12:17:21'), (3, 'Anniversary celebrations', '2018-04-13 10:19:15', '2018-04-13 12:16:22'), (4, 'Buy a phone back cover', '2018-04-13 10:22:43', '2018-04-13 12:16:42'), (5, 'Create a web site', '2018-04-13 10:24:12', '2018-04-13 12:17:06'); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2018_04_13_153317_create_items_table', 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `items` -- ALTER TABLE `items` ADD PRIMARY KEY (`id`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `items` -- ALTER TABLE `items` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; 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 */;
ced9717a19be8a29d07fef8edf0e71dc18e7af76
[ "Markdown", "SQL" ]
2
Markdown
SalithaUCSC/ToDoApp
6e455d64dfab92a03bd7c863fa0c8aae19583e46
dca1b874105006604191c659207666d1da43fce8
refs/heads/master
<file_sep>package com.example.thomas.hangangn.adapter; import android.support.annotation.Nullable; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.thomas.hangangn.R; import com.example.thomas.hangangn.domain.Place; import com.example.thomas.hangangn.domain.Row; import com.example.thomas.hangangn.util.RxEventBus; import java.util.List; public class HomeAdapter extends BaseQuickAdapter<Place, BaseViewHolder> { public HomeAdapter(int layoutResId, @Nullable List<Place> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, Place item) { helper.setText(R.id.home_item_tv, item.getName()); Glide.with(mContext).load(item.getImg()).apply(new RequestOptions().centerCrop().autoClone()).into((ImageView) helper.getView(R.id.home_item_img)); RxEventBus.getInstance().getObservable().subscribe(data -> { if (data instanceof List) { List<Row> lists = (List<Row>) data; helper.setVisible(R.id.home_item_color, false); for (int i = 0; i < lists.size(); i++) { if (lists.get(i).getGIGU().equals(item.getPlaceName())) { helper.setVisible(R.id.home_item_color, true); } } } }); } } <file_sep>package com.example.thomas.hangangn.model; import java.util.ArrayList; import java.util.List; public class Address { private static List<String[]> addressLists; String[] placeName = {"강서", "광나루", "난지", "뚝섬", "망원", "반포", "양화", "여의도", "이촌", "잠원", "잠실"}; static String[] gangseo = {"46788", "46783", "2891"}; static String[] gwangnaru = {"46585", "46609", "1665"}; static String[] nanji = {"46777", "46766", "3142"}; static String[] ttukseom = {"46661", "46650", "2154"}; static String[] mangwon = {"46737", "46733", "3727"}; static String[] banpo = {"46727", "46717", "3702"}; static String[] yanghwa = {"46804", "46801", "2810"}; static String[] yeouido = {"46758", "46747", "3217"}; static String[] leechon = {"46695", "46687", "2645"}; static String[] jamwon = {"46678", "46671", "2551"}; static String[] jamsil = {"46639", "46623", "1812"}; public static List<String[]> get() { if (addressLists == null){ addressLists = new ArrayList<>(); addressLists.add(gangseo); addressLists.add(gwangnaru); addressLists.add(nanji); addressLists.add(ttukseom); addressLists.add(mangwon); addressLists.add(banpo); addressLists.add(yanghwa); addressLists.add(yeouido); addressLists.add(leechon); addressLists.add(jamwon); addressLists.add(jamsil); } return addressLists; } private Address() {} } <file_sep>package com.example.thomas.hangangn.domain data class Place( var img: Int? = null, var name: String? = null, var placeName:String?=null ) data class Filters( var placeName:String?=null )<file_sep>package com.example.thomas.hangangn.domain import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class ApiDomain( // @Expose @SerializedName("GeoInfoJokguWGS") var geoInfoWGS: GeoInfoJokguWGS?=null @Expose @SerializedName(value = "GeoInfoWGS" ,alternate = arrayOf( "GeoInfoBadmintonWGS","GeoInfoWrestlingWGS","GeoInfoLawnBowlingWGS","GeoInfoInlineSkateWGS", "GeoInfoJokguWGS","GeoInfoTrackWGS","GeoInfoWoodballWGS","GeoInfoXgameWGS","GeoInfoArcheryWGS", "GeoInfoParkGolfWGS","GeoInfoTennisWGS","GeoInfoGateballWGS","GeoInfoBasketballWGS","GeoInfoVolleyballWGS","GeoInfoSoccerWGS", "GeoInfoNatureStudyWGS","GeoInfoBaseballWGS","GeoInfoPlaygroundWGS", "GeoInfoDrinkWaterWGS","GeoInfoStoreWGS","GeoInfoParkParkingWGS","GeoInfoBicycleLendWGS","GeoInfoBicycleStorageWGS","GeoInfoParkOfficeWGS", "GeoInfoWaterLeisureWGS","GeoInfoWaterTrainingWGS","GeoInfoDuckBoatWGS","GeoInfoWaterTaxiWGS","GeoInfoPoolWGS", "GeoInfoWorkRoadWGS","GeoInfoInlineRoadWGS")) var geoInfoWGS: GeoInfoJokguWGS?=null ) data class GeoInfoJokguWGS( @Expose @SerializedName("list_total_count") var listTotalCount: Int, @Expose @SerializedName("RESULT") var rESULT: RESULT, @Expose @SerializedName("row") var row: List<Row> ) data class Row( @Expose @SerializedName("GIGU") var gIGU: String, @Expose @SerializedName("LAT") var lAT: String, @Expose @SerializedName("LNG") var lNG: String ) //data class Row( // @Expose var oBJECTID: Double, // var fTC: String, // var iDN: String, // @Expose @SerializedName("GIGU") var gIGU: String, // var jONAME: String, // var tEL: String, // var pIC: String, // var rMK: String, // var hORGCODE: String, // var mGENAM: String, // @Expose @SerializedName("LAT") var lAT: String, // @Expose @SerializedName("LNG") var lNG: String //) data class RESULT( @Expose @SerializedName("CODE") var cODE: String, @Expose @SerializedName("MESSAGE") var mESSAGE: String )<file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.thomas.hangangn" minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { targetCompatibility 1.8 sourceCompatibility 1.8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.2' implementation 'com.android.support:support-v4:28.0.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.android.support:design:28.0.0' implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.42' //rxjava implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' implementation 'io.reactivex.rxjava2:rxjava:2.1.13' implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar' implementation 'com.patloew.rxlocation:rxlocation:1.0.5' implementation group: 'org.jsoup', name: 'jsoup', version: '1.11.3' implementation "com.google.android.gms:play-services-maps:15.0.1" implementation "com.google.android.gms:play-services-location:15.0.1" implementation 'com.github.bumptech.glide:glide:4.8.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0' //direction implementation 'com.akexorcist:googledirectionlibrary:1.1.1' implementation 'com.github.jd-alexander:library:1.1.0' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'com.squareup.retrofit2:converter-scalars:2.3.0' implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1' implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version") { exclude group: 'org.jetbrains', module: 'annotations' } } repositories { jcenter() } apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' <file_sep>package com.example.thomas.hangangn.model; import com.example.thomas.hangangn.domain.ApiDomain; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface HangangService { @GET("75444b447674686f38357a784a7769/json/{apiKind}/1/5/") Call<ApiDomain> test(@Path("apiKind")String kind); } <file_sep>package com.example.thomas.hangangn.util; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; public class RxEventBus { private static RxEventBus mInstance; private PublishSubject<Object> mSubject; private RxEventBus() { mSubject = PublishSubject.create(); } public static RxEventBus getInstance() { if (mInstance == null) { mInstance = new RxEventBus(); } return mInstance; } public void sendEvent(Object object) { mSubject.onNext(object); } public Observable<Object> getObservable() { return mSubject; } } <file_sep>package com.example.thomas.hangangn.view.fragment; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.location.Address; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import com.akexorcist.googledirection.DirectionCallback; import com.akexorcist.googledirection.GoogleDirection; import com.akexorcist.googledirection.constant.TransportMode; import com.akexorcist.googledirection.model.Direction; import com.akexorcist.googledirection.model.Leg; import com.akexorcist.googledirection.model.Route; import com.akexorcist.googledirection.util.DirectionConverter; import com.example.thomas.hangangn.R; import com.example.thomas.hangangn.domain.ApiDomain; import com.example.thomas.hangangn.domain.Place; import com.example.thomas.hangangn.model.HangangService; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.patloew.rxlocation.RxLocation; import com.tbruyelle.rxpermissions2.RxPermissions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * A simple {@link Fragment} subclass. */ public class MapFragment extends Fragment { @BindView(R.id.fragment_map_map_view) MapView mMapView; Unbinder unbinder; GoogleMap mMap; @BindView(R.id.fragment_map_my_location) TextView myLocation; @BindView(R.id.fragment_map_arrive_location_auto_tv) AutoCompleteTextView arriveLocationTv; private RxLocation rxLocation; private LocationRequest locationRequest; private final CompositeDisposable disposable = new CompositeDisposable(); private String serverKey = "<KEY>"; private LatLng origin = new LatLng(37.7849569, -122.4068855); private LatLng destination = new LatLng(37.7814432, -122.4460177); String[] placeName = {"강서", "광나루", "난지", "뚝섬", "망원", "반포", "양화", "여의도", "이촌", "잠원", "잠실"}; String[] placeUniqueName = {"GIGU012", "GIGU002", "GIGU010", "GIGU003", "GIGU011", "GIGU005", "GIGU009", "GIGU007", "GIGU006", "GIGU004", "GIGU001"}; private List<LatLng> placeLocation= new ArrayList<>(); List<String> gigu = new ArrayList<>(); List<Place> places= new ArrayList<>(); LatLng myLatLng; public MapFragment() { // Required empty public constructor } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //액티비티 처음실행시 실행 mMapView.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_map, container, false); unbinder = ButterKnife.bind(this, view); for(int i=0;i<placeName.length;i++){ Place place = new Place(); place.setName(placeName[i]); place.setPlaceName(placeUniqueName[i]); places.add(place); } initPermission(); checkPlayServicesAvailable(); placeList(); return view; } private void placeList() { List<String> place = Arrays.asList( "배드민턴장", "씨름장", "론볼링장", "인라인스케이트장", "족구장", "트랙구장", "우드볼장", "X-GAME장", "국궁장", "파크골프장", "테니스장", "게이트볼장", "농구장", "배구장", "축구장", "자연학습장", "간이어린이야구장", "어린이놀이터", "식수대", "매점", "주차장", "자전거대여소", "자전거보관소", "공원안내소", "수상레저", "수상훈련장", "오리배선착장", "수상관광콜택시", "수영장", "보행자도로", "인라인도로"); List<String> placeUrl = Arrays.asList( "GeoInfoBadmintonWGS", "GeoInfoWrestlingWGS", "GeoInfoLawnBowlingWGS", "GeoInfoInlineSkateWGS", "GeoInfoJokguWGS", "GeoInfoTrackWGS", "GeoInfoWoodballWGS", "GeoInfoXgameWGS", "GeoInfoArcheryWGS", "GeoInfoParkGolfWGS", "GeoInfoTennisWGS", "GeoInfoGateballWGS", "GeoInfoBasketballWGS", "GeoInfoVolleyballWGS", "GeoInfoSoccerWGS", "GeoInfoNatureStudyWGS", "GeoInfoBaseballWGS", "GeoInfoPlaygroundWGS", "GeoInfoDrinkWaterWGS", "GeoInfoStoreWGS", "GeoInfoParkParkingWGS", "GeoInfoBicycleLendWGS", "GeoInfoBicycleStorageWGS", "GeoInfoParkOfficeWGS", "GeoInfoWaterLeisureWGS", "GeoInfoWaterTrainingWGS", "GeoInfoDuckBoatWGS", "GeoInfoWaterTaxiWGS", "GeoInfoPoolWGS", "GeoInfoWorkRoadWGS", "GeoInfoInlineRoadWGS"); ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, place); arriveLocationTv.setAdapter(stringArrayAdapter); arriveLocationTv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { parent.getItemAtPosition(position); int pos = place.indexOf(parent.getItemAtPosition(position)); initRetrofit(placeUrl.get(pos)); //System.out.println("position = "+parent.getItemAtPosition(position)+" po2 = "+place.indexOf(parent.getItemAtPosition(position))); // System.out.println(place.get(pos)+"를 누름 "+placeUrl.get(pos)); } }); } private void initDirectionMap(LatLng myLoca,LatLng arriveLoca) { GoogleDirection.withServerKey(serverKey) .from(arriveLoca) .to(myLoca) .transportMode(TransportMode.DRIVING) .execute(new DirectionCallback() { @Override public void onDirectionSuccess(Direction direction, String rawBody) { Snackbar.make(arriveLocationTv, "Success with status : " + direction.getStatus(), Snackbar.LENGTH_SHORT).show(); if (direction.isOK()) { // Do something Route route = direction.getRouteList().get(0); Leg leg = route.getLegList().get(0); ArrayList<LatLng> directionPositionList = leg.getDirectionPoint(); PolylineOptions polylineOptions = DirectionConverter.createPolyline(getActivity(), directionPositionList, 5, Color.RED); mMap.addPolyline(polylineOptions); LatLng southwest = route.getBound().getSouthwestCoordination().getCoordination(); LatLng northeast = route.getBound().getNortheastCoordination().getCoordination(); LatLngBounds bounds = new LatLngBounds(southwest, northeast); mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100)); Toast.makeText(getActivity(), "성공", Toast.LENGTH_SHORT).show(); } else { // Do something System.out.println("GoogleDirection Error = " + direction.getStatus()); Toast.makeText(getActivity(), "실패", Toast.LENGTH_SHORT).show(); } } @Override public void onDirectionFailure(Throwable t) { System.out.println("onDirectionFailure = " + t.getMessage()); } }); } private void initRetrofit(String choice) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); Retrofit retrofit = new Retrofit .Builder() .baseUrl("http://openapi.seoul.go.kr:8088") .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); HangangService hangangService = retrofit.create(HangangService.class); Call<ApiDomain> call = hangangService.test(choice); call.enqueue(new Callback<ApiDomain>() { @Override public void onResponse(Call<ApiDomain> call, Response<ApiDomain> response) { if (response.isSuccessful()) { //System.out.println(response.toString()); //System.out.println(response.body().getGeoInfoWGS().getRow().toString()); // RxEventBus.getInstance().sendEvent(response.body().getGeoInfoWGS().getRow()); gigu.clear(); placeLocation.clear(); for(int i=0;i<response.body().getGeoInfoWGS().getRow().size();i++){ Double lat = Double.valueOf(response.body().getGeoInfoWGS().getRow().get(i).getLAT()); Double lng = Double.valueOf(response.body().getGeoInfoWGS().getRow().get(i).getLNG()); LatLng arrive = new LatLng(lat,lng); placeLocation.add(arrive); //gigu.add(response.body().getGeoInfoWGS().getRow().get(i).getGIGU()); for(int j=0;j<places.size();j++){ if(response.body().getGeoInfoWGS().getRow().get(i).getGIGU().equals(places.get(j).getPlaceName())){ gigu.add(places.get(j).getName()); } } } // for(int i=0;i<gigu.size();i++){ // gigu.get(i).equals(placeName); // } String[] arr =gigu.toArray(new String[gigu.size()]); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setItems(arr, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mMap.clear(); System.out.println("beforeDirection = "+myLatLng+" : " + placeLocation.get(which)); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(placeLocation.get(which)); mMap.addMarker(markerOptions); mMap.animateCamera(CameraUpdateFactory.newLatLng(placeLocation.get(which))); //initDirectionMap(myLatLng,placeLocation.get(which)); arriveLocationTv.setText(""); arriveLocationTv.clearFocus(); View view = getActivity().getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } }); builder.create().show(); } } @Override public void onFailure(Call<ApiDomain> call, Throwable t) { } }); } private void initLocation() { rxLocation = new RxLocation(getActivity()); rxLocation.setDefaultTimeout(15, TimeUnit.SECONDS); this.locationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setNumUpdates(1); disposable.add(//gps 켜기 and 갖고오기 rxLocation.settings().checkAndHandleResolution(locationRequest) .flatMapObservable(this::getAddressObservable) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onAddressUpdate, throwable -> Log.e("MainPresenter", "Error fetching location/address updates", throwable)) ); } private void initMap() { mMapView.getMapAsync(new OnMapReadyCallback() { @SuppressLint("MissingPermission") @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMyLocationEnabled(true);//내위치보기 mMap.getUiSettings().setZoomControlsEnabled(true);//확대축소 버튼 mMap.getUiSettings().setCompassEnabled(true);//보통안뜨다 지도회전시 나침판뜸 mMap.getUiSettings().setRotateGesturesEnabled(false);//손가락 2개로 지도 회전 불가하게 mMap.setMinZoomPreference(14.5f); } }); } @SuppressLint("MissingPermission") private Observable<Address> getAddressObservable(boolean success) { if (success) { return rxLocation.location().updates(locationRequest) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(this::onLocationUpdate) .flatMap(this::getAddressFromLocation); } else { // this.onLocationSettingsUnsuccessful(); return rxLocation.location().lastLocation() .doOnSuccess(this::onLocationUpdate) .flatMapObservable(this::getAddressFromLocation); } } public void onAddressUpdate(Address address) { if (address != null) { myLocation.setText(getAddressText(address)); } } private String getAddressText(Address address) { String addressText = ""; final int maxAddressLineIndex = address.getMaxAddressLineIndex(); for (int i = 0; i <= maxAddressLineIndex; i++) { addressText += address.getAddressLine(i); if (i != maxAddressLineIndex) { addressText += "\n"; } } return addressText; } public void onLocationUpdate(Location location) { myLatLng= new LatLng(location.getLatitude(), location.getLongitude()); mMap.moveCamera(CameraUpdateFactory.newLatLng(myLatLng)); } private Observable<Address> getAddressFromLocation(Location location) { return rxLocation .geocoding() .fromLocation(location) .toObservable() .subscribeOn(Schedulers.io()); } @SuppressLint("CheckResult") private void initPermission() { RxPermissions rxPermissions = new RxPermissions(getActivity()); rxPermissions .requestEachCombined( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) .subscribe(permission -> { if (permission.granted) { //모든권한 허락함 //Log.e("granted","granted"); initMap(); initLocation(); } else if (permission.shouldShowRequestPermissionRationale) { //권한을 거부함 Toast.makeText(getActivity(), "권한을 수락해야만 사용할수 있어요ㅠ", Toast.LENGTH_SHORT).show(); getActivity().finish(); } else { //권한 다시보지 않기 체크 시 Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null); intent.setData(uri); startActivity(intent); //Log.e("granted","else"); } }); } private void checkPlayServicesAvailable() { final GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int status = apiAvailability.isGooglePlayServicesAvailable(getActivity()); if (status != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(status)) { apiAvailability.getErrorDialog(getActivity(), status, 1).show(); } else { // Snackbar.make(lastUpdate, "Google Play Services unavailable. This app will not work", Snackbar.LENGTH_INDEFINITE).show(); } } } @Override public void onStart() { super.onStart(); mMapView.onStart(); } @Override public void onStop() { super.onStop(); mMapView.onStop(); } @Override public void onResume() { super.onResume(); mMapView.onResume(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onLowMemory() { super.onLowMemory(); mMapView.onLowMemory(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); try { mMapView.onSaveInstanceState(outState); } catch (Exception e) { e.printStackTrace(); } } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } } <file_sep>package com.example.thomas.hangangn.view.fragment; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.example.thomas.hangangn.R; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * A simple {@link Fragment} subclass. */ public class FavoritesFragment extends Fragment { Unbinder unbinder; @BindView(R.id.fragment_favorites_WebView) WebView mWebView; public FavoritesFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_favorites, container, false); unbinder = ButterKnife.bind(this, view); mWebView.setWebViewClient(new MyWebViewClient()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setSupportZoom(false); mWebView.getSettings().setLoadWithOverviewMode(true); new FavoritesFragment.BackgroundWorker().execute(); return view; } private class BackgroundWorker extends AsyncTask<Void, Void, Void> { Handler uiHandler = new Handler(); @Override protected Void doInBackground(Void... voids) { try { Document htmlDocument = Jsoup.connect("http://hangang.seoul.go.kr/archives/category/office/hangang_news_office-n1").get(); Element element = htmlDocument.select("div[id=sub_centent]").first(); // replace body with selected element htmlDocument.body().empty().append(element.toString()); final String html = htmlDocument.toString(); uiHandler.post(new Runnable() { @Override public void run() { try { if (html != null) { mWebView.loadData(html, "text/html", "utf-8"); } } catch (NullPointerException e) { System.out.println(e.getMessage()); } } }); } catch (IOException e) { e.printStackTrace(); } return null; } } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { mWebView.loadUrl(url); return false; } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(request.getUrl().toString()); return false; } } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } }
b956d599a36f817e923a4293e50ed1ba140c555d
[ "Java", "Kotlin", "Gradle" ]
9
Java
thomas819/HanGangN
0f4cecb2f0941c7618c08b915176ed418a8fb2e4
25137adc1a68b653154a09b0c8044306f0cbab52
refs/heads/master
<file_sep>#include <iostream> using namespace std; #include <vector> #include <ctype.h> #include <sstream> #include <boost/filesystem.hpp> #ifndef SORTERS_H #define SORTERS_H //public: //The subjects that the scanned file could belong to. enum Subject { Chemistry, Economics, English, History, Physics, Precal }; //The categories the scanned file could fall under. enum Category { InClass, Notes, Handout, Worksheet}; int name_scanned_file(boost::filesystem::path file, string date, Subject subject, Category category); //private: string date_scanned_file(boost::filesystem::path file, string date); string label_subject_of_scanned_file(boost::filesystem::path file, Subject subject); string categorize_scanned_file(boost::filesystem::path file, Category category); string number_scanned_file(boost::filesystem::path file); #endif<file_sep>/*UNIT TESTING: fs::path trial_1 = fs::path("../../trial_1.png"); fs::path trial_2 = fs::path("../../trial_2.png"); fs::path trial_3 = fs::path(../../trial_3.png"); fs::path trial_4 = fs::path("../../trial_4.png"); Failing tests... too many characters name_scanned_file(trial_1, "1704099", Subject(Chemistry), Category(Handout)); name_scanned_file(trial_2, "170409#", Subject(Chemistry), Category(Handout)); name_scanned_file(trial_3, "1704009", Subject(Precal), Category(Handout)); name_scanned_file(trial_4, "1170409", Subject(Precal),Category(Handout)); date has a letter. name_scanned_file(trial_1, "1704.9", Subject(Chemistry), Category(Handout)); name_scanned_file(trial_2, "17040b", Subject(Chemistry), Category(Handout)); name_scanned_file(trial_3, "z17e09", Subject(Precal), Category(Handout)); name_scanned_file(trial_4, "1#7049", Subject(Precal), Category(Handout)); Passing tests... name_scanned_file(trial_1, " 170409 ", Subject(Chemistry), Category(Handout)); name_scanned_file(trial_2, " 170409", Subject(Chemistry), Category(Handout)); name_scanned_file(trial_3, "170409", Subject(Precal), Category(Handout)); name_scanned_file(trial_4, "170409", Subject(Precal), Category(Handout)); */ #include <iostream> #include <vector> #include <ctype.h> #include <sstream> #include "sorters.h" using namespace std; #include <boost/filesystem.hpp> namespace fs = boost::filesystem; //Returns files found in a directory vector<fs::path> find_scanned_files(fs::path search) { fs::directory_iterator end_itr; //default construction symbolizes the end. vector<fs::path> found; //Iterate through the directory and add it to the found results. for (fs::directory_iterator itr(search); itr != end_itr; ++itr) { found.push_back(itr->path()); } return found; } //This function when called displays each of the scanned files. void display_scanned_files(vector<fs::path> scanned_files) { for (int i = 0; i < scanned_files.size(); ++i) { cout << scanned_files[i] << endl; } } int main() { //The path we are searching for files in. fs::path scanned_file_folder ("/users/brycemacinnis/Documents/Agenda/Scanned"); vector<fs::path> scanned_files = find_scanned_files(scanned_file_folder); return 0; } <file_sep>#include "sorters.h" #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> namespace fs = boost::filesystem; //Check if a string is purely numeric. bool is_numeric(string input) { for (int i = 0; i < input.size(); i++) { //If a character is not a digit, it is no longer numeric. if (!isdigit(input[i])) return false; } //No characters found. return true; } //STEP 1: DATE THE FILE string date_scanned_file(fs::path file, string date) { //Remove all leading/trailing whitespace from the date. boost::algorithm::trim(date); //Run only if the date is given in six characters. YYMMDD. if (date.length() > 6) { return "date contains too many characters."; } //Run only if the date contains no letters. else if (!is_numeric(date)) { return "date contains letters"; } //Rename the file: path/date/extension. e.g. ~/Documents/170428.jpg else { return file.parent_path().string() + '/' + date + fs::extension(file); } } //STEP 2: LABEL THE SUBJECT OF THE FILE string label_subject_of_scanned_file(fs::path file, Subject subject) { //The default case if something breaks along the way. string label = "_Unlabelled"; switch (subject) { case Chemistry: label = "_Chemistry"; break; case Economics: label = "_Economics"; break; case English: label = "_English"; break; case History: label = "_History"; break; case Physics: label = "_Physics"; break; case Precal: label = "_Precal"; break; } return file.parent_path().string() + '/' + file.stem().string() + label + fs::extension(file); } //STEP 3: WHAT TYPE OF NOTE IS IT? string categorize_scanned_file(fs::path file, Category category) { //The default case if something breaks along the way. string label = "_Uncategorized"; switch (category) { case InClass: label = "_InClass"; break; case Notes: label = "_Notes"; break; case Handout: label = "_Handout"; break; case Worksheet: label = "_Worksheet"; break; } return file.parent_path().string() + '/' + file.stem().string() + label + fs::extension(file); } //STEP 4: WRITE THE NUMBER SUFFIX TO MAKE THE FILE UNIQUE. string number_scanned_file(fs::path file) { //Name it assuming there are no other identical files. string unique_file = file.parent_path().string() + '/' + file.stem().string() + "_1" + fs::extension(file); //The current ID of the file, will be iterated if it already exists. int i = 1; //If a file exists, keep adding 1 to the name until it no longer does. while (fs::exists(unique_file)) { //Add 1 to the ID. i++; //Parse the ID into a character std::stringstream parser; parser << i; //The ID as a string string id = parser.str(); //Name the file with the next ID unique_file = file.parent_path().string() + '/' + file.stem().string() + "_" + id + fs::extension(file); } //The name of the file that now has a unique id. return unique_file; } //STEP 5: BRING IT ALL TOGETHER int name_scanned_file(fs::path file, string date, Subject subject, Category category) { string dated_file = date_scanned_file(file, date); string labelled_file = label_subject_of_scanned_file(dated_file, subject); string categorized_file = categorize_scanned_file(labelled_file, category); string numbered_file = number_scanned_file(categorized_file); try { fs::rename(file, numbered_file); } catch (std::exception &ex) { std::cerr << "Could not rename file: \"" + numbered_file + "\"..." << std::endl; } return 0; }<file_sep>cmake_minimum_required(VERSION 3.7.2) project(butterFLY) #Include the headers include_directories(include) #Include all source files file(GLOB SOURCES "src/*.cpp") #Include necessary boost libraries find_package(Boost REQUIRED COMPONENTS filesystem system) include_directories( ${Boost_INCLUDE_DIRS} ) link_directories( ${Boost_LIBRARY_DIRS}) #Build Labella. add_executable(labella ${SOURCES}) target_link_libraries(labella ${Boost_LIBRARIES})
39180b1ce2693373d13aa63f24445a46f3df4567
[ "CMake", "C++" ]
4
C++
brycem24/butterFLY
38c47a63aa739ab877fa01d01a1694a4ec145d9f
f95ad3fdc6bfb44a5732a7a472eac41929647ae1
refs/heads/main
<file_sep>import { ObjectId } from 'mongodb' import { MenuItem, MutationCreateItemArgs, MutationDeleteItemArgs, MutationUpdateItemArgs } from '../../lib/graphql-generated' import { getCollection } from './db' const getMenu = async () => { const menu = await getCollection.then(c => c.find().toArray()) return menu.map(menuItem => ({ ...menuItem, id: menuItem._id + '' })) } const upsertMenuItem = async (args: MutationUpdateItemArgs | MutationCreateItemArgs): Promise<MenuItem> => { const menuItem = await dbUpsertMenuItem(args) if (!menuItem) throw new Error('Error updating item') return menuItem } const deleteMenuItem = async (args: MutationDeleteItemArgs): Promise<MenuItem> => { const id = new ObjectId(args.id) const collection = await getCollection const menu = await (await getCollection).findOne({ _id: id }) const menuItem = { ...menu, id: menu._id + '' } const deleteOp = await collection.deleteOne({ _id: id }) if (!deleteOp.result.ok) throw new Error('Error updating item') return menuItem } async function dbUpsertMenuItem(args: MutationUpdateItemArgs | MutationCreateItemArgs): Promise<MenuItem | void> { const _id = 'id' in args ? new ObjectId(args.id) : new ObjectId() const collection = await getCollection const updateOne = await collection.updateOne( { _id: new ObjectId(_id) }, { $set: args }, { upsert: true } ) const consolidatedId = _id ?? updateOne.upsertedId?._id if (consolidatedId) { const menuItem = await collection.findOne({ _id: consolidatedId }) return { ...menuItem, id: consolidatedId + '' } } } export const MenuRepository = { getMenu, deleteMenuItem: deleteMenuItem, createMenuItem: upsertMenuItem, updateMenuItem: upsertMenuItem } <file_sep>import { ApolloServer, gql } from 'apollo-server-micro' import { resolvers } from '../../lib/graphql/resolvers/resolvers' import { withSession } from '../../lib/session' const typeDefs = gql` type MenuItem { id: ID! name: String! category: String! price: Float! description: String! hot: Boolean special: Boolean } fragment MenuAttrs on MenuItem { id name category price description hot special } type Query { menu: [MenuItem]! } type Mutation { createItem( name: String! category: String! price: Float! description: String! hot: Boolean special: Boolean ): MenuItem updateItem( id: ID! name: String category: String price: Float description: String hot: Boolean special: Boolean ): MenuItem deleteItem(id: ID!): MenuItem } ` export const config = { api: { bodyParser: false } } const apolloServer = new ApolloServer({ typeDefs, resolvers, context: context => context }) const handler = withSession(apolloServer.createHandler({ path: '/api/graphql' })) export default handler <file_sep>import { ReactQueryDevtools } from 'react-query/devtools' import { QueryClientProvider } from 'react-query' import { queryClient } from '../lib/queryClient' // import { useGraphqlSub } from '../lib/graphql/useGraphqlSub' export function AppWrappers({ children }) { // useGraphqlSub() return ( <QueryClientProvider client={queryClient}> {children} <ReactQueryDevtools /> </QueryClientProvider> ) } <file_sep># TO DO: [ ] Need to do that<file_sep>module.exports = { schema: ['./lib/graphql/schema.graphql'], documents: ['./lib/graphql/documents/*.{graphql,js,ts,jsx,tsx}'], extensions: { endpoints: { default: { url: 'http://localhost:3000/api/graphql', headers: {} } } } } <file_sep>import { QueryClient } from 'react-query' import { persistWithLocalStorage } from 'react-query/persist-localstorage-experimental' export const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, cacheTime: 1000 * 60 * 60 * 24 // 24 hours } } }) persistWithLocalStorage(queryClient, { buster: 'v1' }) <file_sep>import { withSession } from '../../lib/session' export default withSession(async (req, res) => { const { username, password } = await req.body if (username === process.env.ADMIN_USER && password === process.env.ADMIN_PASS) { const user = { username: process.env.ADMIN_NAME } req.session.set('user', user) await req.session.save() return res.json(user) } res.status(401).json({ message: 'Wrong password' }) }) <file_sep>/* eslint-disable @typescript-eslint/no-var-requires */ const colors = require('tailwindcss/colors') module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { fontFamily: { sans: ['Lato', 'sans-serif'], serif: ['Merriweather', 'serif'], cursive: ['Niconne', 'cursive'] }, extend: { spacing: { 128: '32rem', 144: '36rem' }, borderRadius: { '4xl': '2rem' }, colors: { 'red-brand': '#d34c4c' } } }, variants: { extend: {} }, plugins: [] } <file_sep>import { createGlobalStyle } from 'styled-components' import tw from 'twin.macro' export const AppGlobalStyles = createGlobalStyle` body, html { color: #333; ${tw`font-sans`} } ` <file_sep>import { ClientError } from 'graphql-request' export function consoleErrorHandler(err: ClientError) { console.error(err) } <file_sep>export const GRAPHQL_PATH = 'api/graphql' export enum GRAPHQL_CHANNELS { NEW_MENU_ITEM = 'NEW_MENU_ITEM', DELETED_MENU_ITEM = 'DELETED_MENU_ITEM' } const host = typeof window === 'undefined' ? '' : window.location.host const wsProtocol = process.env.NODE_ENV === 'production' ? 'wss' : 'ws' export const GRAPHQL_SUB_PATH = `${wsProtocol}://${host}/api/graphql-sub` // SERVER MESSAGES export const SERVER_MESSAGES = { NOT_LOGGED: 'You must be looged to perform this action.' } export const META_TAGS = { AUTHOR: '<NAME> <<EMAIL>>', LANG: 'en-GB', TITLE: 'Next.js & friends', SITE_DESCRIPTION: 'Next.js & friends', KEYWORDS: 'nextjs reactjs graphql tailwindcss mongodb atlas', // OpenGraph Protocol: https://ogp.me/ // Used for facebook/whatsapp previews OG: { TITLE: 'This goes on top of the card', TYPE: 'website', URL: 'https://your-prod-address.com', IMAGE: 'https://your-prod-address.com/public/og-image.jpg', SITE_NAME: 'The root site name', DESCRIPTION: `What's it about` } } <file_sep>import { AuthenticationError } from 'apollo-server-micro' import { MutationCreateItemArgs, MutationDeleteItemArgs } from '../../../lib/graphql-generated' import { GRAPHQL_CHANNELS, SERVER_MESSAGES } from '../../constants' import { MenuRepository } from '../../db/MenuRepository' import { authenticationGate } from '../../session' import Socket from '../../socket' const socket = new Socket() const GlobalMutations = { async createItem(parent, args: MutationCreateItemArgs) { const menuItem = await MenuRepository.createMenuItem(args) if (menuItem.id) { socket.publish(GRAPHQL_CHANNELS.NEW_MENU_ITEM, menuItem) } return menuItem }, async updateItem(parent, args: MutationCreateItemArgs, context) { const { req, res } = context if (!authenticationGate(req, res)) { throw new AuthenticationError(SERVER_MESSAGES.NOT_LOGGED) } const menuItem = await MenuRepository.updateMenuItem(args) if (menuItem.id) { socket.publish(GRAPHQL_CHANNELS.NEW_MENU_ITEM, menuItem) } return menuItem }, async deleteItem(parent, args: MutationDeleteItemArgs, context) { const { req, res } = context if (!authenticationGate(req, res)) { throw new AuthenticationError(SERVER_MESSAGES.NOT_LOGGED) } const menuItem = await MenuRepository.deleteMenuItem(args) if (menuItem.id) { socket.publish(GRAPHQL_CHANNELS.NEW_MENU_ITEM, menuItem) } return menuItem } } export const resolvers = { Query: { async menu() { return MenuRepository.getMenu() } }, Mutation: GlobalMutations } <file_sep>/* eslint-disable @typescript-eslint/no-var-requires */ const clientEnvVars = [] const config = { webpack: (config, { isServer }) => { // Fixes packages that depend on fs/module module if (!isServer) { config.node = { fs: 'empty', module: 'empty' } } return config }, env: clientEnvVars.reduce( (acc, name) => { acc[name] = process.env[name] return acc }, { buildTime: +new Date() } ) } const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true' }) module.exports = withBundleAnalyzer(config) <file_sep>import { GraphQLResolveInfo, print } from 'graphql' import { GraphQLClient } from 'graphql-request' import { GraphQLError } from 'graphql-request/dist/types' import { Headers } from 'graphql-request/dist/types.dom' import gql from 'graphql-tag' export type Maybe<T> = T | null export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] } export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> } export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> } export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string String: string Boolean: boolean Int: number Float: number } export type MenuItem = { __typename?: 'MenuItem' id: Scalars['ID'] name: Scalars['String'] category: Scalars['String'] price: Scalars['Float'] description: Scalars['String'] hot?: Maybe<Scalars['Boolean']> special?: Maybe<Scalars['Boolean']> } export type Query = { __typename?: 'Query' menu: Array<Maybe<MenuItem>> } export type Mutation = { __typename?: 'Mutation' createItem?: Maybe<MenuItem> updateItem?: Maybe<MenuItem> deleteItem?: Maybe<MenuItem> } export type MutationCreateItemArgs = { name: Scalars['String'] category: Scalars['String'] price: Scalars['Float'] description: Scalars['String'] hot?: Maybe<Scalars['Boolean']> special?: Maybe<Scalars['Boolean']> } export type MutationUpdateItemArgs = { id: Scalars['ID'] name?: Maybe<Scalars['String']> category?: Maybe<Scalars['String']> price?: Maybe<Scalars['Float']> description?: Maybe<Scalars['String']> hot?: Maybe<Scalars['Boolean']> special?: Maybe<Scalars['Boolean']> } export type MutationDeleteItemArgs = { id: Scalars['ID'] } export type CreateMenuItemMutationVariables = Exact<{ name: Scalars['String'] category: Scalars['String'] description: Scalars['String'] price: Scalars['Float'] special?: Maybe<Scalars['Boolean']> hot?: Maybe<Scalars['Boolean']> }> export type CreateMenuItemMutation = { __typename?: 'Mutation' } & { createItem?: Maybe< { __typename?: 'MenuItem' } & Pick< MenuItem, 'id' | 'name' | 'category' | 'price' | 'description' | 'hot' | 'special' > > } export type UpdateMenuItemMutationVariables = Exact<{ id: Scalars['ID'] name?: Maybe<Scalars['String']> category?: Maybe<Scalars['String']> description?: Maybe<Scalars['String']> price: Scalars['Float'] special?: Maybe<Scalars['Boolean']> hot?: Maybe<Scalars['Boolean']> }> export type UpdateMenuItemMutation = { __typename?: 'Mutation' } & { updateItem?: Maybe< { __typename?: 'MenuItem' } & Pick< MenuItem, 'id' | 'name' | 'category' | 'price' | 'description' | 'hot' | 'special' > > } export type DeleteMenuItemMutationVariables = Exact<{ id: Scalars['ID'] }> export type DeleteMenuItemMutation = { __typename?: 'Mutation' } & { deleteItem?: Maybe< { __typename?: 'MenuItem' } & Pick< MenuItem, 'id' | 'name' | 'category' | 'price' | 'description' | 'hot' | 'special' > > } export type MenuQueryVariables = Exact<{ [key: string]: never }> export type MenuQuery = { __typename?: 'Query' } & { menu: Array< Maybe< { __typename?: 'MenuItem' } & Pick< MenuItem, 'id' | 'name' | 'category' | 'price' | 'description' | 'hot' | 'special' > > > } export const CreateMenuItemDocument = gql` mutation CreateMenuItem( $name: String! $category: String! $description: String! $price: Float! $special: Boolean $hot: Boolean ) { createItem( name: $name category: $category description: $description price: $price special: $special hot: $hot ) { id name category price description hot special } } ` export const UpdateMenuItemDocument = gql` mutation UpdateMenuItem( $id: ID! $name: String $category: String $description: String $price: Float! $special: Boolean $hot: Boolean ) { updateItem( id: $id name: $name category: $category description: $description price: $price special: $special hot: $hot ) { id name category price description hot special } } ` export const DeleteMenuItemDocument = gql` mutation DeleteMenuItem($id: ID!) { deleteItem(id: $id) { id name category price description hot special } } ` export const MenuDocument = gql` query menu { menu { id name category price description hot special } } ` export type SdkFunctionWrapper = <T>(action: () => Promise<T>) => Promise<T> const defaultWrapper: SdkFunctionWrapper = sdkFunction => sdkFunction() export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) { return { CreateMenuItem( variables: CreateMenuItemMutationVariables, requestHeaders?: Headers ): Promise<{ data?: CreateMenuItemMutation | undefined extensions?: any headers: Headers status: number errors?: GraphQLError[] | undefined }> { return withWrapper(() => client.rawRequest<CreateMenuItemMutation>(print(CreateMenuItemDocument), variables, requestHeaders) ) }, UpdateMenuItem( variables: UpdateMenuItemMutationVariables, requestHeaders?: Headers ): Promise<{ data?: UpdateMenuItemMutation | undefined extensions?: any headers: Headers status: number errors?: GraphQLError[] | undefined }> { return withWrapper(() => client.rawRequest<UpdateMenuItemMutation>(print(UpdateMenuItemDocument), variables, requestHeaders) ) }, DeleteMenuItem( variables: DeleteMenuItemMutationVariables, requestHeaders?: Headers ): Promise<{ data?: DeleteMenuItemMutation | undefined extensions?: any headers: Headers status: number errors?: GraphQLError[] | undefined }> { return withWrapper(() => client.rawRequest<DeleteMenuItemMutation>(print(DeleteMenuItemDocument), variables, requestHeaders) ) }, menu( variables?: MenuQueryVariables, requestHeaders?: Headers ): Promise<{ data?: MenuQuery | undefined extensions?: any headers: Headers status: number errors?: GraphQLError[] | undefined }> { return withWrapper(() => client.rawRequest<MenuQuery>(print(MenuDocument), variables, requestHeaders)) } } } export type Sdk = ReturnType<typeof getSdk> export type ResolverTypeWrapper<T> = Promise<T> | T export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = { fragment: string resolve: ResolverFn<TResult, TParent, TContext, TArgs> } export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = { selectionSet: string resolve: ResolverFn<TResult, TParent, TContext, TArgs> } export type StitchingResolver<TResult, TParent, TContext, TArgs> = | LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs> export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> = | ResolverFn<TResult, TParent, TContext, TArgs> | StitchingResolver<TResult, TParent, TContext, TArgs> export type ResolverFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => Promise<TResult> | TResult export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>> export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult> export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs> resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs> } export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs> resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs> } export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> = | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs> | SubscriptionResolverObject<TResult, TParent, TContext, TArgs> export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>) | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs> export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = ( parent: TParent, context: TContext, info: GraphQLResolveInfo ) => Maybe<TTypes> | Promise<Maybe<TTypes>> export type IsTypeOfResolverFn<T = {}, TContext = {}> = ( obj: T, context: TContext, info: GraphQLResolveInfo ) => boolean | Promise<boolean> export type NextResolverFn<T> = () => Promise<T> export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = ( next: NextResolverFn<TResult>, parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult> /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { MenuItem: ResolverTypeWrapper<MenuItem> ID: ResolverTypeWrapper<Scalars['ID']> String: ResolverTypeWrapper<Scalars['String']> Float: ResolverTypeWrapper<Scalars['Float']> Boolean: ResolverTypeWrapper<Scalars['Boolean']> Query: ResolverTypeWrapper<{}> Mutation: ResolverTypeWrapper<{}> } /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = { MenuItem: MenuItem ID: Scalars['ID'] String: Scalars['String'] Float: Scalars['Float'] Boolean: Scalars['Boolean'] Query: {} Mutation: {} } export type MenuItemResolvers< ContextType = any, ParentType extends ResolversParentTypes['MenuItem'] = ResolversParentTypes['MenuItem'] > = { id?: Resolver<ResolversTypes['ID'], ParentType, ContextType> name?: Resolver<ResolversTypes['String'], ParentType, ContextType> category?: Resolver<ResolversTypes['String'], ParentType, ContextType> price?: Resolver<ResolversTypes['Float'], ParentType, ContextType> description?: Resolver<ResolversTypes['String'], ParentType, ContextType> hot?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType> special?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type QueryResolvers< ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query'] > = { menu?: Resolver<Array<Maybe<ResolversTypes['MenuItem']>>, ParentType, ContextType> } export type MutationResolvers< ContextType = any, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation'] > = { createItem?: Resolver< Maybe<ResolversTypes['MenuItem']>, ParentType, ContextType, RequireFields<MutationCreateItemArgs, 'name' | 'category' | 'price' | 'description'> > updateItem?: Resolver< Maybe<ResolversTypes['MenuItem']>, ParentType, ContextType, RequireFields<MutationUpdateItemArgs, 'id'> > deleteItem?: Resolver< Maybe<ResolversTypes['MenuItem']>, ParentType, ContextType, RequireFields<MutationDeleteItemArgs, 'id'> > } export type Resolvers<ContextType = any> = { MenuItem?: MenuItemResolvers<ContextType> Query?: QueryResolvers<ContextType> Mutation?: MutationResolvers<ContextType> } /** * @deprecated * Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config. */ export type IResolvers<ContextType = any> = Resolvers<ContextType> export const namedOperations = { Query: { menu: 'menu' }, Mutation: { CreateMenuItem: 'CreateMenuItem', UpdateMenuItem: 'UpdateMenuItem', DeleteMenuItem: 'DeleteMenuItem' } } <file_sep>/* eslint-disable @typescript-eslint/no-var-requires */ const PubNub = require('pubnub') // PubNub Integration // turned off class Socket { client = null constructor() { const cfg = { publishKey: '', subscribeKey: '', uuid: '' } // only on server if (typeof window === 'undefined') { cfg.secretKey = process.env.WS_SERVER_KEY } // this.client = new PubNub(cfg) } publish(channel, data) { // return this.client.publish({ // channel: channel, // message: data // }) } subscribe(channels, cb) { this.client.subscribe({ channels }) this.client.addListener({ message: function (m) { const channel = m.channel // Channel on which the message was published const channelGroup = m.subscription // Channel group or wildcard subscription match (if exists) const pubTT = m.timetoken // Publish timetoken const msg = m.message // Message payload const publisher = m.publisher // Message publisher cb({ channel, data: msg }) } }) } unsubscribe() { // this.client?.unsubscribeAll?.() } } module.exports = Socket <file_sep>// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions import { withIronSession } from 'next-iron-session' import { SERVER_MESSAGES } from './constants' export function withSession(handler) { return withIronSession(handler, { password: <PASSWORD>.<PASSWORD>COOKIE_<PASSWORD>, cookieName: 'app_session', cookieOptions: { // the next line allows to use the session in non-https environments like // Next.js dev mode (http://localhost:3000) secure: process.env.NODE_ENV === 'production' } }) } export function authApiHandler(handler) { return withSession(async function (...args) { const [req, res] = args const user = req.session.get('user') if (!user) { return res.status(401).json({ message: SERVER_MESSAGES.NOT_LOGGED }) } return handler(...args) }) } export function authenticationGate(req, res) { const user = req.session.get('user') if (!user) { // res.status(401).json({ // message: 'You must be looged to perform this action.' // }) return false } return true } export const withUserProps = withSession(async function ({ req, res }) { // Get the user's session based on the request const user = req.session.get('user') if (!user) { return { redirect: { destination: '/login', permanent: true } } } return { props: { user } } }) <file_sep>ADMIN_NAME=John ADMIN_USER=admin ADMIN_PASS=<PASSWORD> DB_CLUSTER_NAME= DB_NAME= DB_PASS= WS_SERVER_KEY= SECRET_COOKIE_PASSWORD=<file_sep>This is a starter for new [Next.js](https://nextjs.org/) projects, easily deployable to [vercel](vercel.com/), with GraphQL (with codegen!), tailwind (twin.macro) and friends working out of the box. Note that besides Next.js and twin.macro, all other libraries are easily replaced or taken off. # What is included - [Next.js@^10](https://nextjs.org/) - [twin.macro](https://github.com/ben-rogerson/twin.macro/) - [GraphQL (Apollo server)](https://www.apollographql.com/docs/apollo-server/v1/servers/micro/) - [react-query](https://react-query.tanstack.com/) - [react-hook-form](https://react-hook-form.com/) - [antd](https://ant.design/) - [Cloud MongoDB integration](https://cloud.mongodb.com) # VS Code integration It is important to have some extensions so your intellisense works properly. There are configuration files on the project that makes them work properly. - GraphQL (from GraphQL Foundation) - Tailwind CSS Intellisense (from <NAME>) - twin.macro Auto Complete (from <NAME>) - optional: Tailwind Docs (<NAME>) # Getting started - Create file `.env.local` based on `.env.example` - Customize meta tags at: lib/constants.ts@META_TAGS - Customize your schema.graphql Project structure: ``` ├── codegen.yml -- codegen config (https://graphql-code-generator.com/) ├── components │ ├── AppHead.tsx -- <head /> tag │ ├── AppWrappers.js │ ├── GlobalStyles.js -- global styles │ ├── Header.js -- App Header component │ └── styled.js -- Some styled components ├── graphql.config.js -- config, ├── lib │ ├── api │ │ └── handlers.ts -- common handlers │ ├── constants.ts -- app constants │ ├── db │ │ ├── db.ts -- db wrappers │ │ └── MenuRepository.ts -- repository │ ├── graphql │ │ ├── documents │ │ │ ├── mutations.graphql │ │ │ └── query.graphql │ │ ├── graphqlClient.ts │ │ ├── resolvers │ │ │ └── resolvers.ts │ │ ├── schema.graphql │ │ └── useGraphqlSub.ts │ ├── graphql-generated.ts │ ├── hooks │ │ └── data-hooks.ts │ ├── queryClient.ts │ ├── session.js -- session utils │ └── socket.js -- websocket utils ├── next.config.js ├── next-env.d.ts ├── package.json ├── pages │ ├── admin │ │ └── index.js │ ├── api │ │ ├── graphql.ts │ │ ├── login.js │ │ └── logout.ts │ ├── _app.js │ ├── _document.js │ ├── index.js │ ├── login.js │ └── logout.js ├── public │ └── favicon.ico ├── README.md ├── __server__socket-io-trial.js ├── tailwind.config.js ├── TODO.md ├── tsconfig.json ├── yarn-error.log └── yarn.lock ``` This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file. [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`. The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/import?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. <file_sep>import { MongoClient, WithId } from 'mongodb' import { MenuItem } from '../../lib/graphql-generated' const DB = process.env.DB_NAME const DB_PASS = process.env.DB_PASS const CLUSTER_NAME = process.env.DB_CLUSTER_NAME const uri = `mongodb+srv://${CLUSTER_NAME}:${DB_PASS}@${CLUSTER_NAME}.8qfwh.mongodb.net/${DB}?retryWrites=true&w=majority` const COLLECTIONS = { menu: 'menu' } // exports export const dbClient = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }) export const getDb = dbClient.connect().then(client => client.db(DB)) export type CollectionMenuItem = WithId<MenuItem> export const getCollection = getDb.then(db => db.collection<CollectionMenuItem>(COLLECTIONS.menu)) <file_sep>import * as next from 'next' import 'next/types/global' import { Session } from 'next-iron-session' declare type AppNextApiRequest = next.NextApiRequest & { session: Session } <file_sep>import { GraphQLClient } from 'graphql-request' import { GRAPHQL_PATH } from '../constants' export const graphqlClient = new GraphQLClient(`${globalThis?.location?.origin}/${GRAPHQL_PATH}`, { headers: {} }) <file_sep>import { throttle } from "lodash" import { useEffect, useMemo, useRef, useState } from "react" export function useScrolledPastHeader (headerElementSelector: string) { const [scrolledPast, setScrolledPast] = useState<boolean>(false) const headerRef = useRef<HTMLElement>( typeof document !== 'undefined' ? document.querySelector(headerElementSelector) : null ) const onScroll = useMemo(() => { return throttle(() => { const headerElement = headerRef.current if (headerElement) { setScrolledPast(window.pageYOffset > headerElement.clientHeight) } else { headerRef.current = document.querySelector(headerElementSelector) } }, 200) }, []) useEffect(() => { window.addEventListener('scroll', onScroll) window.addEventListener('resize', onScroll) onScroll() return () => { window.removeEventListener('scroll', onScroll) window.removeEventListener('resize', onScroll) } // eslint-disable-next-line react-hooks/exhaustive-deps }, []) return scrolledPast }<file_sep>import { useEffect } from 'react' import { queryClient } from '../queryClient' import { MenuItem } from '../../lib/graphql-generated' import { GRAPHQL_CHANNELS } from '../constants' import Socket from '../socket' export function useGraphqlSub() { useEffect(() => { if (typeof window === 'undefined') { return } const socket = new Socket() socket.subscribe(Object.values(GRAPHQL_CHANNELS), (data: SubscriptionResponse) => { switch (data.channel) { case GRAPHQL_CHANNELS.NEW_MENU_ITEM: queryClient.fetchQuery('MenuDocument') break case GRAPHQL_CHANNELS.DELETED_MENU_ITEM: queryClient.fetchQuery('MenuDocument') break default: break } }) return () => socket.unsubscribe() }, []) } type SubscriptionResponse = | { channel: GRAPHQL_CHANNELS.NEW_MENU_ITEM newMenuItem: MenuItem } | { channel: GRAPHQL_CHANNELS.DELETED_MENU_ITEM; deleteMenuItem: MenuItem } <file_sep>import { withSession } from '../../lib/session' import type { NextApiResponse } from 'next' import { AppNextApiRequest } from '../../next-env' export default withSession((req: AppNextApiRequest, res: NextApiResponse): void => { req.session.destroy() res.redirect('/') }) <file_sep>import Link from 'next/link' import styled from 'styled-components' import tw from 'twin.macro' export default function Header({ isAdmin }) { return ( <header id="main-header" tw="bg-yellow-200 p-4 pt-8 shadow-md"> <div tw="container mx-auto "> <div tw="flex flex-col text-center sm:flex-row"> <Logo tw="text-5xl flex-1 font-cursive text-center sm:text-left mb-6">My App</Logo> {isAdmin ? ( <div tw="text-2xl self-center mr-4 md:mt-4">ADMIN</div> ) : ( <div tw="flex flex-col justify-between text-2xl mb-4"> <Link href="/admin"> <span tw="text-blue-500 cursor-pointer hover:(underline text-blue-800)">Login</span> </Link> </div> )} </div> </div> </header> ) } const Logo = styled.h1` text-shadow: 1px 1px 1px black; ${tw`text-red-brand`} ` <file_sep>import { useMutation, useQuery } from 'react-query' import { queryClient } from '../queryClient' import { CreateMenuItemDocument, DeleteMenuItemDocument, MenuDocument, MenuItem, MutationCreateItemArgs, MutationDeleteItemArgs, MutationUpdateItemArgs, UpdateMenuItemDocument } from '../../lib/graphql-generated' import { consoleErrorHandler } from '../api/handlers' import { graphqlClient } from '../graphql/graphqlClient' export function useMenu(sortField = 'name') { return useQuery<MenuItem[], unknown>('MenuDocument', () => { return graphqlClient .request(MenuDocument) .then(d => { return d.menu.sort((c, p) => { if (c[sortField] < p[sortField]) return -1 return 1 }) }) .catch(consoleErrorHandler) }) } export function useCreateMenuItem() { return useMutation<MutationCreateItemArgs, unknown, MutationCreateItemArgs>(args => graphqlClient .request(CreateMenuItemDocument, args) .catch(consoleErrorHandler) .then(() => queryClient.fetchQuery('MenuDocument')) ) } export function useUpdateMenuItem() { return useMutation<MutationUpdateItemArgs, unknown, MutationUpdateItemArgs>(args => graphqlClient .request(UpdateMenuItemDocument, args) .catch(consoleErrorHandler) .then(() => queryClient.fetchQuery('MenuDocument')) ) } export function useDeleteMenuItem() { return useMutation<MutationDeleteItemArgs, unknown, MutationDeleteItemArgs>(args => graphqlClient .request(DeleteMenuItemDocument, args) .catch(consoleErrorHandler) .then(() => queryClient.fetchQuery('MenuDocument')) ) } <file_sep>import Header from '../../components/Header' import AppHead from '../../components/AppHead' import MenuForm from '../../components/MenuForm' import { withUserProps } from '../../lib/session' import { AppWrappers } from '../../components/AppWrappers' import 'antd/dist/antd.css' export const getServerSideProps = withUserProps export default function Admin() { return ( <AppWrappers> <AppHead preventSeo /> <Header isAdmin /> <MenuForm /> </AppWrappers> ) }
fa87bf246f1711688dae2c4e6310b521fe70f9bb
[ "JavaScript", "TypeScript", "Markdown", "Shell" ]
27
TypeScript
melloc01/nextjs-twin-graphql-starter
46c1e96fb506f26dfc723c2bdf5f71bd190c9165
383e3ea0847654bf58de1b5443e3ebf87e894c5c
refs/heads/master
<file_sep><?php /** * QuickSurveys extension - Displays configured surveys on Mobile and Desktop. * * For more info see http://mediawiki.org/wiki/Extension:QuickSurveys * * @file * @ingroup Extensions * @author <NAME>, <NAME>, <NAME>, <NAME> 2015 */ if ( function_exists( 'wfLoadExtension' ) ) { wfLoadExtension( 'QuickSurveys' ); // Keep i18n globals so mergeMessageFileList.php doesn't break $wgMessagesDirs['QuickSurveys'] = __DIR__ . '/i18n'; return; } else { die( 'This version of the QuickSurveys extension requires MediaWiki 1.25+' ); } <file_sep># creepy-guacamole
2eeeef7acdff9c04ab50e9de843d4b340164ce2d
[ "Markdown", "PHP" ]
2
PHP
rmoen/creepy-guacamole
fef6a8e4e08ba0a63a2ba7c760d8208c09fb453d
1540fb4484cad7f2b4c392c3f7d8aac81a7370ff
refs/heads/master
<repo_name>ipfaffy/lastfm-obs<file_sep>/README.md ## LastFM-OBS This package will get the currently playing song and output it to stdout. You can redirect it to a file and ingest it using OBS to add it to your video. It requires the environment variables `LASTFM_APIKEY`, `LASTFM_APISECRET`, and `LASTFM_USER` be set. Example compile and usage: ``` $ git clone <EMAIL>:ipfaffy/lastfm-obs.git && cd lastfm-obs $ glide install $ go build $ sudo cp lastfm-obs /usr/local/bin/. $ while true; do lastfm-obs > /tmp/currentSong; sleep 5; done ``` <file_sep>/lastfm-obs.go package main import ( "fmt" "os" "github.com/shkh/lastfm-go/lastfm" ) func checkenv(key, fallback string) string { value := os.Getenv(key) if len(value) == 0 { return fallback } return value } func main() { ApiKey := checkenv("LASTFM_APIKEY", "none_provided") ApiSecret := checkenv("LASTFM_APISECRET", "none_provided") user := checkenv("LASTFM_USER", "none_provided") api := lastfm.New(ApiKey, ApiSecret) p := lastfm.P{"user": user} r, err := api.User.GetRecentTracks(p) if err != nil { fmt.Println(err) return } for _, track := range r.Tracks[:1] { fmt.Println("Name: " + track.Name) fmt.Println("Artist: " + track.Artist.Name) } }
76fb631903db3008345b0336c97ce425991ac299
[ "Markdown", "Go" ]
2
Markdown
ipfaffy/lastfm-obs
3228896fa91e6172a6e44fff17e6ff144cafa328
a37bbf014b532b7f9bc7bee22c1e78d53cfd4e7d
refs/heads/master
<file_sep>from gym_qubit.envs.qsedql_env import QuantumSzilardEngineDQLENV
419737951c4bba38cfc53d19f685eb746a6058bd
[ "Python" ]
1
Python
ruiw0509/gym-qse
9bbd183dd20bd87de7d2eb83feec6ef0f802b2f9
8e06e6100b5e70d718f155891bb1397e2c6e5d9e
refs/heads/master
<file_sep>from flask import Flask from roku import Roku app = Flask(__name__) roku = Roku('192.168.1.2') # change to the IP address of your Roku TV @app.route("/") def hello(): return "Hello World!" @app.route("/up") def volup(): for lvls in range(5): roku.volup() return "louder!" @app.route("/down") def voldn(): for lvls in range(5): roku.voldn() return "Shhh..." @app.route("/power") def power_tog(): roku.power() return "power" <file_sep># Roku Volume controller though SmartThings and Google Home I really didn't want to use a remote to turn the volume up or down on my Roku TV. There is a few dependances you need to meet to get this to work: 1. Roku TV (duh.) 2. Local Server (in my case a RaspberryPi but, anything on the same network as the TV and can run python) 3. Python * Flask * Roku 4. SmartThings 5. Google Home ## Setup Python First, we need the TV's IP address, the Local Server's IP address, and your public IP. Next, lets get python ready. On debian / Ubuntu you can: `sudo apt update` `sudo apt install python python-dev python-pip -y` `sudo pip install flask roku` Next we need to add a little something to roku's core.py `nano +30 /usr/local/lib/python3.4/dist-packages/roku/core.py` change this: ``` 'literal': 'Lit' } ``` to: ``` 'literal': 'Lit', 'power': 'Power', 'volup' : 'VolumeUp', 'voldn' : 'VolumeDown' } ``` Finally, for python lets run a detached Flask instance in the background. ` FLASK_APP=listener.py flask run --host=0.0.0.0 ` ## Setup SmartThings WebCore <NAME> once said, "Something something shoulders of giants". So, lets go stand on some giants! [You must complete all of these steps.](https://wiki.webcore.co/#Installing_webCoRE) * GitHub [Install](https://wiki.webcore.co/GitHub_Install) or [Manual Install](https://wiki.webcore.co/Manual_Install) of webCoRE source code into the SmartThings Cloud * [Enable webCoRE OAuth](https://wiki.webcore.co/Enable_webCoRE_OAuth) in the SmartThings cloud * [Install webCoRE](https://wiki.webcore.co/Install_webCoRE) in the SmartThings mobile app * [Enabling webCoRE dashboard](https://wiki.webcore.co/Enabling_webCoRE_dashboard) * [Enable webCoRE on Another Device](https://wiki.webcore.co/Enable_webCoRE_on_Another_Device) ## Create SmartThings Virtual Devices Login it to the SmartThings IDE: [https://graph.api.smartthings.com/](https://graph.api.smartthings.com/) 1. Click My Devices and click new device. 2. Fill out the form make sure the type is simulated switch. Set the name to Roku_Volume_Up 3. Click My Devices and click new device. 4. Fill out the form make sure the type is simulated switch. Set the name to Roku_Volume_Down 5. Click My Devices and click new device. 6. Fill out the form make sure the type is simulated switch. Set the name to Power ## Setup Our SmartThings SmartApp Login to the SmartThings Dashboard: [https://webcore.co/re](https://webcore.co/re) You need to create two pistons, one for Volume Up and Volume Down. ``` ************************************************************/ /* Volume Up */ /**************************************************************/ execute if Roku_Volume_Up's switch physically changes to on then with Roku_Volume_Up do Make a GET request to http://flask_ip_address:5000/up with type JSON; end with; end if; with Roku_Volume_Up do Set switch to off; end with; end execute; ``` and ``` ***********************************************************/ /* Volume Down */ /**************************************************************/ execute if Roku_Volume_Down's switch physically changes to on then with Roku_Volume_Down do Make a GET request to http://flask_ip_address:5000/down with type JSON; end with; end if; with Roku_Volume_Down do Set switch to off; end with; end execute; ``` and ``` **************************************************************/ /* Power */ /**************************************************************/ execute if Power's switch physically changes to on then with Power do Make a GET request to http://public_ip_address:5000/power with type JSON; end with; end if; with Power do Set switch to off; end with; end execute; ``` ## Setup SmartThings App We need to add the Virtual Switches to the App so that Google Home can then see them and talk to them. Open the SmartThings App on your phone. Click Add a Thing Find and Add the Roku_Volume_Up and Roku_Volume_Down devices. ## Setup Google Home Now, we can add the virtual switches to Google Home and Nickname them to 'Roku Up' and 'Roku Down'. ### Finally! Hopefully you are still with me here. Once this is all done, the flask server is running, the webcore stuff is waiting, we can test! Now, say loudly - say proudly... "Hey Google, Turn On Roku Up" If your house just sploded, not my fault.
8c2380dc962f0f850f5d51dc6042f840c69c6cc5
[ "Markdown", "Python" ]
2
Python
mccannical/Roku_Volume
3be4753358b4b8af4dd8b4f19c7773823c96f83e
21d7de920992c6ce3a62f780d818374dab8b9950
HEAD
<repo_name>EasyMetrics/emx-hapijs-base<file_sep>/CHANGELOG.md <a name="0.4.3"></a> ## [0.4.3](https://github.com/EasyMetrics/emx-microservice-es7/compare/v0.4.0...v0.4.3) (2016-10-06) ### Bug Fixes * **changelog:** add missing changelog deps ([736daeb](https://github.com/EasyMetrics/emx-microservice-es7/commit/736daeb)) * **deps:** missing lab defs ([89ed822](https://github.com/EasyMetrics/emx-microservice-es7/commit/89ed822)) * **server:** bump initialization timeout ([39aaf69](https://github.com/EasyMetrics/emx-microservice-es7/commit/39aaf69)) <a name="0.4.0"></a> # [0.4.0](https://github.com/EasyMetrics/emx-microservice-es7/compare/v0.3.0...v0.4.0) (2016-10-03) ### Features * **good:** good logging implementation ([be7beb2](https://github.com/EasyMetrics/emx-microservice-es7/commit/be7beb2)) * **swagger:** add swagger ui ([e42aafc](https://github.com/EasyMetrics/emx-microservice-es7/commit/e42aafc)) * **swagger:** stag and prod swagger configs ([bf2e48c](https://github.com/EasyMetrics/emx-microservice-es7/commit/bf2e48c)) <a name="0.3.0"></a> # [0.3.0](https://github.com/EasyMetrics/emx-microservice-es7/compare/v0.2.0...v0.3.0) (2016-10-03) ### Bug Fixes * **style:** es6 export syntax ([23ba1f5](https://github.com/EasyMetrics/emx-microservice-es7/commit/23ba1f5)) ### Features * **es6:** es2015 import statments ([29b6dce](https://github.com/EasyMetrics/emx-microservice-es7/commit/29b6dce)) <file_sep>/.docker/mongodb.dockerfile FROM easymetrics/circleci-mongod:latest MAINTAINER EasyMetrics COPY ./.docker/mongo_data /mongo_data # Example only, don't commit real credentials # Also note that the base container prints out creds in plain text # and to the terminal on first run. # Once again, dev & test only. Never deploy this container to a live host, ever # ... ENV MONGODB_ROOT_USERNAME=dbadmin ENV MONGODB_ROOT_PASSWORD=<PASSWORD> ENV MONGODB_ROOT_ROLE=root ENV MONGODB_USERNAME=webrole ENV MONGODB_PASSWORD=<PASSWORD> ENV MONGODB_DBNAME=emx-server_db ENV MONGODB_ROLE=readWrite RUN touch /.firstrun EXPOSE 27017 ENTRYPOINT ["/mongo_scripts/run.sh"] <file_sep>/src/jobs/index.js import Path from 'path'; import Fs from 'fs'; import Chalk from 'chalk'; import _ from 'lodash'; import Agenda from 'agenda'; export function register(server, options, next) { const Config = server.settings.app.jobs; if (!Config) { return next(); } const address = Config.address; const collection = Config.collection; const agenda = new Agenda({ db: { address, collection, }, }); // register all jobs _.each(Fs.readdirSync(Path.resolve(__dirname)), (filename) => { let job; if (filename !== 'index.js') { job = require(`./${filename}`); job(server, agenda); } }); agenda.on('error', (err) => { server.error(Chalk.red([error], err)); // eslint-disable-line no-undef }); agenda.on('ready', () => { if (server.settings.app.env !== 'test') { console.log(Chalk.cyan(' * Job queue starting up...')); } const recurringJobs = _(server.plugins.runtime.jobs).values().filter(job => job.FREQUENCY && job.NAME && job.TYPE === 'recurring').value(); _.each(recurringJobs, (recurringJob) => { agenda.every(recurringJob.FREQUENCY, recurringJob.NAME); }); agenda.start(); }); agenda.processEvery(Config.frequency).maxConcurrency(Config.concurrency); server.decorate('server', 'jobs', agenda); next(); } exports.register.attributes = { name: 'jobs-plugin', }; <file_sep>/src/index.js import Path from 'path'; import Spdy from 'spdy'; import Hoek from 'hoek'; import Chalk from 'chalk'; import Glue from 'glue'; import Labbable from 'labbable'; import Config from './config'; const ServerConfig = Config.server['emx-server']; const SocketIOConfig = Config.server['emx-server-socketio']; ServerConfig.uri = `${ServerConfig.tls ? 'https://' : 'http://'}${ServerConfig.host}:${ServerConfig.port}`; SocketIOConfig.uri = `${SocketIOConfig.tls ? 'https://' : 'http://'}${SocketIOConfig.host}:${SocketIOConfig.port}`; /** * Server Glue Plugin Manifest */ const manifest = { server: { app: Config, }, /** * Using the spdy package here to provide http2 due to missing functionality in node-http2 needed for hapi-auth-jwt. * Only the 'h2' & 'http/1.1' protocals are configured. */ connections: [ { listener: Spdy.createServer(ServerConfig.tlsOptions), host: ServerConfig.host, port: ServerConfig.port, tls: ServerConfig.tls, routes: { cors: { origin: ['*'], headers: ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'], additionalHeaders: ['cache-control', 'x-requested-with', 'Accept-language', 'Access-Control-Allow-Origin'], }, }, labels: ['main'], }, { host: SocketIOConfig.host, port: SocketIOConfig.port, labels: ['socketio'], }, ], // Registrations for global plugins only registrations: [ { plugin: { register: 'hapi-auth-bearer-token', }, }, { plugin: { register: 'hapi-auth-jwt', }, }, { plugin: { register: 'good', options: Config.good, }, }, { plugin: { register: 'chairo', options: Config.chairo, }, }, { plugin: { register: 'inert', }, }, { plugin: { register: 'vision', }, }, { plugin: { register: 'hapi-swagger', options: Config.swagger, }, }, { plugin: { register: 'dogwater', options: Config.dogwater, }, }, { plugin: { register: '../lib', }, }, { plugin: { register: '../socketio', }, }, ], }; /** * In Memory Cache Configuration */ if (Config.cache) { const caches = []; Object.keys(Config.cache).forEach((key) => { caches.push(Config.cache[key]); }); manifest.server.cache = caches; } /** * Instantiates Labbable for testing */ const labbable = module.exports = new Labbable(); // eslint-disable-line no-multi-assign const opts = { relativeTo: Path.join(__dirname, 'node_modules'), }; /** * Compose and Initialize Hapi Server */ Glue.compose(manifest, opts, (err, server) => { Hoek.assert(!err, err); labbable.using(server); const bootMessage = ` ${Chalk.magenta.underline(`${Config.product.name} Initialized!`)}\n - ${Chalk.blue(`${Config.product.name} is listening on`)} ${Chalk.white.underline(ServerConfig.uri)}\n - ${Chalk.blue(`${Config.product.name}-socketio is listening on`)} ${Chalk.white.underline(SocketIOConfig.uri)}\n - ${Chalk.blue('Swagger Documentation at ')} ${Chalk.white.underline(`${ServerConfig.uri}/docs`)}\n - ${Chalk.red(`Environment: ${Config.env}`)}\n `; server.initialize((err) => { Hoek.assert(!err, err); if (Config.auth) { server.auth.default(Config.auth); } if (module.parent) { return; } server.start((err) => { Hoek.assert(!err, err); setTimeout(() => { console.log(bootMessage); }, 4000); }); }); }); <file_sep>/src/auth/index.js import Path from 'path'; import Fs from 'fs'; import Chalk from 'chalk'; import _ from 'lodash'; export function register(server, options, next) { if (server.settings.app.env !== 'test') { console.log(Chalk.cyan(' * Registering authentication strategies...')); } let strategies; _.each(Fs.readdirSync(Path.resolve(__dirname)), (filename) => { if (filename !== 'index.js') { strategies = require(`./${filename}`); strategies(server, options); } }); next(); } exports.register.attributes = { name: 'auth-plugin', }; <file_sep>/src/runtime/index.js import Path from 'path'; import Fs from 'fs'; import Chalk from 'chalk'; import _ from 'lodash'; export function register(server, options, next) { if (server.settings.app.env !== 'test') { console.log(Chalk.cyan(' * Saving runtime configuration...')); } let key; _.each(Fs.readdirSync(Path.resolve(__dirname)), (filename) => { if (filename !== 'index.js') { key = filename.replace(/\.js/, ''); server.expose(key, require(`./${key}`)); } }); next(); } exports.register.attributes = { name: 'runtime', }; <file_sep>/src/db/index.js import Chalk from 'chalk'; import _ from 'lodash'; export function register(server, options, next) { if (server.settings.app.env === 'test') { return next(); } console.log(Chalk.cyan(' * Configuring databases...')); const indexesConfig = require('./indexes'); const collections = Object.keys(indexesConfig); let collection; _.each(collections, (collectionName) => { collection = server.waterline.collections[collectionName]; _.each(indexesConfig[collectionName], (configObj) => { collection.native((err, rawCollection) => { if (err) { throw err; } rawCollection.createIndex(configObj.keys, configObj.options); }); }); }); next(); } exports.register.attributes = { name: 'db-plugin', }; <file_sep>/src/config/staging.js import Pack from '../../package.json'; const HOSTNAME = require('os').hostname(); module.exports = { env: 'staging', product: { name: 'emx-server', }, server: { 'emx-server': { port: process.env.APP_PORT || 4433, host: HOSTNAME, tls: true, tlsOptions: { key: '-----<KEY> KEY-----\n', cert: '-----<KEY>END CERTIFICATE-----\n', spdy: { protocols: ['h2', 'http/1.1'], plain: false, }, }, }, 'emx-server-socketio': { port: process.env.SOCKETIO_PORT || 3001, host: HOSTNAME, tls: false, }, }, good: { ops: { interval: 1000, }, reporters: { goodFileReporter: [{ module: 'good-squeeze', name: 'Squeeze', args: [{ ops: '*' }], }, { module: 'good-squeeze', name: 'SafeJson', }, { module: 'good-file', args: ['./logs/emx-server.log'], }], }, }, chairo: { options: { // prevent seneca timeout error // https://github.com/senecajs/seneca-transport/issues/23 timeout: 999999999, }, }, cache: { mainCache: { engine: 'catbox-memory', name: 'mainCache', partition: 'emx-es-6-hapi', }, }, swagger: { info: { title: Pack.name, description: Pack.description, version: Pack.version, }, documentationPage: true, documentationPath: '/docs', jsonEditor: true, basePath: '/', pathPrefixSize: 2, jsonPath: '/docs/swagger.json', sortPaths: 'path-method', lang: 'en', tags: [ { name: 'pets', }, { name: 'users', }, ], host: `${process.env.HOST}:${process.env.PORT}`, }, dogwater: { connections: { emxApi: { adapter: 'sails-mongo', host: 'localhost', port: 27017, database: 'emx-api', }, }, adapters: { 'sails-mongo': require('sails-mongo'), }, models: require('path').resolve(__dirname, '..', 'models'), }, jobs: { address: 'mongodb://localhost:27017/emx-api', collection: 'jobs', frequency: '5 minutes', concurrency: 20, }, apiPrefix: `${process.env.APP_API_VERSION}`, }; <file_sep>/src/config/test.js const HOSTNAME = require('os').hostname(); module.exports = { env: 'test', product: { name: 'emx-server', }, server: { 'emx-server': { port: process.env.APP_PORT || 4433, host: HOSTNAME, tls: true, tlsOptions: { key: '-----<KEY>', cert: '-----<KEY>END CERTIFICATE-----\n', spdy: { protocols: ['h2', 'http/1.1'], plain: false, }, }, }, 'emx-server-socketio': { port: process.env.SOCKETIO_PORT || 3001, host: HOSTNAME, tls: false, }, }, // auth: 'token', auth0: { domain: 'API_URL', secret: 'API_SECRET', clientId: 'API_CLIENT_ID', algorithms: ['HS256'], }, chairo: { options: { timeout: 999999999, }, }, dogwater: { connections: { emxApi: { adapter: 'sails-mongo', host: 'localhost', port: 27017, database: 'emx_db-test', }, }, adapters: { 'sails-mongo': require('sails-mongo'), }, models: require('path').resolve(__dirname, '..', 'models'), }, }; <file_sep>/src/auth/auth0.js import Boom from 'boom'; import Chalk from 'chalk'; import Config from '../config'; const AuthenticationClient = require('auth0').AuthenticationClient; const Auth0 = new AuthenticationClient({ domain: Config.auth0.domain, clientId: Config.auth0.clientId, }); // get the token from the given request authorization header const getRawTokenFromHeader = function (authorization) { const parts = authorization.split(/\s+/); if (parts.length !== 2) { return null; } if (parts[0].toLowerCase() !== 'bearer') { return null; } if (parts[1].split('.').length !== 3) { return null; } return parts[1]; }; // get the user information from Auth0 and save locally const getAndSaveAuth0User = function (id, rawToken, server, reply) { return Auth0.tokens.getInfo(rawToken) .then((userData) => { const record = { user_id: userData.user_id, email: userData.email, name: userData.name, authorization: userData.app_metadata.authorization ? userData.app_metadata.authorization : {}, }; if (id) { return server.methods.users.edit(id, record, reply); } return server.methods.users.create(record, reply); }) .catch(reply); }; // validate the user from Auth0, and save the information if not already in the system const validateFunc = function (req, token, reply) { const authHeader = req.headers.authorization; if (!authHeader) { return reply(Boom.unauthorized(null, 'Bearer')); } // original token. used to get more info const rawToken = getRawTokenFromHeader(authHeader); const server = req.server; if (!rawToken) { return reply(Boom.unauthorized(null, 'Bearer')); } // decoded user_id const userId = token.sub; // check if already cached, otherwise get and save from Auth0 server.methods.users.getActiveUser(userId, (error, user, cached, report) => { // eslint-disable-line no-unused-vars if (error) { console.error(Chalk.red([error], error)); return reply(error, false, token); } let id; if (user) { // update existing record id = user.id; } if (!cached) { return getAndSaveAuth0User(id, rawToken, server, (error, user) => { // eslint-disable-line no-unused-vars if (error) { console.error(Chalk.red([error], error)); return reply(error, false, token); } return reply(null, true, token); }); } return reply(null, true, token); }); }; module.exports = (server, options) => { // eslint-disable-line no-unused-vars const jwtConfig = { key: new Buffer(Config.auth0.secret, 'base64'), verifyOptions: { ignoreExpiration: false, algorithms: Config.auth0.algorithms, audience: Config.auth0.clientId, }, validateFunc, }; server.auth.strategy('auth0', 'jwt', jwtConfig); }; <file_sep>/src/routes/handlers/users.js export default { find: (request, reply) => reply(request.pre.users), create: (request, reply) => reply(request.pre.user).created(request.pre.location), findOneById: (request, reply) => reply(request.pre.user), edit: (request, reply) => reply(request.pre.user), destroy: (request, reply) => reply().code(204), }; <file_sep>/src/config/prod.js import path from 'path'; import fs from 'fs'; import Pack from '../../package.json'; const HOSTNAME = require('os').hostname(); const opbeat = require('opbeat').start({ // eslint-disable-line no-unused-vars appId: process.env.OPBEAT_APP || '', organizationId: process.env.OPBEAT_ORG || '', secretToken: process.env.OPBEAT_SECRET || '', }); module.exports = { env: 'production', product: { name: 'emx-server', }, // Keys below are built into the base NodeJS docker container. server: { 'emx-server': { port: process.env.APP_PORT || 4433, host: HOSTNAME, tls: true, tlsOptions: { key: fs.readFileSync(path.resolve('/etc/ssl/private/star_easymetrics_com.key')), cert: fs.readFileSync(path.resolve('/etc/ssl/certs/star_easymetrics_com.crt')), ca: fs.readFileSync(path.resolve('/etc/ssl/certs/DigiCertCA.crt')), spdy: { protocols: ['h2', 'http/1.1'], plain: false, }, }, }, 'emx-server-socketio': { port: process.env.SOCKETIO_PORT || 3001, host: HOSTNAME, tls: false, }, }, auth: 'auth0', auth0: { domain: `${process.env.API_URL}`, secret: `${process.env.API_SECRET}`, clientId: `${process.env.API_CLIENT_ID}`, algorithms: ['HS256'], }, good: { ops: { interval: 1000, }, reporters: { goodFileReporter: [{ module: 'good-squeeze', name: 'Squeeze', args: [{ ops: '*' }], }, { module: 'good-squeeze', name: 'SafeJson', }, { module: 'good-file', args: ['./logs/emx-server.log'], }], }, }, chairo: { options: { timeout: 999999999, }, }, cache: { mainCache: { engine: 'catbox-memory', name: 'mainCache', partition: 'emx-cache', }, }, swagger: { info: { title: Pack.name, description: Pack.description, version: Pack.version, }, documentationPage: true, documentationPath: '/docs', jsonEditor: true, basePath: `${process.env.APP_API_VERSION}`, pathPrefixSize: 3, jsonPath: '/docs/swagger.json', sortPaths: 'path-method', lang: 'en', tags: [ { name: 'employees', }, { name: 'facilities', }, { name: 'projects', }, ], host: `${process.env.DOCKERCLOUD_SERVICE_FQDN}:${process.env.APP_PORT}`, }, dogwater: { connections: { emxApi: { adapter: 'sails-mongo', host: `${process.env.MONGO_HOST}`, port: `${process.env.MONGO_PORT}`, user: `${process.env.MONGO_USER}`, password: `${<PASSWORD>}`, database: `${process.env.MONGO_DB}`, }, }, adapters: { 'sails-mongo': require('sails-mongo'), }, models: require('path').resolve(__dirname, '..', 'models'), }, jobs: { address: `mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_HOST}:${process.env.MONGO_PORT}/${process.env.MONGO_DB}`, collection: 'jobs', frequency: '5 minutes', concurrency: 20, }, apiPrefix: `${process.env.APP_API_VERSION}`, }; <file_sep>/docker-compose.yml ##---------------------------------------------------------------------------------------------------## # 1. export DOCKER_ACCT=<dockerHubAccountName> # # 2. Run docker-compose --file docker-compose.yml build # # 3. Run docker-compose --file docker-compose.yml up # ##---------------------------------------------------------------------------------------------------## version: "2" services: # Uncomment the `build` section to build local containers or just pull from the registry. # Comment out the entire `emx-server` section to just run the supporting stack for local dev. emx-server: container_name: emx-server image: gcr.io/jobtrak-155518/emx-server:develop # build: # context: . # dockerfile: Dockerfile ports: - "4433:4433" - "3001:3001" links: - mongodb - redis networks: - emx-server-network mongodb: container_name: emx-mongodb image: easymetrics/circleci-mongod # build: # context: . # dockerfile: .docker/mongodb.dockerfile ports: - "27017" env_file: - ./.docker/env/mongo.env networks: - emx-server-network redis: container_name: emx-redis image: easymetrics/circleci-redis # build: # context: . # dockerfile: .docker/redis.dockerfile ports: - "6379" networks: - emx-server-network networks: emx-server-network: driver: bridge <file_sep>/src/methods/index.js import Path from 'path'; import Fs from 'fs'; import Chalk from 'chalk'; import _ from 'lodash'; export function register(server, options, next) { if (server.settings.app.env !== 'test') { console.log(Chalk.cyan(' * Loading server methods...')); } let methods; _.each(Fs.readdirSync(Path.resolve(__dirname)), (filename) => { if (filename !== 'index.js') { methods = require(`./${filename}`); server.method(methods(server, options)); } }); next(); } exports.register.attributes = { name: 'methods-plugin', }; <file_sep>/src/methods/users.js import Chalk from 'chalk'; import Boom from 'boom'; import _ from 'lodash'; const find = function find(query, next) { this .find({ limit: query.limit, skip: query.offset }) .exec((err, users) => { if (err) { console.error(Chalk.red([error], err)); return next(Boom.badImplementation()); } return next(null, users); }); }; const findOneById = function findOneById(id, next) { this .findOneById(id) .exec((err, user) => { if (err) { console.error(Chalk.red([error], err)); return next(Boom.badImplementation()); } if (!user) { return next(Boom.notFound('User not found')); } return next(null, user); }); }; const getActiveUser = function getActiveUser(userId, next) { this.findOne({ user_id: userId }) .exec((err, user) => { if (err) { console.error(Chalk.red([error], err)); return next(Boom.badImplementation()); } return next(null, user); }); }; const create = function create(data, next) { this .create(data) .exec((err, user) => { if (err) { console.error(Chalk.red([err], err)); return next(Boom.badImplementation()); } return next(null, user); }); }; const edit = function edit(id, data, next) { this .update({ id }, data) .exec((err, user) => { if (err) { console.error(Chalk.red([error], err)); return next(Boom.badImplementation()); } if (!user.length) { return next(Boom.notFound('User not found')); } return next(null, _.head(user)); }); }; const destroy = function destroy(id, next) { this .destroy({ id }, (err) => { if (err) { console.error(Chalk.red([error], err)); return next(Boom.badImplementation()); } return next(); }); }; module.exports = (server, options) => [ // eslint-disable-line no-unused-vars { name: 'users.find', method: find, options: { bind: server.waterline.collections.users, cache: server.plugins.runtime.cache.users.find.cache ? server.plugins.runtime.cache.users.find : undefined, generateKey: opts => JSON.stringify(opts), }, }, { name: 'users.findOneById', method: findOneById, options: { bind: server.waterline.collections.users, cache: server.plugins.runtime.cache.users.findOneById.cache ? server.plugins.runtime.cache.users.findOneById : undefined, generateKey: opts => JSON.stringify(opts), }, }, { name: 'users.create', method: create, options: { bind: server.waterline.collections.users, }, }, { name: 'users.edit', method: edit, options: { bind: server.waterline.collections.users, }, }, { name: 'users.destroy', method: destroy, options: { bind: server.waterline.collections.users, }, }, { name: 'users.getActiveUser', method: getActiveUser, options: { bind: server.waterline.collections.users, cache: server.plugins.runtime.cache.users.activeUsers.cache ? server.plugins.runtime.cache.users.activeUsers : undefined, generateKey: opts => JSON.stringify(opts), }, }, ]; <file_sep>/src/db/indexes.js module.exports = { users: [ { keys: { emFacilityId: 1 }, options: { background: true, unique: false, sparse: false }, }, ], }; <file_sep>/src/routes/config/users.js import Validations from '../validations/users'; import Handlers from '../handlers/users'; export default { find: { validate: Validations.find, pre: [ { method: 'users.find(query)', assign: 'users', }, ], handler: Handlers.find, plugins: { 'hapi-swagger': { responses: { 200: { description: 'Success', }, 400: { description: 'BadRequest', }, }, payloadType: 'form', }, }, tags: [ 'api', 'users', ], description: 'Find a user.', }, create: { validate: Validations.create, pre: [ { method: 'users.create(payload)', assign: 'user', }, { method: 'utils.buildResourceLocation(path, pre.user.id)', assign: 'location', }, ], handler: Handlers.create, plugins: { 'hapi-swagger': { responses: { 200: { description: 'Success', }, 400: { description: 'BadRequest', }, }, payloadType: 'form', }, }, tags: [ 'api', 'users', ], description: 'Create a user.', }, findOneById: { validate: Validations.findOneById, pre: [ { method: 'users.findOneById(params.id)', assign: 'user', }, ], handler: Handlers.findOneById, plugins: { 'hapi-swagger': { responses: { 200: { description: 'Success', }, 400: { description: 'BadRequest', }, }, payloadType: 'form', }, }, tags: [ 'api', 'users', ], description: 'Find One user by objectId', }, edit: { validate: Validations.edit, pre: [ { method: 'users.edit(params.id, payload)', assign: 'user', }, ], handler: Handlers.edit, plugins: { 'hapi-swagger': { responses: { 200: { description: 'Success', }, 400: { description: 'BadRequest', }, }, payloadType: 'form', }, }, tags: [ 'api', 'users', ], description: 'Edit a user.', }, destroy: { validate: Validations.destroy, pre: ['users.destroy(params.id)'], handler: Handlers.destroy, plugins: { 'hapi-swagger': { responses: { 200: { description: 'Success', }, 400: { description: 'BadRequest', }, }, payloadType: 'form', }, }, tags: [ 'api', 'users', ], description: 'Delete a user.', }, }; <file_sep>/.docker/postgresql.dockerfile FROM easymetrics/circleci-postgresql:latest # Maintener MAINTAINER EasyMetrics # Example only, don't commit real credentials # Also note that the base container prints out creds in plain text # and to the terminal on first run. # Once again, dev & test only. Never deploy this container to a live host, ever # ... ENV POSTGRES_DB_NAME=emx-server_pgsql ENV POSTGRES_DB_USER=dbadmin ENV POSTGRES_DB_PASS=<PASSWORD> # Set volume VOLUME ["/var/lib/pgsql"] # Set username USER postgres # Run PostgreSQL Server CMD ["/bin/bash", "/usr/local/bin/postgresql.sh"] # Expose ports. EXPOSE 5432 <file_sep>/src/lib/shutdown.js import Chalk from 'chalk'; import _ from 'lodash'; const gracefulShutdown = (server) => { if (server.settings.app.env !== 'test') { console.log(Chalk.yellow(' * Shutting down...')); } server.jobs && server.jobs.stop(() => { if (server.settings.app.env !== 'test') { console.log(Chalk.yellow(' * Shutting down job queue...')); } process.exit(0); // eslint-disable-line no-process-exit }); }; export function register(server, options, next) { if (server.settings.app.env !== 'test') { console.log(Chalk.cyan(' * Registering shutdown cleanup...')); } process.on('SIGTERM', _.bind(gracefulShutdown, null, server)); process.on('SIGINT', _.bind(gracefulShutdown, null, server)); next(); } exports.register.attributes = { name: 'shutdown-plugin', }; <file_sep>/src/socketio/handlers/index.js import Path from 'path'; import Fs from 'fs'; import _ from 'lodash'; // socket handlers export default (server, socket) => { let handlers; _.each(Fs.readdirSync(Path.resolve(__dirname)), (filename) => { if (filename !== 'index.js') { handlers = require(`./${filename}`); handlers.default(server, socket); } }); }; // for global API (not tied to a socket) export function globalApi(server, io) { let handlers; _.each(Fs.readdirSync(Path.resolve(__dirname)), (filename) => { if (filename !== 'index.js') { handlers = require(`./${filename}`); if (handlers.globalApi) { handlers.globalApi(server, io); } } }); } <file_sep>/src/routes/users.js import Config from './config/users'; module.exports = (server, options) => [ // eslint-disable-line no-unused-vars { method: 'GET', path: '/users', config: Config.find, }, { method: 'POST', path: '/users', config: Config.create, }, { method: 'GET', path: '/users/{id}', config: Config.findOneById, }, { method: 'PATCH', path: '/users/{id}', config: Config.edit, }, { method: 'DELETE', path: '/users/{id}', config: Config.destroy, }, ]; <file_sep>/README.md [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![G.P.A][gpa]][gpa-url] <div align="center"> <img width="200" height="200" src="https://cdn.worldvectorlogo.com/logos/hapi.svg"> <a href="https://github.com/easymetrics"> <img width="200" height="200" vspace="" hspace="25" src="https://cdn.worldvectorlogo.com/logos/easymetrics-inc.svg"> </a> <h1>EasyMetrics es2016+ HapiJS Base</h1> <p>Project seed for our HapiJS based APIs.<p> </div> ## Table of Contents - [Development Experience](#development-experience) - [Prerequisites](#prerequisites) - [Usage](#usage) - [Testing](#testing) - [Performance Benchmarks](#benchmarking-suite) - [Debugging](#debugging) - [Security & Updates](#security--updates) - [Changelog & Release](#changelog--release) - [API Configuration Options](#api-configuration-options) ### Core Libraries - [HapiJS](http://hapijs.com/) A rich framework for building applications and services - [Swagger 2.0](http://swagger.io/) a.k.a The OpenAPI Specification - [Good](https://github.com/hapijs/good) Hapi process monitoring - [Good Console](https://github.com/hapijs/good-console) Console reporting for Good process monitor - [Good Squeeze](https://github.com/hapijs/good-squeeze) Simple transform stream for event filtering with good - [Good HTTP](https://github.com/hapijs/good-http) Http(s) broadcasting for Good process monitor - [Agenda](https://github.com/rschmukler/agenda) Agenda is a light-weight job scheduling library for Node.js - [SocketIO](https://github.com/socketio/socket.io) node.js realtime framework server - [Waterline ORM](https://github.com/balderdashy/waterline) An adapter-based ORM for Node.js with support for mongo, postgres, redis, and more. - [Redis](https://github.com/antirez/redis) Redis is an open source, in-memory data structure store for cache and message brokering. - [Mongodb](https://github.com/mongodb/mongo) The Mongo Database. - [Docker](https://www.docker.com/) Docker is an open platform for developers and sysadmins to build, ship, and run distributed applications. ### Development Experience - Node optimized ES6 / ES7 transpilation with [Babel](https://github.com/babel/babel) - ES6+ aware minifier based on the Babel toolchain [babili](https://github.com/babel/babili) - Code monitoring and auto server restart with [nodemon](https://github.com/remy/nodemon) - ES6+ Testing via [babel-register](https://github.com/babel/babel/tree/master/packages/babel-register) with [Lab](https://github.com/hapijs/lab) & [Labbable](https://github.com/devinivy/labbable) - Code Linting with [ESLint](https://github.com/eslint/eslint) - Sourcemap generation - Vulnerability scan via [nsp](https://github.com/nodesecurity/nsp) - Check for latest versions of dependencies via [ncu](https://github.com/tjunnone/npm-check-updates) ### Prerequisites * Docker for OSX or Windows * [NVM](https://github.com/creationix/nvm) ( Node version manager ) - Do not user brew for nodejs * Node v6 or higher and npm 5 or higher. * [Commitizen](https://github.com/commitizen/cz-cli) - Zen-like commit messages for internet citizens. * Editor - VSCode / Atom / Webstorm / Sublime ( In that Order ). * [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) for manually testing restful APIs ### Continuous Integration & Deployment _Note: The CI/CD setup if very specific EasyMetrics_ - The CircleCI / Docker configuration is purpose built for our CI/CD process, it may be useful as a an example but it's not general enough to be useful for public consumption. - Any of the docker configurations begining with `FROM gcr.io/ ...` are pulling from a private registry and will have to be replaced with an applicable image of you choosing. ### Usage - `npm start` - execute code in `src` directory with live reload via `nodemon` transpiled with `babel-node` - `npm run serve:dev` - execute target code with live reload via `nodemon` transpiled with `babel-node` - `npm run build:dist` - transpile and minify ES6+ code and create sourcemaps with `babel` & `babili` - `npm run serve:dist` - serve production files from the `./dist` folder via `node` - `npm test` - run tests with `lab` and `chai` assertions - `npm run test:coverage` - run tests with `lab` and generates code coverage - `npm run lint` - code linting with `eslint` - `npm run lint:fix` - fix problems automatically with `eslint` - `npm run benchmark` - run benchmark tests with `benchmark.js` - `npm run benchmark:watch` - run benchmark tests with `benchmark.js` and watch for file changes - `npm run scan:security` - run vulnerability tests via the node security platform `nsp` - `npm run scan:updates` - check for latest versions of dependencies via `ncu` ### Creating a new project - Run a find/replace in the project root for `emx-server` & replace with the server name of your choosing. - All the configuration values are pulled from dotenv - All of the connections are setup as plugins, add / remove Postgres and Redis as you see fit. MongoDB is required to make use of Agenda. - Change the path of the SSL certs in `./src/config/prod.js` to the path of the installed certs on your production build container. ### Running the supporting stack _Adds your dockerhub username to any container created to prevent name colisions_ ```bash export DOCKER_ACCT=<dockerHubAccountName> ``` _Build the containers using docker compose_ ```bash docker-compose --file docker-compose.yml build ``` _Run the stack via docker-compose and load seed data_ ```bash docker-compose --file docker-compose.yml up ``` _Docker loads data ( if it exists ) into MongoDB on the first run only, to reset the seed data you need to remove & rebuild the containers_ ```bash # Stop all running containers docker stop $(docker ps -a -q) # Delete all containers docker rm $(docker ps -a -q) ``` ### Testing _Testing with [Lab](https://github.com/hapijs/lab) and [Labbable](https://github.com/devinivy/labbable), Code quality via [ESLint](https://github.com/eslint/eslint) & [Codeclimate](https://codeclimate.com)_ ```bash npm test ``` ### Debugging There is a Visual Studio Code launch configuration included in `./.vscode/launch.json`. It inturn executes babel-node allowing you to set break points and step through es2016+ code ### Security & Updates _Run vulnerability tests via node security platform as a part of the CircleCI configuarion._ ```bash npm run scan:security ``` ### Changelog & Release _Changelog generation is provided by `conventional-changelog` & `cz-conventional-changelog`_ - We follow the [AngularJS Commit Messsage Guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#-git-commit-guidelines), [Commitizen](https://github.com/commitizen/cz-cli) does this for us. - The `CHANGELOG.md` is generated from this specific commit message formatting. - Workflow for changelog & release can be found [here](https://github.com/EasyMetrics/emx-microservice-es7/tree/master/scripts/release) ### API Configuration Options Confiugration is handled by [dotenv](https://github.com/motdotla/dotenv) with any reqired constants having defaults configured. ```javascript const APP_PORT = 4433; const SOCKETIO_PORT = 3001; const MONGO_HOST = localhost const MONGO_PORT = 27017 const MONGO_USER = webrole const MONGO_PASS = '<PASSWORD>' const MONGO_DB = 'configureMe' const PG_HOST = localhost const PG_PORT = 5432 const PG_USER = dbadmin const PG_PASS = '<PASSWORD>' const API_URL = 'configureMe' const API_SECRET = 'configureMe' const API_CLIENT_ID = 'configureMe' const S3_ACCESS_KEY = 'configureMe' const S3_SECRET_ACCESS_KEY = 'configureMe' const S3_REGION = 'configureMe' ``` [tests]: https://img.shields.io/circleci/project/github/RedSparr0w/node-csgo-parser.svg [tests-url]: https://circleci.com/gh/EasyMetrics/hapijs-babel-starter [gpa]: https://codeclimate.com/github/EasyMetrics/hapijs-babel-starter/badges/gpa.svg [gpa-url]: https://codeclimate.com/github/EasyMetrics/hapijs-babel-starter [cover]: https://codeclimate.com/github/EasyMetrics/hapijs-babel-starter/badges/coverage.svg [cover-url]: https://codeclimate.com/github/EasyMetrics/hapijs-babel-starter/coverage <file_sep>/src/models/index.js import Path from 'path'; import Fs from 'fs'; import _ from 'lodash'; module.exports = []; let modelObject; _.each(Fs.readdirSync(__dirname), (file) => { if (file !== 'index.js') { modelObject = require(Path.join(__dirname, file)); module.exports.push(modelObject); } });
bdd52754ddeebadf9ecb4513e46c196110104feb
[ "Markdown", "JavaScript", "Dockerfile", "YAML" ]
23
Markdown
EasyMetrics/emx-hapijs-base
8d086fce79f2d575d20c462a71eb522cafad2129
af94b57fd61f4ab4f5146af454a5b709368e589b
refs/heads/main
<repo_name>SpreeRaj/bWNP7nAH8BbKmr<file_sep>/README.md # bWNP7nAH8BbKmr ## Relay 5 ## Project Setup - Clone repository - Got to repository folder - To build Server ```sh cd connectfiveserver mvn clean install mvn spring-boot:run ``` - To build Client ```sh cd connectclient mvn clean install mvn spring-boot:run ``` -To Run Game with JAR files ```sh cd game_jars_updated [For Server]: java -jar connectfiveserver.jar [For Clients]: java -jar connectfiveclient.jar ``` ## Play game ### 1. Run Server in one terminal ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/ServerStartup.PNG) ### 2. Run Client for Player-1 ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/ClientStartip.PNG) ### 3. Enter Player-1 Details > Note: Perform step-4 after terminal prompts "Waiting for player 2" ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/ClientStartupPlayer1.PNG) ### 4. Run Client for Player-2 in Separate Terminal ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/ClientStartupPlayer2.PNG) ### 5. Game play ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/GamePlay.PNG) ## Testing - `Screenshot for tests attached below :` - `You can run test using any IDE directly` ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/CodeCoverage.PNG) ## Swagger URL - Swaggger is enabled and can be viewed after server startup at: >http://localhost:8080/swagger-ui.html >http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config ![alt text](https://github.com/SpreeRaj/bWNP7nAH8BbKmr/blob/main/Screenshots/Swagger.PNG) ## Additional Notes : - If one player disconnects game takes 6 seconds to declare other player winner. - To start a new game shutdown both server and clients and follow steps again of `Play Game` - Tests only involve unit test for 2 Manager Classes. Integration tests would need further upgrade/Implementation. - `Know issue`: Cannot Start two clients simultaneously. Need to finish entering details of Player 1 before starting client 2. - Server is capable of handling game of any size and connect of any number. Currently built with 6X9 and win of relay 5. Just rebuild client by making those changes and you are good to go. ## Concepts Used ### 1.Spring boot - To develop client ### 2. Spring Boot Rest - To develop server apis. ### 3. Junit 5 - For Unit Testing ### 4. Multithreding and Long Polling - To handle two player gameplay without web socket # Enjoy the Game !!!! :) ## License MIT <file_sep>/connectclient/src/main/java/com/game/connect/five/connectclient/util/UpdateCurrentPlayerStatusThread.java package com.game.connect.five.connectclient.util; import com.game.connect.five.connectclient.service.PutCalls; import lombok.AllArgsConstructor; @AllArgsConstructor public class UpdateCurrentPlayerStatusThread implements Runnable { private PutCalls putCalls; private String clientPlayerID; @Override public void run() { try { while (true) { this.putCalls.callCurrentPlayerUpdateStatus(this.clientPlayerID); Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/connectfiveserver/src/main/java/com/game/connect/five/connectfiveserver/service/SessionManager.java package com.game.connect.five.connectfiveserver.service; import com.game.connect.five.connectfiveserver.model.Game; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; @Component @AllArgsConstructor @NoArgsConstructor public class SessionManager { @Autowired Game game; public String updateOpponentStatus(String playerId) { if(this.game.getPlayer1().getUniqueID().equals(playerId)){ this.game.getPlayer2().setPlayerStatus("Inactive"); } else if(this.game.getPlayer2().getUniqueID().equals(playerId)){ this.game.getPlayer1().setPlayerStatus("Inactive"); } else return "Update Error"; return "Done"; } public String updatecurrentPlayerStatus(String playerId) { if(this.game.getPlayer1().getUniqueID().equals(playerId)){ this.game.getPlayer1().setPlayerStatus("Active"); } else if(this.game.getPlayer2().getUniqueID().equals(playerId)){ this.game.getPlayer2().setPlayerStatus("Active"); } else return "Update Error"; return "Done"; } } <file_sep>/connectfiveserver/src/test/java/com/game/connect/five/connectfiveserver/service/GameManagerTest.java package com.game.connect.five.connectfiveserver.service; import com.game.connect.five.connectfiveserver.model.Game; import com.game.connect.five.connectfiveserver.model.GameBoard; import com.game.connect.five.connectfiveserver.model.GameBoardSize; import com.game.connect.five.connectfiveserver.model.Player; import com.game.connect.five.connectfiveserver.util.BoardHandler; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class GameManagerTest { Player player1=new Player("Ron", "RED", "Active", 5); Player player2=new Player("Harry", "test", "Active", 5); GameBoard gameBoard=new GameBoard(new String[3][3], 5); Game game; BoardHandler boardHandler; @BeforeEach void setUp() { game=new Game(gameBoard, player1, player2); boardHandler=new BoardHandler(game, new int[3], player1, null, 9, false, new Player()); } @Test void noArgsTestGameManager() { GameManager gameManager=new GameManager(); assertNotNull(gameManager); } //Start New Game @Test void startNewGameTest() { GameBoardSize gameBoardSize=new GameBoardSize(3, 3); GameManager gameManager=new GameManager(game, boardHandler); String response=gameManager.startNewGame(gameBoardSize); assertEquals("Game created with Board size 3 X 3", response); } //Add player Details @Test void addPlayer1DetailsTest() { game=new Game(gameBoard, new Player(), new Player()); GameManager gameManager=new GameManager(game, boardHandler); Player p=gameManager.addPlayerDetails("Raj", "Red"); assertEquals(p.getPlayerName(), "Raj"); } @Test void addPlayer2DetailsTest() { game=new Game(gameBoard, player1, new Player()); GameManager gameManager=new GameManager(game, boardHandler); Player p=gameManager.addPlayerDetails("Raj", "Red"); assertEquals(p.getPlayerName(), "Raj"); } //update Board @Test void updateBoardwithIncorrectClientId() { GameManager gameManager=new GameManager(game, boardHandler); String response=gameManager.updateBoard(1, "RandomID"); assertEquals("INVALID_PLAYER", response); } @Test void updateBoardWithIllegalTurn() { GameManager gameManager=new GameManager(game, boardHandler); String response=gameManager.updateBoard(1, player2.getUniqueID()); assertEquals("WRONG_TURN", response); } @Test void updateBoardWithInvalidValidColum() { GameManager gameManager=new GameManager(game, boardHandler); String response=gameManager.updateBoard(1, player1.getUniqueID()); assertEquals("INVALID_COLUMN", response); } @Test void updateBoardWithWinnerResponse() { this.game.getGameBoard().setColumn(3); this.game.getGameBoard().setRow(3); this.game.setGameBoard(gameBoard); this.game.getGameBoard().setWinSize(3); String[][] board = this.game.getGameBoard().getBoard(); for(int i=0 ; i<3 ; i++) for(int j=0 ; j<3 ; j++) board[i][j]=""; board[0][1]="RED"; board[0][2]="RED"; GameManager gameManager=new GameManager(game, boardHandler); gameManager.getBoardHandler().setWinnerFlag(true); String response=gameManager.updateBoard(1, player1.getUniqueID()); assertEquals("WINNER", response); } @Test void updateBoardWithUpdateAddTokenResponse() { this.game.getGameBoard().setColumn(3); this.game.getGameBoard().setRow(3); this.game.setGameBoard(gameBoard); String[][] board = this.game.getGameBoard().getBoard(); for(int i=0 ; i<3 ; i++) for(int j=0 ; j<3 ; j++) board[i][j]=""; GameManager gameManager=new GameManager(game, boardHandler); gameManager.getBoardHandler().setWinnerFlag(true); String response=gameManager.updateBoard(1, player1.getUniqueID()); assertEquals("TOKEN_ADDED", response); } @Test void updateBoardWithUpdateAddTokenResponsePlayer2() { this.game.getGameBoard().setColumn(3); this.game.getGameBoard().setRow(3); this.game.setGameBoard(gameBoard); this.boardHandler.setCurrentPlayer(this.game.getPlayer2()); String[][] board = this.game.getGameBoard().getBoard(); for(int i=0 ; i<3 ; i++) for(int j=0 ; j<3 ; j++) board[i][j]=""; GameManager gameManager=new GameManager(game, boardHandler); gameManager.getBoardHandler().setWinnerFlag(true); gameManager.getGame(); String response=gameManager.updateBoard(1, player2.getUniqueID()); assertEquals("TOKEN_ADDED", response); } @Test void getGame() { } @Test void getBoardHandler() { } @Test void setGame() { } @Test void setBoardHandler() { } }<file_sep>/connectclient/src/main/java/com/game/connect/five/connectclient/config/GameConfig.java package com.game.connect.five.connectclient.config; import org.springframework.stereotype.Component; import lombok.Getter; @Component @Getter public class GameConfig { public final String[] PlayerToken= {"RED", "BLUE", "GREEN", "YELLOW"}; } <file_sep>/connectfiveserver/src/main/java/com/game/connect/five/connectfiveserver/model/GameBoardSize.java package com.game.connect.five.connectfiveserver.model; import org.springframework.stereotype.Component; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Component @Getter@Setter @NoArgsConstructor @AllArgsConstructor public class GameBoardSize { private int row; private int column; } <file_sep>/connectclient/src/main/java/com/game/connect/five/connectclient/util/ResponseMapper.java package com.game.connect.five.connectclient.util; import java.util.LinkedHashMap; import java.util.Map; import com.game.connect.five.connectclient.model.Game; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.JsonParser; import org.springframework.boot.json.JsonParserFactory; import org.springframework.stereotype.Component; @Component public class ResponseMapper { @Autowired Game game; public void updateGameObject(String response) { JsonParser jsonParser = JsonParserFactory.getJsonParser(); Map<String, Object> responseMap = jsonParser.parseMap(response); LinkedHashMap player1 = (LinkedHashMap) responseMap.get("player1"); LinkedHashMap player2 = (LinkedHashMap) responseMap.get("player2"); game.setPlayer1Name(player1.get("playerName") != null ? player1.get("playerName").toString() : null); game.setPlayer1Status(player1.get("playerStatus") != null ? player1.get("playerStatus").toString() : null); game.setPlayer1TokenColor( player1.get("playerTokenColor") != null ? player1.get("playerTokenColor").toString() : null); game.setPlayer1uniqueID(player1.get("uniqueID") != null ? player1.get("uniqueID").toString() : "test"); game.setPlayer2Name(player2.get("playerName") != null ? player2.get("playerName").toString() : null); game.setPlayer2Status(player2.get("playerStatus") != null ? player2.get("playerStatus").toString() : null); game.setPlayer2TokenColor( player2.get("playerTokenColor") != null ? player2.get("playerTokenColor").toString() : null); game.setPlayer2uniqueID(player2.get("uniqueID") != null ? player2.get("uniqueID").toString() : null); } public void printBoard(String response) { JSONObject json = new JSONObject(response); JSONObject data = json.getJSONObject("gameBoard"); JSONArray board = data.getJSONArray("board"); String token=""; for (int i = board.length()-1; i>=0; i--) { JSONArray boardRow = board.getJSONArray(i); for (int j = 0; j < boardRow.length(); j++) { if (boardRow.get(j).equals("")) System.out.print("' ' "); else{ token=(String) boardRow.get(j); System.out.print("'"+token.charAt(0)+"' "); } } System.out.println(); } JSONArray boardRow = board.getJSONArray(0); for(int i=1 ; i<=boardRow.length() ; i++) System.out.print("|"+i+"| "); } public String getCurrentPlayer(String response) { JSONObject json = new JSONObject(response); JSONObject data = json.getJSONObject("currentPlayer"); String playerId=(String) data.get("uniqueID"); try{ JSONObject data2 = json.getJSONObject("winningPlayer"); String winningPlayerId=(String) data2.get("uniqueID"); this.game.setWinningPlayerId(winningPlayerId); }catch(Exception e){} return playerId.toString(); } public String getCurrentPlayerStatus(String response) { JSONObject json = new JSONObject(response); JSONObject data = json.getJSONObject("currentPlayer"); String playerStatus=(String) data.get("playerStatus"); // System.out.println(playerStatus); return playerStatus.toString(); } }
0b64c1c081fa467a02efcfef43cba46804146354
[ "Markdown", "Java" ]
7
Markdown
SpreeRaj/bWNP7nAH8BbKmr
55c8899ec551649706f75a66ad115a2fb5af66ac
75b9140b63485c70a19ca31da5243d8daabf53a8
refs/heads/master
<file_sep><?php require('config.php'); $text = ''; if (date("G")>7) { $text = 'NOT'; } $sel = $mysqli->query("SELECT * FROM `tag` WHERE `name` ".$text." LIKE '%утро%'"); $num = rand(0, $sel->num_rows); $sel->data_seek($num); $res = $sel->fetch_assoc(); $sel = $mysqli->query("SELECT * FROM `workout` WHERE `id`=".$res['workout_id']); $sel->data_seek(0); $res = $sel->fetch_assoc(); $name = $res['name']; $width = '100%'; echo '<span class="title">-Случайная тренировка-<br/><span class="subtitle">(Воспользуйся поиском в кнопке "Потренить", если хочешь что-то конкретное)</span></span><br/>'; ?><file_sep><?php $tag_where = ''; $workout_where = ''; $tag_having = ''; if (isset($_GET['tag_str'])){ $results = []; $tag_arr = json_decode($_GET['tag_str']); if (count($tag_arr)>0&&isset($tag_arr[0])){ $tag_having = "HAVING COUNT(`tag`.`name`)=".count($tag_arr); $tag_where = "WHERE `tag`.`name`='".$tag_arr[0]."' "; } if (count($tag_arr)>1){ for ($i=1; $i<count($tag_arr); $i++){ $tag_where .= "OR `tag`.`name`='".$tag_arr[$i]."' "; } } } if (isset($_GET['interval'])||isset($_GET['coach'])){ $workout_where = 'WHERE '; } if (isset($_GET['interval'])){ $int_arr = json_decode($_GET['interval']); $workout_where .= "((`duration`>".$int_arr[0]." AND `duration`<".$int_arr[1].") OR `duration`=0)"; if (isset($_GET['coach'])&&$_GET['coach']!='any'){ $workout_where .= ' AND '; } } if (isset($_GET['coach'])){ $coach = $_GET['coach']; if ($coach!='any'){ $workout_where .= " `coach`='".$coach."'"; } } if (!isset($_GET['tag_str'])||count($tag_arr)==0||!isset($tag_arr[0])){ $query = "SELECT `name` AS `video`, `description`, `coach`, `duration` FROM `workout` ".$workout_where; } else { $query = "SELECT `tag`.*, `work`.`name` AS `video`, `work`.*, COUNT(`tag`.`name`) AS matches FROM `tag` JOIN (SELECT * FROM `workout` ".$workout_where.") AS `work` ON `tag`.`workout_id`= `work`.`id` ".$tag_where." GROUP BY `tag`.`workout_id`".$tag_having; } $sel = $mysqli->query($query); if ($sel->num_rows>0) { for($i=0;$i<$sel->num_rows; $i++){ $sel->data_seek($i); $res = $sel->fetch_assoc(); $results[$i] = [$res['video'], $res['description'], $res['coach'], $res['duration'], $res['id']]; } } $res_json = json_encode($results); $search = ["'", "\""]; $replace = ["\'", "\\\""]; $res_json = str_replace($search, $replace, $res_json); if ($_GET['type']=='rnd') { $num = rand(0, count($results)-1); echo "<script type='text/javascript'>location.replace('workout.php?name=".$results[$num][0]."');</script> "; } ?><file_sep><?php header("Content-Type: text/html; charset=utf-8"); include('authorize.php'); include('config.php'); include('php/tag_list.php'); include('php/coach_list.php'); $query = "SELECT * FROM `workout` WHERE `duration`>0"; $sel = $mysqli->query($query); $q1 = $sel->num_rows; $query = "SELECT * FROM `workout`"; $sel = $mysqli->query($query); $q2 = $sel->num_rows; $ratio = round(100*$q1/$q2); ?> <script> var tag_str = '<?php echo $tag_str; ?>'; var coach_str = '<?php echo $coach_str; ?>'; var coach = 'any'; </script> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/workout.css"> <script src="js/jquery.js"></script> <script src="js/help.js"></script> <script src="js/coaches.js"></script> <script src="js/tags.js"></script> <script src="js/duration.js"></script> <title>Тренировки</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <div class="content"> <div class="block coach-list"> <div class="title">-Куратор-</div> <div id="coaches"></div> </div> <div class="block tag-list"> <div class="title">-Теги-</div> <div id="tags"></div> </div> <div class="block duration-list"> <div class="title">-Продолжительность- <br/><span>(на данный момент продолжительность указана для <?php echo $ratio; ?> % тренировок)</span></div> <div id="duration"> <div class="time-list" id="duration-from"> От: </div> <div class="time-list" id="duration-to"> До: </div> </div> </div> <div class="block"> <div class="buttons"> <div class="button"><a id="b1" href="workout_list.php?type=rnd">Запустить случайную</a></div> <div class="button"><a id="b2" href="workout_list.php?type=list">Показать список</a></div> </div> </div> </div> </div> <script> createCoachList(); createTagList(); createDurationList(); var button_rnd = document.getElementById('b1').href; var button_list = document.getElementById('b2').href; </script> </body> </html><file_sep>var tag_array = JSON.parse(tag_str); var tag_select = []; function createTagList(){ for (i=0;i<tag_array.length;i++){ document.getElementById('tags-del').innerHTML += '<div class="tag" id="tag' + i + '" style="background-color: #ccc; color: #333;" onclick="tagDel('+i+');">' + tag_array[i] + '</div>'; tag_select[i] = 0; j = 0; document.getElementById('tags-edit').innerHTML += '<div class="tag" id="tag-edit' + (i+j) + '" style="background-color: #ccc; color: #333;"><span onclick="tagEdit('+(i+j)+');">' + tag_array[i+j] + '</span></div>'; } } function tagDel(i){ if (tag_select[i] == 0) { document.getElementById('tag'+i).style.backgroundColor='#f00'; document.getElementById('tag'+i).style.color='#fff'; tag_select[i] = 1; changeLinks(); } else { document.getElementById('tag'+i).style.backgroundColor='#ccc'; document.getElementById('tag'+i).style.color='#333'; tag_select[i] = 0; changeLinks(); } } function changeLinks() { var tags = []; var j = 0; for (i=0; i<tag_select.length; i++){ if (tag_select[i]==1) { tags[j] = tag_array[i]; j++; } } var tag_str = JSON.stringify(tags); document.getElementById('b1').href = button_del + '?tag_str=' + tag_str; } function tagEdit(i) { document.getElementById('tag-edit'+i).innerHTML = '<input type="text" id="tag-edit-input'+i+'" autofocus name="tag" value="' + tag_array[i] + '">'; document.getElementById('tag-edit'+i).innerHTML += '<img src="icon/OK.png" width=20 class="ok-button" onClick="tagEditSend('+i+', \''+tag_array[i]+'\');"></div>'; } function tagEditSend(i, old_str) { var new_str = document.getElementById('tag-edit-input'+i).value; if (new_str!=old_str) { var url = 'php/tag_edit.php' $.post( url , { old_str: old_str, new_str: new_str }).done(function() { }); } document.getElementById('tag-edit'+i).innerHTML = ' '; document.getElementById('tag-edit'+i).innerHTML = '<b>' + new_str + '</b>'; } createTagList(); var button_del = document.getElementById('b1').href; <file_sep><?php if (!$_COOKIE['user_login']) echo "<script type='text/javascript'> location.replace('login.php'); </script> "; else echo "<div id='user'>Hi,".$_COOKIE['user_login']."! <a href='login.php?action=exit'>Выйти</a></div>"; ?> <file_sep><?php header("Content-Type: text/html; charset=utf-8"); include('config.php'); include('authorize.php'); include('php/tag_list.php'); echo "<script> var tag_str='$tag_str' ; var tag_del = []; </script>"; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/editor.css"> <script src="js/jquery.js"></script> <script src="js/help.js"></script> <title>Редактор тегов</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <span class="title">Удаление:</span> <div id="tags-del"></div> <div class="button"><a id="b1" href="tag_delete.php">Удалить все упоминания выделенных тегов</a></div> <span class="title">Редактирование:</span> <div id="tags-edit"></div> </div> <script src="js/tag_editor.js"></script> </body> </html><file_sep><?php include('authorize.php'); include('config.php'); $width = '90%'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/workout.css"> <link rel="stylesheet" href="css/warmup.css"> <script src="js/jquery.js"></script> <script src="js/help.js"></script> <script src="js/workout.js"></script> <title>Тренировка</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <div class="content"> <a href="workout.php?name=<?php echo $_GET['back_to']; ?>">Назад</a> <div class="row"> <div class="col"> <?php $name = '011.mp4'; require('php/video.php'); ?> </div> <div class="col"> <?php $name = '012.mp4'; require('php/video.php'); ?> </div> </div> </div> </div> </body> </html><file_sep># Сайт для упорядочивания своих видеозаписей. Делался для тренировок. Для примера работает на video.mda85.ru с первыми попавшимися под скачивание видео. <file_sep><?php header("Content-Type: text/html; charset=utf-8"); include('authorize.php'); include('config.php'); include('php/search_result.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/workout.css"> <script src="js/jquery.js"></script> <script src="js/help.js"></script> <script src="js/workout.js"></script> <title>Тренировка</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <input type="hidden" name="start" id="start" value=0> <input type="hidden" name="end" id="end" value=0> <div class="content" id="ppp"> <?php // echo "'".$res_json."'"; ?> <div id="video-list"> </div> </div> </div> <script> var video_str = '<?php echo $res_json; ?>' ; var video_array = JSON.parse(video_str); var j = 1; var start_list = 0; var end_list = video_array.length; document.getElementById('start').value = 0; document.getElementById('end').value = 9; if (end_list>10){ end_list=10; document.getElementById('ppp').innerHTML += "<div id='button-add' onclick='videoList();'>Показать ещё</div>"; } videoList(); </script> </body> </html><file_sep><?php $mysqli = new mysqli("localhost:3306", "user", "password", "db"); if ($mysqli->connect_errno) { echo "Не удалось подключиться к MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; exit(); } if (!$mysqli->set_charset("utf8")) { printf("Ошибка при загрузке набора символов utf8: %s\n", $mysqli->error); exit(); } ?><file_sep><?php include('config.php'); if (isset($_GET['name'])) { // удалить запись из workout, взяв id $sel = $mysqli->query("SELECT * FROM `workout` WHERE `name`='".$_GET['name']."'"); $sel->data_seek(0); $res = $sel->fetch_assoc(); $id = $res['id']; $del = $mysqli->query("DELETE FROM `workout` WHERE `name`='".$_GET['name']."'"); // удалить все привязанные теги $del = $mysqli->query("DELETE FROM `tag` WHERE `workout_id`=".$id); // удалить файл unlink('video/'.$_GET['name']); header('Location: workout_search.php'); } ?><file_sep><?php include('authorize.php'); include('config.php'); $name = $_GET['name']; $width = '100%'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/workout.css"> <script src="js/jquery.js"></script> <script src="js/help.js"></script> <script src="js/workout.js"></script> <title>Тренировка</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <div class="content"> <?php require('php/video.php'); ?> </div> </div> </body> </html><file_sep><?php include('authorize.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/index.css"> <link rel="stylesheet" href="css/workout.css"> <script src="js/jquery.js"></script> <title>Document</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <div class="content"> <?php include('incl/index_content.html'); ?> <?php require('php/index_video.php'); require('php/video.php'); ?> </div> </div> </body> </html><file_sep><?php $sel = $mysqli->query("SELECT * FROM `workout` WHERE `name`='".$name."'"); $sel->data_seek(0); $res = $sel->fetch_assoc(); $id = $res['id']; $description = $res['description']; $coach = $res['coach']; $duration = $res['duration']; $morning = 0; $tags = []; $sel = $mysqli->query("SELECT * FROM `tag` WHERE `workout_id`='".$id."'"); for($i=0;$i<$sel->num_rows; $i++){ $sel->data_seek($i); $res = $sel->fetch_assoc(); $tags[$i] = $res['name']; if ($res['name']=='утро'||$res['name']=='утроворк'||$res['name']=='Утро'){ $morning = 1; } } if ($morning==1){ echo "<a href='warmup.php?back_to=$name'>Разминка</a>"; } echo '<video width="'.$width.'" controls="controls"><source src="video/'.$name.'"></video>'; echo "<div id='info'><div class='description'>Описание: $description</div> <div class='description'>Куратор: $coach</div> <div class='description'>Продолжительность: $duration</div>"; for ($i = 0; $i < count($tags); $i++){ echo "<div class='tag'>".$tags[$i]."</div>"; } echo "</div>"; $tag_str = json_encode($tags); ?> <script> var tags = JSON.parse('<?php echo $tag_str; ?>'); function editInfo() { var form = '<form action="edit_info.php" method="POST"><input type="hidden" name="id" value="<?php echo $id; ?>">' + '<table><tr><td>Описание</td>' + '<td><textarea name="description" cols="40" rows="3"><?php echo $description;?></textarea></td>' + '</tr><tr><td>Тренер</td>' + '<td><input type="text" name="coach" value ="<?php echo $coach;?>"></td>' + '</tr><tr><td>Продолжительность</td>' + '<td><input type="text" name="duration" value =<?php echo $duration;?>></td>' + '</tr><tr><td>Теги<br/>(через пробел)</td>' + '<td><textarea name="tags" cols="40" rows="3">'; for (i=0; i<tags.length; i++){ form += tags[i] + " "; } form += '</textarea></td></tr></table><input type="submit" value="Отправить"></p></form>'; document.getElementById('info').innerHTML = form; document.getElementById('buttons').innerHTML = ''; } </script> <div id="buttons"> <div class="button-upd" onclick="editInfo();">Редактировать</div> <div class="button-del" onclick="deleteVideo('<?php echo $_GET['name']; ?>');">Удалить</div> </div><file_sep><?php include('config.php'); header("Content-Type: text/html; charset=utf-8"); if ($_GET['action']=='exit') { setcookie("user_login", $_COOKIE['user_login'], time()-3600, '/', 'video.mda85.ru'); echo "<script> location.replace('login.php'); </script> "; } if ($_POST['login']&&$_POST['password']) { // нет, защита здесь и сейчас не нужна, просто ограничитель. if (($_POST['password']=='<PASSWORD>')&&$_POST['login']=='test') { setcookie('user_login', 'User', time()+36000000, '/', 'video.mda85.ru'); header('Location: http://video.mda85.ru'); } else { echo "<script> alert('Неверный логин/пароль'); location.replace('login.php'); </script> "; } } else { ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/login.css"> <title>Авторизация</title> </head> <body> <div class="page"> <form class="form" method="post" action="login.php"> <div class="input"> <input type="text" name="login"> <input type="<PASSWORD>" name="password"> <input type="submit" class="button" value="Войти"> </div> </form> </div> <? } ?> </body> </html><file_sep><?php $sel = $mysqli->query("SELECT DISTINCT `name` FROM `tag` ORDER BY `name`"); $tag_arr = []; if ($sel->num_rows>0) { for($i=0;$i<$sel->num_rows; $i++){ $sel->data_seek($i); $res = $sel->fetch_assoc(); $tag_arr[$i] = $res['name']; } $tag_str = json_encode($tag_arr); } ?><file_sep><?php echo " <nav> <a href='workout_search.php'>Поиск</a> <a href='tag_editor.php'>Редактор</a> </nav> "; ?> <? /* <div class="button-help" onclick="setHelpRequest();">Нужна помощь?</div> <div id="request-back"> <div id="request-block"> В любое время, по любому вопросу, вообще по любому, не только по сайту.<br/> (текст необязателен, можно просто нажать кнопку "Отправить") <textarea id="request-text" cols="40" rows="4"></textarea> <div class="button-send" onclick="sendHelpRequest();">Отправить</div> <div class="button-close" onclick="closeHelpRequest();">Закрыть</div> </div> </div> */ ?><file_sep><?php include('../config.php'); if (isset($_POST['old_str'])&&isset($_POST['new_str'])) { $upd = $mysqli->query("UPDATE `tag` SET `name`='".$_POST['new_str']."' WHERE `name`='".$_POST['old_str']."'"); echo 'ok'; } ?><file_sep><?php include('authorize.php'); include('config.php'); if (isset($_GET['tag_str'])){ $tags = json_decode($_GET['tag_str']); for ($i=0; $i<count($tags); $i++){ $del = $mysqli->query("DELETE FROM `tag` WHERE `name`='".$tags[$i]."'"); } echo "<script type='text/javascript'>location.replace('tag_editor.php');</script>"; } else { echo "<script type='text/javascript'>alert('Чтобы что-то удалить надо что-то выбрать...'); location.replace('tag_editor.php');</script>"; } ?><file_sep>function setHelpRequest() { document.getElementById('request-back').style.display = 'block'; } function closeHelpRequest() { document.getElementById('request-back').style.display = 'none'; } function sendHelpRequest() { var url = 'http://damihailov85.website/my_bot/wh.php' if (document.getElementById('request-text').value) { var message = document.getElementById('request-text').value; } else message="!!!"; $.post( url , { message: message }).done(function(data) { if (data==1) alert('Отправлено.Ожидай результат!'); else alert('Что-то пошло не так! Позвони 89261764068 или воспользуйся другим известным способом связи!'); }); closeHelpRequest(); }<file_sep><?php include('config.php'); $query = "UPDATE `workout` SET `description`='".$_POST['description']."', `coach`='".$_POST['coach']."', `duration`=".$_POST['duration']." WHERE `id`=".$_POST['id']; $upd = $mysqli->query($query); if (isset($_POST['tags'])){ $sel = $mysqli->query("SELECT * FROM `tag` WHERE `workout_id`='".$_POST['id']."'"); $cur_tag = []; for($i=0;$i<$sel->num_rows; $i++){ $sel->data_seek($i); $res = $sel->fetch_assoc(); $cur_tag[$i] = $res['name']; } $new_tag = explode(" ", $_POST['tags']); for ($i=0; $i<count($new_tag); $i++){ $match = 0; for ($j=0; $j<count($cur_tag); $j++){ if ($new_tag[$i]==$cur_tag[$j]) { $match = 1; break; } } if ($match==0){ if (isset($new_tag[$i])&&$new_tag[$i]!=''&&$new_tag[$i]!=" "){ $query = "INSERT INTO `tag` (`name`, `workout_id`) VALUES ('".$new_tag[$i]."', ".$_POST['id'].")"; $ins = $mysqli->query($query); } } } for ($i=0; $i<count($cur_tag); $i++){ $match = 0; for ($j=0; $j<count($new_tag); $j++){ if ($cur_tag[$i]==$new_tag[$j]) { $match = 1; break; } } if ($match==0){ $query = "DELETE FROM `tag` WHERE `name`='".$cur_tag[$i]."' AND `workout_id`=".$_POST['id']; $del = $mysqli->query($query); } } } else { $query = "DELETE FROM `tag` WHERE `workout_id`=".$_POST['id']; $del = $mysqli->query($query); } $sel = $mysqli->query("SELECT * FROM `workout` WHERE `id`='".$_POST['id']."'"); $sel->data_seek(0); $res = $sel->fetch_assoc(); $name = $res['name']; echo "<script type='text/javascript'>location.replace('workout.php?name=".$name."');</script> "; ?><file_sep>var coach_array = JSON.parse(coach_str); var coach_select = []; function createCoachList(){ for (i=0;i<coach_array.length;i++){ if (coach_array[i]=='null'||(coach_array[i]+0)==0) { coach_array[i]='Не указан'; } if (coach_array[i]!='no_result'){ document.getElementById('coaches').innerHTML += '<div class="coach" id="coach' + i + '" style="background-color: #ccc; color: #333;" onclick="coachSel('+i+');">' + coach_array[i] + '</div>'; tag_select[i] = 0; } } if (coach_array.length==1&&coach_array[0]=='no_result') { document.getElementById('coaches').innerHTML = 'Пока что ни в одном видео не указан тренер. Выбирать не из чего..'; } } function coachSel(i) { for (j=0;j<coach_array.length;j++){ document.getElementById('coach'+j).style.backgroundColor='#ccc'; document.getElementById('coach'+j).style.color='#333'; } if (coach != coach_array[i]) { document.getElementById('coach'+i).style.backgroundColor='#333'; document.getElementById('coach'+i).style.color='#ccc'; coach = coach_array[i]; } else { coach = 'any'; } changeLinks(); }<file_sep> function videoList() { start = document.getElementById('start').value; end = document.getElementById('end').value; end++; end--; start++;start--; if (end>=video_array.length&&end!=9) { end = video_array.length; document.getElementById('button-add').innerHTML = ''; } for (i=start; i<end; i++){ if (video_array[i][3]==0) { var duration = '<span style="color:#f00; text-decoration: underline;" onclick="setDuration(\''+video_array[i][0]+'\');"> Не указано </span> '; } else { var duration = video_array[i][3]; } // getTags(video_array[i][4]); $bgc = j>0 ? '#ddd' : '#fff' ; document.getElementById('video-list').innerHTML += '<div class="row-video" style="background-color:' + $bgc + '">' + '<div id="col1">' + '<video width="250" height="150" controls="controls"><source src="video/' + video_array[i][0] + '"></video>' + '</div>' + '<div id="col2">' + video_array[i][1] + '<br/>' + 'Куратор:' + video_array[i][2] + '<br/>' + 'Продолжительность:' + duration + 'мин.<br/>' + '<a href="workout.php?name=' + video_array[i][0] + '">Поехали!</a>' + '</div>' + '</div>'; j *= -1; } if (end<video_array.length) { document.getElementById('start').value = end + 1; document.getElementById('end').value = end + 10; } } function deleteVideo(name) { var del = confirm("Удалить это видео?"); if (del) { location.replace('delete_video.php?name=' + name); } } function getTags(id) { var url = 'php/get_tags.php' $.post( url , { id: id }).done(function(data) { data = JSON.parse(data); }); } <file_sep><?php include('config.php'); header("Content-Type: text/html; charset=utf-8"); if($_FILES['f']['error'] == 0){ $ins = $mysqli->query("INSERT INTO `workout` (`name`) VALUES ('00000.mp3')"); // такого имени точно нет $sel = $mysqli->query("SELECT * FROM `workout` WHERE name='00000.mp3'"); $sel->data_seek(0); $res = $sel->fetch_assoc(); $temp = $_FILES['f']['tmp_name']; echo $temp."<br/>"; $type = explode(".", $_FILES['f']['name']); echo $type[1]."<br/>"; $name_file = ($res['id']+1000).'.'.$type[1]; move_uploaded_file($temp, "video/".$name_file); echo $_POST['description']."/".$_POST['coach']."/".$_POST['duration']."<br/>"; $description = (isset($_POST['description'])) ? $_POST['description'] : 0; $coach = (isset($_POST['coach'])) ? $_POST['coach'] : 'Не указан'; $duration = (isset($_POST['duration'])) ? $_POST['duration'] : 0; $query_upd = "UPDATE `workout` SET `name`='".$name_file."', `description`='".$description."', `coach`='".$coach."', `duration`=".$duration. " WHERE `id`=".$res['id']; $upd = $mysqli->query($query_upd); echo $query_upd."<br/>"; if (isset($_POST['tags'])) { $tag = explode(" ", $_POST['tags']); for ($i=0; $i < count($tag); $i++){ $ins = $mysqli->query("INSERT INTO `tag`(`name`, `workout_id`) VALUES ( '".$tag[$i]."', ".$res['id']." )"); } } echo "<script type='text/javascript'>location.replace('workout.php?name=".$name_file."');</script> "; } else { echo "<script type='text/javascript'>alert('Что-то пошло не так...');</script> "; // echo "<script type='text/javascript'>location.replace('download.php');</script> "; } ?><file_sep><?php $sel = $mysqli->query("SELECT DISTINCT `coach` FROM `workout` ORDER BY `coach`"); $coach_arr = []; if ($sel->num_rows>0) { for($i=0;$i<$sel->num_rows; $i++){ $sel->data_seek($i); $res = $sel->fetch_assoc(); $coach_arr[$i] = $res['coach']; } } else { $coach_arr[0] = 'no_result'; } $coach_str = json_encode($coach_arr); ?><file_sep><?php include('authorize.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/download.css"> <script src="js/jquery.js"></script> <script src="js/help.js"></script> <title>Загрузчик</title> </head> <body> <div class="page"> <?php include('php/links.php'); ?> <form enctype="multipart/form-data" action="download_file.php" method="POST"> <table> <tr> <td>Выбери файл<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /></td> <td><input type="file" name="f" accept="video/*"></td> </tr> <tr> <td>Описание</td> <td><textarea name="description" cols="40" rows="3"></textarea></td> </tr> <tr> <td>Тренер</td> <td><input type="text" name="coach"></td> </tr> <tr> <td>Продолжительность</td> <td><input type="text" name="duration"></td> </tr> <tr> <td>Теги<br/>(через пробел)</td> <td><textarea name="tags" cols="40" rows="3"></textarea></td> </tr> </table> <input type="submit" value="Отправить"></p> </form> </div> </body> </html>
7300d1f320d5dab4b58a4beeec69d99543d934e4
[ "JavaScript", "Markdown", "PHP" ]
26
PHP
damihailov85/video
3b988154e27c517d9ac007335eae413c38f3e1fc
53c0748560337528c961b4098473076d56b21362
refs/heads/master
<file_sep>var websocket = require('websocket-stream'); var socket = process.argv[2]; var ws = websocket("ws://" + socket); ws.pipe(process.stdout); <file_sep>var websocket = require('websocket-stream'); var port = process.argv[2]; var wss = websocket.createServer({ port: port }, handler); function handler(handle) { process.stdin.pipe(handle); } <file_sep>#!/usr/bin/env node require('../receive.js'); <file_sep># wls # Install ```sh $ npm install -g wls ``` # Usage ``` $ cat /dev/random | wls-send 9999 ``` ``` $ wls-receive localhost:9999 ```
d1f738708449f882db3cf6e0f5c6b4430f77c178
[ "JavaScript", "Markdown" ]
4
JavaScript
gkatsev/wls
afdfbd221b2a32baf551f601bda9f745056169ee
078f225301c30a33c8e794fbac439cc28eb0b12c
refs/heads/master
<file_sep>void letext(const char *argv[], int mem[]); void ledata(const char *argv[], int mem[]); void tipoR(int bancoReg[], int rs, int rt, int rd, int shamt, int funct, int *HI, int *LO, int *PC); void tipoI(int bancoReg[], int opcode, int rs, int rt, int immediate); void tipoJ(int mem[], int bancoReg[], int opcode, int immediate, int *PC); //Tipo R void add(int bancoReg[], int rs, int rt, int rd); void sub(int bancoReg[], int rs, int rt, int rd); void mult(int bancoReg[], int rs, int rt,int *HI, int *LO); void divv(int bancoReg[], int rs, int rt,int *HI, int *LO); void mfhi(int bancoReg[], int rd, int *HI); void mflo(int bancoReg[], int rd, int *LO); void and(int bancoReg[], int rs, int rt, int rd); void or(int bancoReg[], int rs, int rt, int rd); void slt(int bancoReg[], int rs, int rt, int rd); void sll(int bancoReg[], int rt, int rd, int shamt); void srl(int bancoReg[], int rt, int rd, int shamt); void jr(int bancoReg[], int rs, int *PC); //Tipo I void addi(int bancoReg[], int rs, int immediate, int rt); void addiu(int bancoReg[], int rs, int rt, int immediate); //Tipo J //funçoes acima terminadas void j(int mem[], int *PC, int immediate); void jal(int mem[], int bancoReg[], int immediate, int *PC); void lw(int *mem, int C, int s, int *t); void lh(int *mem, int C, int s, int *t); void lb(int *mem, int C, int s, int *t); void sw(int *mem, int C, int s, int *t); void sh(int *mem, int C, int s, int *t); void sb(int *mem, int C, int s, int *t); void lui(int *d, int C); void andi(int *d, int s, int t); void ori(int *d, int s, int t); void slti(int *d, int s, int t); void beq(int *PC, int s, int t, int C); void bne(int *PC, int s, int t, int C); void syscall(int bancoReg[],int *EXIT);<file_sep>#include <stdio.h> #include <stdlib.h> void letext(const char *argv[], int mem[]){ //lendo .text FILE *f; int lSize; f = fopen(argv[1],"rb"); if(f == NULL){ printf("Erro ao abrir o arquivo\n"); } //lSize = num de bytes do arquivo de entrada fseek (f , 0 , SEEK_END); lSize = ftell (f); rewind (f); //copiando a entrada pra memória for (int i = 0; i < lSize/4; i++){ fread(&mem[i], 4, 1, f); } fclose(f); } void ledata(const char *argv[], int mem[]){ FILE *f; int lSize; f = fopen(argv[2],"rb"); if(f == NULL){ printf("Erro ao abrir o arquivo\n"); } //lSize = num de bytes do arquivo de entrada fseek (f , 0 , SEEK_END); lSize = ftell (f); rewind (f); //copiando a entrada pra memória for (int i = 0x2000/4; i < 0x2000/4 + lSize/4; i++){ fread(&mem[i], 4, 1, f); } fclose(f); } void add(int bancoReg[], int rs, int rt, int rd){ bancoReg[rd] = bancoReg[rs] + bancoReg[rt]; } void sub(int bancoReg[], int rs, int rt, int rd){ bancoReg[rd] = bancoReg[rs] - bancoReg[rt]; } void addi(int bancoReg[], int rs, int rt, int immediate){ bancoReg[rt] = bancoReg[rs] + immediate; } void addiu(int bancoReg[], int rs, int rt, int immediate){ bancoReg[rt] = bancoReg[rs] + (unsigned)immediate; } /* void mult(int bancoReg[], int rs, int rt,int *HI, int *LO){ long long int aux,mascHI,mascLO; aux = bancoReg[rs] * bancoReg[rt]; mascHI = 0xffffffff00000000; mascLO = 0x00000000ffffffff; *HI = (int)((aux & mascHI) >> 32); *LO = (int)(aux & mascLO); } */ void divv(int bancoReg[], int rs, int rt,int *HI, int *LO){ *HI = bancoReg[rs]%bancoReg[rt]; *LO = bancoReg[rs]/bancoReg[rt]; } void mfhi(int bancoReg[], int rd, int *HI){ bancoReg[rd] = *HI; } void mflo(int bancoReg[], int rd, int *LO){ bancoReg[rd] = *LO; } void and(int bancoReg[], int rs, int rt, int rd){ bancoReg[rd] = bancoReg[rs] & bancoReg[rt]; } void or(int bancoReg[], int rs, int rt, int rd){ bancoReg[rd] = bancoReg[rs] | bancoReg[rt]; } void slt(int bancoReg[], int rs, int rt, int rd){ bancoReg[rd] = (bancoReg[rs] < bancoReg[rt]); } void sll(int bancoReg[], int rt, int rd, int shamt){ bancoReg[rd] = bancoReg[rt] << shamt; } void srl(int bancoReg[], int rt, int rd, int shamt){ bancoReg[rd] = bancoReg[rt] >> shamt; } void jr(int bancoReg[], int rs, int *PC){ *PC = bancoReg[rs]; } void j(int mem[], int *PC, int immediate){ int masc = 0xf0000000,pc,C; pc = (mem[(*PC)+1] & masc);//pc = $PC[31-28]; C = immediate << 2; *PC = (pc | C); } void jal(int mem[], int bancoReg[], int immediate, int *PC){ bancoReg[31] = mem[*PC]; j(mem,PC,immediate); } void syscall(int bancoReg[],int *EXIT){ char *string; int n; int r; switch(bancoReg[2]) { case 1: printf("%d", bancoReg[4]); break; /*case 2: printf("%s\n", ); break; case 3: break;*/ case 4: printf("%s", (char *)bancoReg[4]); break; case 5: scanf("%d",&bancoReg[2]); break; /*case 6: scanf("%f"); break; case 7: scanf("%lf"); break;*/ case 8: string = (char *) malloc((bancoReg[5]+1)*sizeof(char)); scanf("%s", string); bancoReg[4] = (int)string; free(string); break; case 10: *EXIT = 1; break; case 11: printf("%c", bancoReg[4]); break; case 12: scanf("%c",&bancoReg[2]); break; case 34: printf("%08x", bancoReg[4]); break; case 35: n = bancoReg[4]; for(int i = 31; i >= 0; i--) { r = n >> i; if(r & 1) printf("1"); else printf("0"); } break; case 36: printf("%u", bancoReg[4]); break; } } void tipoR(int bancoReg[], int rs, int rt, int rd, int shamt, int funct, int *HI, int *LO, int *PC){ switch(funct){ //add case 0x20: add(bancoReg, rs, rt, rd); break; //sub case 0x22: sub(bancoReg, rs, rt, rd); break; //mult case 0x18: //mult(bancoReg, rs, rt, rd); break; //divv case 0x1a: divv(bancoReg, rs, rt, HI, LO); break; //mfhi case 0x10: mfhi(bancoReg, rd, HI); break; //mflo case 0x12: mflo(bancoReg, rd, LO); break; //and case 0x24: and(bancoReg, rs, rt, rd); break; //or case 0x25: or(bancoReg, rs, rt, rd); break; //slt case 0x2a: slt(bancoReg, rs, rt, rd); break; //sll case 0x0: sll(bancoReg,rt,rd,shamt); break; //srl case 0x2: srl(bancoReg,rt,rd,shamt); break; //jr case 0x8: jr(bancoReg,rs,PC); break; } } void tipoI(int bancoReg[], int opcode,int rs, int rt, int immediate){ switch(opcode){ case 0x8: bancoReg[rt] = bancoReg[rs] + immediate; break; } } /* jump opcode == 000010; jal opcode == 000011; */ void tipoJ(int mem[], int bancoReg[], int opcode, int immediate, int *PC){ switch(opcode){ //jump case 0x2: j(mem,PC,immediate); break; //jal case 0x3: jal(mem,bancoReg, immediate, PC); break; } }<file_sep>#include <stdio.h> #include <stdlib.h> #include "func.h" typedef char String[32]; int main(int argc, const char *argv[]){ int mem[1024*4] = {0}; int bancoReg[32] = {0}; int PC = 0; int mascara; int inst; int opcode; int rs,rt,rd,shamt,funct; int immediate; int EXIT = 0; int HI = 0,LO = 0; // int bancoReg[32] = {0}; //Confere se o numero de argumentos está correto if(argc != 3){ printf("Numero de argumentos invalidos\n"); return 1; } // Começo Leitura //Le arquivo text.bin e salva na memória letext(argv,mem); //Le arquivo data.bin e salva na memória ledata(argv,mem); // Fim Leitura // Inicio Decode while(EXIT == 0){ inst = mem[PC]; printf(" %d %08x\n", PC,inst); mascara = 0xfc000000; opcode = (inst & mascara) >> 26; if(inst == 0xc){ syscall(bancoReg,&EXIT); }else if(opcode == 0){ mascara = 0x3e00000; rs = (inst & mascara) >> 21; rt = (inst & (mascara >> 5)) >> 16; rd = (inst & (mascara >> 10)) >> 11; shamt = (inst & (mascara >> 15)) >> 6; mascara = 0x3f; funct = (inst & mascara); tipoR(bancoReg, rs, rt, rd, shamt, funct,&HI,&LO,&PC); } else if(opcode != 0x10 && opcode != 0x11){ mascara = 0x3e00000; rs = (inst & mascara) >> 21; rt = (inst & (mascara >> 5)) >> 16; mascara = 0x0000ffff; immediate = (inst & mascara); tipoI(bancoReg, opcode, rs, rt, immediate); }else{ immediate = inst >> 6; tipoJ(mem,bancoReg, opcode, immediate, &PC); } PC++; } for (int i = 0; i < 32; ++i) { printf("%08x\n", bancoReg[i]); } return 0; }<file_sep># Arq Autores: <NAME>, <NAME> e <NAME> 32bit MIPS emulator
ee904d8175d67a803bcb577611929fa20884a2f9
[ "Markdown", "C" ]
4
C
Gls-Facom/Arq
a14d9aaf1242cefd95387b796b2412fd67561f8c
c996f86b7a9869f578bb490ed86cffe1399313bd
refs/heads/master
<repo_name>Szeba25/Cheese<file_sep>/code/taskperformerinterface.cpp #include "taskperformerinterface.h" TaskPerformerInterface::~TaskPerformerInterface() { } <file_sep>/code/speedtester.cpp #include "speedtester.h" SpeedTester::SpeedTester(double n1, double n2, char op, unsigned int count): number1(n1), number2(n2), operation(op), count(count) { } double SpeedTester::getNumber1() const { return number1; } double SpeedTester::getNumber2() const { return number2; } char SpeedTester::getOperation() const { return operation; } unsigned int SpeedTester::getCount() const { return count; } SpeedTester::time_measure SpeedTester::test() const { chrono::system_clock::time_point t1 = chrono::high_resolution_clock::now(); double res; if (operation == '*') { for (unsigned int i=1; i<count; i++) res=number1*number2; } else if (operation == '/') { for (unsigned int i=1; i<count; i++) res=number1/number2; } else if (operation == '+') { for (unsigned int i=1; i<count; i++) res=number1+number2; } else if (operation == '-') { for (unsigned int i=1; i<count; i++) res=number1-number2; } chrono::system_clock::time_point t2 = chrono::high_resolution_clock::now(); return t2-t1; } <file_sep>/code/main.cpp #include <iostream> #include <thread> #include <list> #include "speedtester.h" #include "fibonacci.h" #include "logreader.h" #include "taskperformerinterface.h" #include "taskcontainer.h" #include "worker.h" using namespace std; int main() { TaskContainer taskContainer; unsigned int n = thread::hardware_concurrency(); if (n < 3) n = 3; if (n > 8) n = 8; int maxThreads = n-1; list<Worker*> workers; for (int i = 0; i < maxThreads; i++) { workers.push_back(new Worker(i)); } cout << "Executing on " << maxThreads << " number of threads" << endl << endl; for (Worker*& w : workers) { w->reg(&TaskObserver::getInstance()); w->start(); } TaskPerformerInterface* task = taskContainer.getNextTask(); while (task != nullptr) { for (Worker*& w : workers) { if (!w->isBusy()) { w->setTask(task); task = taskContainer.getNextTask(); break; } } } for (Worker*& w : workers) { w->join(); delete w; } taskContainer.saveOutput(); return 0; } <file_sep>/code/fibonacci.cpp #include "fibonacci.h" unsigned long long int Fibonacci::getFibo(unsigned int n) { if (n==0) return 0; else if (n==1) return 1; else return getFibo(n-1) + getFibo(n-2); } <file_sep>/code/worker.cpp #include "worker.h" Worker::Worker(int id) : id(id), workerThread(nullptr), task(nullptr), killed(false) { } Worker::~Worker() { if (workerThread != nullptr) { delete workerThread; } } void Worker::reg(TaskObserver* observer) { taskObserver = observer; } void Worker::start() { workerThread = new thread(Worker::work, this); } void Worker::join() { if (workerThread != nullptr) { kill(); workerThread->join(); } } void Worker::setTask(TaskPerformerInterface *task) { mtx.lock(); this->task = task; mtx.unlock(); } bool Worker::isBusy() { mtx.lock(); bool result = (task != nullptr); mtx.unlock(); return result; } void Worker::work() { while (!isKilled()) { if (isBusy()) { taskObserver->startTask(id, task); chrono::system_clock::time_point begin = chrono::high_resolution_clock::now(); task->execute(); chrono::system_clock::time_point end = chrono::high_resolution_clock::now(); chrono::duration<long long int, std::nano> elapsed = (end-begin); taskObserver->endTask(id, task, elapsed); setTask(nullptr); } } } void Worker::kill() { mtx.lock(); killed = true; mtx.unlock(); } bool Worker::isKilled() { mtx.lock(); bool result = killed; mtx.unlock(); return result; } <file_sep>/code/worker.h #ifndef WORKER_H #define WORKER_H #include <iostream> #include <thread> #include <mutex> #include <chrono> #include "taskperformerinterface.h" #include "taskobserver.h" using namespace std; class Worker { public: Worker(int id); ~Worker(); void reg(TaskObserver* observer); void start(); void join(); void setTask(TaskPerformerInterface* task); // Function guarded by mutex bool isBusy(); // Function guarded by mutex private: int id; thread* workerThread; TaskPerformerInterface* task; // Guarded by mutex bool killed; // Guarded by mutex mutex mtx; TaskObserver* taskObserver; void work(); void kill(); // Function guarded by mutex bool isKilled(); // Function guarded by mutex }; #endif // WORKER_H <file_sep>/code/speedtesterperformer.cpp #include "speedtesterperformer.h" SpeedTesterPerformer::SpeedTesterPerformer(double n1, double n2, char op, unsigned int count) : n1(n1), n2(n2), op(op), count(count) { speedTester = new SpeedTester(n1, n2, op, count); } SpeedTesterPerformer::~SpeedTesterPerformer() { delete speedTester; } void SpeedTesterPerformer::execute() { time = speedTester->test(); } string SpeedTesterPerformer::getDescription() const { stringstream ss; ss << fixed; ss << setprecision(6); ss << "speed test, numbers: " << n1 << ", " << n2 << ", operation: " << op << ", iterations: " << count; return ss.str(); } string SpeedTesterPerformer::getResult() const { stringstream ss; ss << fixed; ss << setprecision(6); ss << time.count() << " milliseconds (" << (count/(time.count()))/1000 << " million operations per second)"; return ss.str(); } <file_sep>/code/logreader.h #ifndef LOGREADER_H #define LOGREADER_H #include <iostream> #include <set> #include <exception> #include <fstream> #include <string> #include <list> #include <sstream> using namespace std; class LogReader { public: enum LogErrorType // Enum to handle error types { LET_RELOGIN = 0, LET_LOGOUT_WITHOUT_LOGIN, LET_STAYED_LOGGED_IN, LET_FAILED_LOGIN, LET_INVALID_ENTRY_TYPE, LET_INVALID_USER_ID }; struct LogEntryError // Inside structure to save errors { int line, user_id; // Line where occured, user_id (-1 is the error is invalid entry or id) LogErrorType error_type; // type of error LogEntryError(int line, int id, LogErrorType type): line(line), user_id(id), error_type(type) {} }; private: unsigned int failed_logins=0; // Number of failed logins list<LogEntryError> entry_errors; // List of errors void evaluateLine(int line, const string &line_data, set<int>& logins); // New: Evaluate a line of data void checkForLoggedInUsers(int line, set<int>& logins); // New: Add an error log after all logged in users public: unsigned int getFailedLogins() const; const list<LogEntryError> &getEntryErrors() const; void clearData(); // To initialize member variables static string errorTypeToString(LogErrorType type); // Static function to convert error type from enum to text bool readLog(const string &file_name); // Function to read the file (must be written) }; #endif // LOGREADER_H <file_sep>/code/logreaderperformer.h #ifndef LOGREADERPERFORMER_H #define LOGREADERPERFORMER_H #include <sstream> #include "taskperformerinterface.h" #include "logreader.h" class LogReaderPerformer : public TaskPerformerInterface { public: LogReaderPerformer(const string& fileName); virtual ~LogReaderPerformer(); virtual void execute(); virtual string getDescription() const; virtual string getResult() const; private: string fileName; bool fileExists; LogReader* logReader; }; #endif // LOGREADERPERFORMER_H <file_sep>/code/fibonacciperformer.cpp #include "fibonacciperformer.h" FibonacciPerformer::FibonacciPerformer(int number) : number(number), fibonacciNumber(0) { } FibonacciPerformer::~FibonacciPerformer() { } void FibonacciPerformer::execute() { fibonacciNumber = Fibonacci::getFibo(number); } string FibonacciPerformer::getDescription() const { stringstream ss; ss << "fibonacci, number: " << number; return ss.str(); } string FibonacciPerformer::getResult() const { return to_string(fibonacciNumber); } <file_sep>/code/taskperformerinterface.h #ifndef TASKPERFORMERINTERFACE_H #define TASKPERFORMERINTERFACE_H #include <string> using namespace std; class TaskPerformerInterface { public: virtual ~TaskPerformerInterface(); // Because it is an abstract class virtual void execute() = 0; // The function to execute the task virtual string getDescription() const = 0; // Returns a description of the task as a string virtual string getResult() const = 0; // Returns the result of the task as a string }; #endif // TASKPERFORMERINTERFACE_H <file_sep>/code/fibonacciperformer.h #ifndef FIBONACCIPERFORMER_H #define FIBONACCIPERFORMER_H #include <sstream> #include "taskperformerinterface.h" #include "fibonacci.h" using namespace std; class FibonacciPerformer : public TaskPerformerInterface { public: FibonacciPerformer(int number); virtual ~FibonacciPerformer(); virtual void execute(); virtual string getDescription() const; virtual string getResult() const; private: unsigned int number; unsigned long long int fibonacciNumber; }; #endif // FIBONACCIPERFORMER_H <file_sep>/code/logreaderperformer.cpp #include "logreaderperformer.h" LogReaderPerformer::LogReaderPerformer(const string &fileName) : fileName(fileName), fileExists(false) { logReader = new LogReader(); } LogReaderPerformer::~LogReaderPerformer() { delete logReader; } void LogReaderPerformer::execute() { fileExists = logReader->readLog(fileName); } string LogReaderPerformer::getDescription() const { stringstream ss; ss << "logreader, file: " << fileName; return ss.str(); } string LogReaderPerformer::getResult() const { if (fileExists) { stringstream ss; ss << "number of failed logins: " << logReader->getFailedLogins() << endl; list<LogReader::LogEntryError> log = logReader->getEntryErrors(); for (const LogReader::LogEntryError &e : log) { ss << "in line " << e.line << ": user id: " << e.user_id << ", problem: " << LogReader::errorTypeToString(e.error_type) << endl; } return ss.str(); } else { return string("Cannot read file\n"); } } <file_sep>/code/fibonacci.h #ifndef FIBONACCI_H #define FIBONACCI_H class Fibonacci { public: static unsigned long long int getFibo(unsigned int n); // Standard recursive fibonacci function, only it is static }; #endif // FIBONACCI_H <file_sep>/code/speedtester.h #ifndef SPEEDTESTER_H #define SPEEDTESTER_H #include <chrono> using namespace std; class SpeedTester { double number1, number2; char operation; unsigned int count; public: typedef chrono::duration<double, std::milli> time_measure; // Just a typedef SpeedTester(double n1, double n2, char op, unsigned int count); double getNumber1() const; double getNumber2() const; char getOperation() const; unsigned int getCount() const; time_measure test() const; // The function that performs the test }; #endif // SPEEDTESTER_H <file_sep>/code/logreader.cpp #include "logreader.h" void LogReader::evaluateLine(int line, const string &line_data, set<int> &logins) { if (line_data != "") { stringstream ss(line_data); string entry(""); string strid(""); ss >> entry; ss >> strid; int id = -1; // No user ID, or NaN try { id = stoi(strid); } catch (exception& e) { entry_errors.push_back(LogEntryError(line, id, LET_INVALID_USER_ID)); return; // Skip all other operations } // Find out if the user is logged in or not (points to end iterator) set<int>::iterator find_it = logins.find(id); if (entry == "userlogin") { if (find_it != logins.end()) { // User is already logged in entry_errors.push_back(LogEntryError(line, id, LET_RELOGIN)); } else { // Login the user... logins.insert(id); } } else if (entry == "userlogout") { if (find_it == logins.end()) { // User logout without login entry_errors.push_back(LogEntryError(line, id, LET_LOGOUT_WITHOUT_LOGIN)); } else { // Logout the user... logins.erase(find_it); } } else if (entry == "failedlogin") { // User failed to login entry_errors.push_back(LogEntryError(line, id, LET_FAILED_LOGIN)); failed_logins++; } else { // Invalid entry entry_errors.push_back(LogEntryError(line, -1, LET_INVALID_ENTRY_TYPE)); } } } void LogReader::checkForLoggedInUsers(int line, set<int> &logins) { for (int id : logins) { entry_errors.push_back(LogEntryError(line, id, LET_STAYED_LOGGED_IN)); } } unsigned int LogReader::getFailedLogins() const { return failed_logins; } const list<LogReader::LogEntryError> &LogReader::getEntryErrors() const { return entry_errors; } void LogReader::clearData() { failed_logins=0; entry_errors.clear(); } string LogReader::errorTypeToString(LogReader::LogErrorType type) { if (type==LET_RELOGIN) return "relogin"; else if (type==LET_LOGOUT_WITHOUT_LOGIN) return "logout without login"; else if (type==LET_STAYED_LOGGED_IN) return "stayed logged in at the end"; else if (type==LET_FAILED_LOGIN) return "failed login"; else if (type==LET_INVALID_ENTRY_TYPE) return "invalid log entry type"; else if (type==LET_INVALID_USER_ID) return "invalid user id"; return "----------"; } bool LogReader::readLog(const string &file_name) { ifstream file(file_name); string line_data; set<int> logins; int line = 1; if (file.is_open()) { while (file.good()) { getline(file, line_data); evaluateLine(line, line_data, logins); line++; } file.close(); checkForLoggedInUsers(line, logins); return true; } else { return false; } } <file_sep>/code/taskcontainer.cpp #include "taskcontainer.h" TaskContainer::TaskContainer() { ifstream file("tasklist.txt"); string data; bool completed = false; if (file.is_open()) { while (file.good() && !completed) { file >> data; if (data == "*") { completed = true; } else if (data == "fibonacci") { int number; file >> number; //cout << number << endl; tasks.push_back(new FibonacciPerformer(number)); } else if (data == "speedtest") { double n1, n2; char op; int count; file >> n1 >> op >> n2 >> count; //cout << n1 << " " << op << " " << n2 << " " << count << endl; tasks.push_back(new SpeedTesterPerformer(n1, n2, op, count)); } else if (data == "readlog") { string fileName; file >> fileName; //cout << fileName << endl; tasks.push_back(new LogReaderPerformer(fileName)); } } file.close(); } else { cout << "ERROR: Missing tasklist.txt file" << endl; } currentTask_it = tasks.begin(); } TaskContainer::~TaskContainer() { for (TaskPerformerInterface*& task : tasks) { delete task; } } TaskPerformerInterface *TaskContainer::getNextTask() { if (currentTask_it == tasks.end()) { return nullptr; } else { list<TaskPerformerInterface*>::iterator it = currentTask_it; currentTask_it++; return *it; } } void TaskContainer::saveOutput() { ofstream file("output.txt"); if (file.is_open()) { for (TaskPerformerInterface*& task : tasks) { file << endl << "Task description: " << task->getDescription() << endl; file << "Result:" << endl; file << task->getResult() << endl; file << "---------------------------------" << endl; } } file.close(); } <file_sep>/code/speedtesterperformer.h #ifndef SPEEDTESTERPERFORMER_H #define SPEEDTESTERPERFORMER_H #include <iomanip> #include <sstream> #include "taskperformerinterface.h" #include "speedtester.h" class SpeedTesterPerformer : public TaskPerformerInterface { public: SpeedTesterPerformer(double n1, double n2, char op, unsigned int count); virtual ~SpeedTesterPerformer(); virtual void execute(); virtual string getDescription() const; virtual string getResult() const; private: SpeedTester* speedTester; SpeedTester::time_measure time; double n1, n2; char op; unsigned int count; }; #endif // SPEEDTESTERPERFORMER_H <file_sep>/code/taskcontainer.h #ifndef TASKCONTAINER_H #define TASKCONTAINER_H #include <iostream> #include <fstream> #include <sstream> #include <list> #include "taskperformerinterface.h" #include "fibonacciperformer.h" #include "speedtesterperformer.h" #include "logreaderperformer.h" using namespace std; class TaskContainer { public: TaskContainer(); ~TaskContainer(); TaskPerformerInterface* getNextTask(); void saveOutput(); private: list<TaskPerformerInterface*> tasks; list<TaskPerformerInterface*>::iterator currentTask_it; }; #endif // TASKCONTAINER_H <file_sep>/code/taskobserver.h #ifndef TASKOBSERVER_H #define TASKOBSERVER_H #include <chrono> #include <ctime> #include <iostream> #include <mutex> #include "taskperformerinterface.h" using namespace std; class TaskObserver { public: static TaskObserver& getInstance(); void startTask(int id, TaskPerformerInterface* task); void endTask(int id, TaskPerformerInterface* task, chrono::duration<long long int, nano> elapsed); private: TaskObserver(); TaskObserver(const TaskObserver &other); mutex mtx; void printTime(); }; #endif // TASKOBSERVER_H <file_sep>/code/taskobserver.cpp #include "taskobserver.h" TaskObserver &TaskObserver::getInstance() { static TaskObserver instance; return instance; } TaskObserver::TaskObserver() {} void TaskObserver::startTask(int id, TaskPerformerInterface* task) { mtx.lock(); printTime(); cout << "Task started on thread: " << id << ": " << task->getDescription() << endl << endl; mtx.unlock(); } void TaskObserver::endTask(int id, TaskPerformerInterface* task, chrono::duration<long long int, nano> elapsed) { mtx.lock(); printTime(); cout << "Task ended on thread: " << id << ": " << task->getDescription() << endl; cout << "Execution time: " << elapsed.count() << " nanoseconds" << endl << endl; mtx.unlock(); } void TaskObserver::printTime() { chrono::system_clock::time_point p = chrono::system_clock::now(); time_t t = chrono::system_clock::to_time_t(p); cout << ctime(&t); }
16c95114b5afa5335bfb8f4f4f1cd6b321215b60
[ "C++" ]
21
C++
Szeba25/Cheese
bcc08233b80103c66eab0036026e40dcfec4be02
e81893738a40fca61bbd6a478bfb21473709f92f
refs/heads/master
<repo_name>wall-et/hello-git<file_sep>/a.rb puts "Hello, A!" <file_sep>/b.rb puts "Hello, B!"
2f7deff7db28623d89de2cb1f43ac94d8ffa8292
[ "Ruby" ]
2
Ruby
wall-et/hello-git
033ce89cb9e376ebaaad7d5aef60088e340d9445
b23cc3af9f9beb3badd9d6fcb1e8763f5f9cb278
refs/heads/master
<repo_name>kirillsurkov/cudaFlipMetric<file_sep>/FlipMetric.hpp #pragma once #include <memory> class FlipMetricImpl; class FlipMetric { private: std::shared_ptr<FlipMetricImpl> m_impl; public: FlipMetric(const unsigned char* reference, unsigned int width, unsigned int height, float ppd = 67.0206f); ~FlipMetric(); float compareDevice(const unsigned char* image); float compareHost(const unsigned char* image); }; <file_sep>/Makefile all: nvcc main.cpp FlipMetric.cpp FlipMetricImpl.cu Image.cpp -arch=compute_35 -g -rdc=true -lpng -lcudnn <file_sep>/FlipMetric.cpp #include "FlipMetric.hpp" #include "FlipMetricImpl.cuh" FlipMetric::FlipMetric(const unsigned char* reference, unsigned int width, unsigned int height, float ppd) { m_impl = std::make_shared<FlipMetricImpl>(reference, width, height, ppd); } FlipMetric::~FlipMetric() { } float FlipMetric::compareDevice(const unsigned char* image) { return m_impl->compareDevice(image); } float FlipMetric::compareHost(const unsigned char* image) { return m_impl->compareHost(image); } <file_sep>/Image.cpp #include "Image.hpp" #include "svpng.inc" #include <iostream> #include <stdexcept> #include <cmath> #include <thread> #include <mutex> #include <png.h> void Image::brightnessContrast(float brightness, float contrast, unsigned char& r, unsigned char& g, unsigned char& b) { float factor = (259.0f * (contrast + 255)) / (255.0f * (259 - contrast)); r = std::max(std::min(brightness + factor * (r - 128) + 128, 255.0f), 0.0f); g = std::max(std::min(brightness + factor * (g - 128) + 128, 255.0f), 0.0f); b = std::max(std::min(brightness + factor * (b - 128) + 128, 255.0f), 0.0f); } void Image::savePNG(const std::string& filename, std::shared_ptr<Image> image) { std::vector<unsigned char> data(image->m_width * image->m_height * 3); for (unsigned int y = 0; y < image->m_height; y++) { auto pixelInput = image->m_dataPtr + y * image->m_stride; auto pixelOutput = data.data() + y * image->m_width * 3; for (unsigned int x = 0; x < image->m_width; x++) { pixelOutput[x * 3 + 0] = pixelInput[x * 3 + 0]; pixelOutput[x * 3 + 1] = pixelInput[x * 3 + 1]; pixelOutput[x * 3 + 2] = pixelInput[x * 3 + 2]; } } FILE* file = fopen(filename.c_str(), "wb"); svpng(file, image->m_width, image->m_height, data.data(), 0); fclose(file); } std::shared_ptr<Image> Image::readPNG(const std::string& filename) { int width; int height; unsigned char header[8]; // 8 is the maximum size that can be checked /* open file and test for it being a png */ FILE *fp = fopen(filename.c_str(), "rb"); if (!fp) throw std::runtime_error("[read_png_file] File '" + filename + "' could not be opened for reading"); fread(header, 1, 8, fp); if (png_sig_cmp(header, 0, 8)) throw std::runtime_error("[read_png_file] File '" + filename + "' is not recognized as a PNG file"); /* initialize stuff */ png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) throw std::runtime_error("[read_png_file] png_create_read_struct failed"); png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) throw std::runtime_error("[read_png_file] png_create_info_struct failed"); if (setjmp(png_jmpbuf(png_ptr))) throw std::runtime_error("[read_png_file] Error during init_io"); png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); png_byte color_type = png_get_color_type(png_ptr, info_ptr); unsigned int channels = (color_type == PNG_COLOR_TYPE_RGB ? 3 : 4); png_read_update_info(png_ptr, info_ptr); /* read file */ if (setjmp(png_jmpbuf(png_ptr))) throw std::runtime_error("[read_png_file] Error during read_image"); png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for (int y=0; y<height; y++) row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_ptr,info_ptr)); png_read_image(png_ptr, row_pointers); std::vector<unsigned char> data; for (int y = 0; y < height; y++) { png_byte* row = row_pointers[y]; for (int x = 0; x < width; x++) { png_byte* pixel = &row[x * channels]; data.push_back(pixel[0]); data.push_back(pixel[1]); data.push_back(pixel[2]); } free(row); } free(row_pointers); png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); fclose(fp); return std::make_shared<Image>(width, height, width * 3, std::move(data)); } Image::Image(unsigned int width, unsigned int height, unsigned int stride, std::vector<unsigned char>&& data) : m_width(width), m_height(height), m_stride(stride), m_data(data), m_dataPtr(m_data.data()) { } Image::Image(unsigned int width, unsigned int height, unsigned int stride, unsigned char* data) : m_width(width), m_height(height), m_stride(stride), m_dataPtr(data) { } unsigned int Image::getWidth() const { return m_width; } unsigned int Image::getHeight() const { return m_height; } unsigned int Image::getStride() const { return m_stride; } const unsigned char* Image::getData() const { return m_dataPtr; } unsigned char* Image::getData() { return m_dataPtr; } void Image::applyBC(float brightness, float contrast) { unsigned int totalPixels = m_width * m_height; unsigned char* thisData = m_data.data(); for (unsigned int i = 0; i < totalPixels; i++) { unsigned int x = i % m_width; unsigned int y = i / m_height; unsigned char* pixel = thisData + (y * m_width + x) * 3; brightnessContrast(brightness, contrast, pixel[0], pixel[1], pixel[2]); } } <file_sep>/Color.hpp #pragma once struct Color { float x; float y; float z; Color& operator+=(const Color& other) { x += other.x; y += other.y; z += other.z; return *this; } __device__ friend Color operator+(const Color& left, const Color& right) { return Color{left.x + right.x, left.y + right.y, left.z + right.z}; } }; <file_sep>/main.cpp #include <iostream> #include "Image.hpp" #include "FlipMetric.hpp" int main() { std::vector<unsigned char> imgData; auto img1 = Image::readPNG("input_mj.png"); auto img2 = Image::readPNG("best.png"); FlipMetric metric(img1->getData(), img1->getWidth(), img1->getHeight()); std::cout << "1: " << metric.compareHost(img1->getData()) << std::endl; imgData = std::vector<unsigned char>(img1->getWidth() * img1->getHeight() * 3); std::cout << "2: " << metric.compareHost(img2->getData()) << std::endl; imgData = std::vector<unsigned char>(img2->getWidth() * img2->getHeight() * 3); return 0; } <file_sep>/Image.hpp #pragma once #include <string> #include <vector> #include <memory> class Image : public std::enable_shared_from_this<Image> { private: unsigned int m_width; unsigned int m_height; unsigned int m_stride; std::vector<unsigned char> m_data; unsigned char* m_dataPtr; static void brightnessContrast(float brightness, float contrast, unsigned char& r, unsigned char& g, unsigned char& b); public: static void savePNG(const std::string& filename, std::shared_ptr<Image> image); static std::shared_ptr<Image> readPNG(const std::string& filename); Image(unsigned int width, unsigned int height, unsigned int stride, std::vector<unsigned char>&& data); Image(unsigned int width, unsigned int height, unsigned int stride, unsigned char* data); unsigned int getWidth() const; unsigned int getHeight() const; unsigned int getStride() const; const unsigned char* getData() const; unsigned char* getData(); void applyBC(float brightness, float contrast); void applyC(float contrast); };
1ab319dfe2a74efae569574516aa323ef87ccbff
[ "Makefile", "C++" ]
7
C++
kirillsurkov/cudaFlipMetric
ee37465720e041e0f18746165c0e4aa0e2c3b319
23fa6e805722df8425c8e263c4b4d35e02e89ddb
refs/heads/master
<file_sep>#!/bin/bash #-x CATAMI_HOME=/home/catami/catamiportal #==================================================# # PULL THE LATEST CODE REVISION #==================================================# cd $CATAMI_HOME"/catami" git pull https://github.com/catami/catami.git #==================================================# # QUERY DJANGO TO GET A LIST OF INSTALLED APPS #==================================================# export DJANGO_SETTINGS_MODULE=catamiPortal.settings cd $CATAMI_HOME"/catami" DJANGO_STRING="import catamiPortal.settings; print [ app for app in catamiPortal.settings.PROJECT_APPS if not \"django\" in app ]" DJANGO_APP_LIST=`python -c "${DJANGO_STRING}"` IFS="," set -- $DJANGO_APP_LIST #==================================================# # THE DJANGO LIST HAS SQUARE BRACKETS WE NEED TO # REMOVE AND APPOSTRAPHES AND SPACES #==================================================# declare -a apps_array=() for app in $@ do temp_app=`echo ${app} | sed -r 's/\[//g' | sed -r 's/\]//g' | sed -r "s/'//g" | sed -r 's/ //g'` echo $temp_app #apps_array=("${apps_array[@]}",$app) #append the filterd app #==================================================# # MIGRATE ALL OF THE APPS #==================================================# echo Doing south migration for ${temp_app} python manage.py migrate ${temp_app} done # For userena python manage.py check_permissions echo DONE!! <file_sep>#!/bin/bash set -eux juju-log "Installing Apache2, Django1.4, postgres, postgis via apt-get" apt-get install -y python-django postgresql-9.1 apache2 juju-log "Installing catamiportal via apt-get" apt-add-repository -y ppa:catami/dev & apt-get update apt-get install catamiportal juju-log "catamiportal install complete"<file_sep>#!/bin/bash #cd /home/catami/catami #python manage.py runserver 0.0.0.0:8000 #restart apache and we're off apache2ctl graceful<file_sep>from catamiPortal.conf.settings.dev import * STAGING_IMPORT_DIR = 'STAGING_IMPORT_DIR_TEXT' # the archive directory where we put original full resolution uncompressed images STAGING_ARCHIVE_DIR = 'STAGING_ARCHIVE_DIR_TEXT' <file_sep>deployment-charm ================<file_sep>#!/bin/bash -x #==================================================# # SETUP GEOSERVER #==================================================# echo 'Setting up geoserver' #Check if geoserver is already on here, if not then download it if [ -a "geoserver-2.2.4-war.zip" ] then echo 'geoserver-2.2.4.zip found, skipping download' else echo 'Downloading geoserver' wget http://downloads.sourceforge.net/project/geoserver/GeoServer/2.2.4/geoserver-2.2.4-war.zip fi #stop tomcat, so we can make some adjustments service tomcat7 stop #put geoserver into tomcat unzip -o geoserver-2.2.4-war.zip unzip -o geoserver.war -d geoserver sudo mv geoserver /var/lib/tomcat7/webapps/ # sed replace the username and password in datastore-config.xml sed -i "s@the_username@$U_NAME@g" geoserver-config/catami/catamidb/datastore.xml sed -i "s@the_password@$PASSWORD@g" geoserver-config/catami/catamidb/datastore.xml # relace the host with given host sed -i "s@the_host@$SERVER@g" geoserver-config/catami/catamidb/datastore.xml #copy the config over to geoserver, and make tomcat the owner sudo cp -r geoserver-config/catami /var/lib/tomcat7/webapps/geoserver/data/workspaces/ chown -R tomcat7 /var/lib/tomcat7/webapps chgrp -R tomcat7 /var/lib/tomcat7/webapps #change username and password for admin # look in /var/lib/tomcat7/webapps/geoserver/data/security sed -i "s@admin=geoserver@$U_NAME=$PASSWORD@g" /var/lib/tomcat7/webapps/geoserver/data/security/users.properties echo 'Restarting tomcat' sudo service tomcat7 restart echo 'Restarting apache' sudo service apache2 restart <file_sep>#!/bin/bash NUM_CPUS=4 apt-get install -y libtorque2 torque-common torque-mom torque-pam torque-scheduler torque-server #================================================== # SET UP THE SAME GROUP THAT CATAMI BELONGS TO # ON EPIC AND THE CURRENT USER #================================================== sudo groupadd partner464 #Partner 464 is the group on CATAMI belongs to on Epic sudo usermod -a -G partner464 `whoami` #================================================== # KILL PBS SO WE CAN CHANGE SETTINGS #================================================== killall pbs_mom killall pbs_sched killall pbs_server echo "SERVERHOST $HOSTNAME" > /var/spool/torque/torque.cfg echo "$HOSTNAME np ${NUM_CPUS}" > /var/spool/torque/server_priv/nodes echo "\$pbs_server $HOSTNAME" > /var/spool/torque/mom_priv/config echo "$HOSTNAME" > /etc/torque/server_name #bug fix echo "altering /etc/hosts for bug fix" sed -i "s/127.0.0.1 localhost/127.0.0.1 localhost $HOSTNAME/g" /etc/hosts #================================================== # CREATE A QUEUE THE SAME NAME AS EPIC #================================================== pbs_server pbs_sched pbs_mom qmgr -c "create queue routequeue" qmgr -c "set queue routequeue queue_type = Execution" qmgr -c "set queue routequeue max_running = 6" qmgr -c "set queue routequeue resources_max.ncpus = ${NUM_CPUS}" qmgr -c "set queue routequeue resources_max.nodes = 1" qmgr -c "set queue routequeue resources_default.ncpus = 1" qmgr -c "set queue routequeue resources_default.neednodes = 1:ppn=1" qmgr -c "set queue routequeue resources_default.walltime = 24:00:00" qmgr -c "set queue routequeue max_user_run = 6" qmgr -c "set queue routequeue enabled = True" qmgr -c "set queue routequeue started = True" qmgr -c "set server default_queue = routequeue" qmgr -c "set server scheduling = True" echo pbsnodes -a echo qstat -Q <file_sep>#!/bin/bash -x #==================================================# # SETUP DOLLY #==================================================# echo 'Setting up dolly' sudo apt-get -y install maven2 sudo apt-get -y install default-jdk git clone https://github.com/catami/dolly.git cd dolly mvn clean:clean mvn compile war:war sudo cp target/dolly.war /var/lib/tomcat7/webapps <file_sep>#!/bin/bash -x CRON_LOG_FILE="/etc/cron.hourly/catamiPortalLog.py" CRON_BAK_FILE="/etc/cron.hourly/catami-postgres-backup-cron.sh" CATAMI_DIR="/var/www/catami" service tomcat7 stop #==================================================# # DESTORY THE DATABASE, TEST DATABASE AND SUPERUSER #==================================================# #start postgres first /etc/init.d/postgresql restart echo "Destroying database, test database and superuser" su postgres -c "dropdb catamidb" su postgres -c "dropdb test_catamidb" su postgres -c "dropuser pocock" #==================================================# # REMOVE THE LOG FILES #==================================================# echo "Removing log files" if [ -f $CRON_BAK_FILE ]; then rm $CRON_BAK_FILE fi if [ -f $CRON_LOG_FILE ]; then rm $CRON_LOG_FILE fi #==================================================# # REMOVE ANY OLD INSTALL DIRECTORIES #==================================================# echo "removing "$CATAMI_DIR if [ -d $CATAMI_DIR ]; then rm -r $CATAMI_DIR fi #==================================================# # REMOVE TOMCAT AND GEOSERVER #==================================================# source destroy_dolly source destroy_geoserver<file_sep>#!/bin/bash killall pbs_mom killall pbs_sched killall pbs_server sudo apt-get remove -y --purge libtorque2 torque-common torque-mom torque-pam torque-scheduler torque-server # make sure the config files are gone too rm -r /var/spool/torque echo 'done'<file_sep>#!/bin/bash set -eux # -x for verbose logging to juju debug-log hooksdir=$PWD user=`relation-get user` password=`<PASSWORD>` host=`relation-get host` database=`relation-get database` # All values are set together, so checking on a single value is enough # If $user is not set, DB is still setting itself up, we exit awaiting next run [ -z "$user" ] && exit 0 juju-log "Setting up catamiportal for the first time" relation-set ip=`unit-get private-address` cd /var/www/juju && chown www-data sites/default/settings.php open-port 80/tcp<file_sep>#!/bin/bash juju-log "Stopping Machine" /etc/init.d/apache2 stop /etc/init.d/postgres stop
34fc358b1fa63d1842b92f7db92b69cf5488ec21
[ "Markdown", "Python", "Shell" ]
12
Shell
catami/deployment-charm
69dbb0e0ac341da45242bf28abcd9f66a7ee3316
bf0872388ff096ca00fa9eb77b1bc29f92c7fabf
refs/heads/master
<file_sep>#include <stdio.h> #include <locale.h> #include <string.h> #include <stdlib.h> #define ALL_PRODUCT 10 int code[ALL_PRODUCT] = { 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009 }; char product[ALL_PRODUCT][40] = { "notebook 96 sheets", "notebook 48 sheets", "ballpoint pen blue", "a set of colored pencils", "stapler", "a4 paper", "paper files", "folder for papers", "datebook", "office calculator" }; double price[ALL_PRODUCT] = { 70, 45, 11, 210, 175, 299, 101, 30, 250, 599 }; int discount[ALL_PRODUCT] = { 5, 2, 0, 10, 30, 40, 3, 0, 50, 15 }; double sum = 0; double discount_price(double price, int discount); void conclusion(); int purchases(int* buff); double cheque(int* buff, int num_buff); int main() { conclusion(); int buff[50], num_buff = 0; num_buff = purchases(buff); sum = cheque(buff, num_buff); printf("sum - %.2f", sum); return 0; } int purchases(int* buff) { char str[5] = ""; int num = 0, number_buff = 0; while (strcmp(str, "exit")) { printf("Enter the product code or exit to exit: "); scanf_s("%s", str, 5); if (strspn(str, "0123456789")) { num = atoi(str); for (int i = 0; i < ALL_PRODUCT; i++) if (code[i] == num) { buff[number_buff] = code[i]; number_buff++; } } } return number_buff; } double discount_price(double price, int discount) { return price - (price * discount) / 100; } void conclusion() { for (int i = 0; i < ALL_PRODUCT; i++) { printf("code: %d, product:%s ", code[i], product[i]); printf("\n"); } } double cheque(int* buff, int num_buff) { for (int i = 0; i < num_buff; i++) for (int j = 0; j < ALL_PRODUCT; j++) { if (code[j] == buff[i]) { printf("%s, ", product[j]); printf("\tprice - %0.2f,\t discount - %d%%,\t discount price - %0.2f\n", price[j], discount[j], discount_price(price[j], discount[j])); sum += discount_price(price[j], discount[j]); } } return sum; }<file_sep>//табличные значения для ДСП: 650 кг/м^3, ДВП: 800 кг/м^3, дерева 550 кг/м^3 //входные данные 180 100 80 //выходные данные 90.576000 #include <stdio.h> int main() { double h, w, d, back_wall, side_wall, upper_n_lower_wall, shelves, doors, a; int i = 0; printf("enter wardrobe dimensions in santimeters: height, width, depth: "); do { scanf("%lf %lf %lf", &h, &w, &d); //habarytes } while ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)); //checking a = h - 3; h *= 0.01; w *= 0.01; d *= 0.01; back_wall = h * w * 0.005 * 800; side_wall = (h-0.03) * d * 0.015 * 650 * 2; upper_n_lower_wall = w * d * 0.015 * 650 * 2; while (a >= 40) //shelves amount { a -= 40; i++; } shelves = d * (w - 0.03) * 0.015 * 650 * i; doors = h * w * 0.01 * 550; //each part's weight /* printf("back wall weight: %lf\n", back_wall); printf("side wall weight: %lf\n", side_wall); printf("upper and lower walls weight: %lf\n", upper_n_lower_wall); printf("shelves weight: %lf\n", shelves); printf("doors weight: %lf\n", doors); */ printf("overall wardrobe weight is %lf", back_wall + side_wall + upper_n_lower_wall + shelves + doors, "kg\n"); return 0; }<file_sep>#include <iostream> #include <cstdlib> #include <clocale> #include <fstream> #include "polynom.h" #include "display.h" using namespace std; /* Чтение происходит из файла "data.txt" -В первой строке - количество полиномов -В второй строке перечисленны степени каждого полинома -В последующих строках перечисленны коэффициенты полиномов !!!Предполагается, что введенные данные верны!!! */ int main() { setlocale(LC_ALL, "rus"); int n, ans = 1; float x; int ind_1; int ind[2]; TPolynom* p; TPolynom res; try { read_file(&p, n); while (ans) { system("cls"); print_p(p, n); choose(); answer(ans); switch (ans) { case 0: break; case 1: system("cls"); print_p(p, n); index(ind, n); system("cls"); print_2p(p[ind[0]], p[ind[1]], ind); res = p[ind[0]] + p[ind[1]]; cout << "f" << ind[0] << " + f" << ind[1] << " = "; cout << res; retry(ans); break; case 2: system("cls"); print_p(p, n); index(ind, n); system("cls"); print_2p(p[ind[0]], p[ind[1]], ind); res = p[ind[0]] - p[ind[1]]; cout << "f" << ind[0] << " - f" << ind[1] << " = "; cout << res; retry(ans); break; case 3: system("cls"); print_p(p, n); index(ind, n); system("cls"); print_2p(p[ind[0]], p[ind[1]], ind); res = p[ind[0]] * p[ind[1]]; cout << "f" << ind[0] << " * f" << ind[1] << " = "; cout << res; retry(ans); break; case 4: system("cls"); print_p(p, n); cout << "Выберите полином: "; do { cin >> ind_1; } while (ind_1 < 0 || ind_1 > n); cout << "Введите значение x: "; cin >> x; system("cls"); cout << "f" << ind_1 << " = "; cout << p[ind_1]; cout << "\nf" << ind_1 << "(" << x << ") = " << p[ind_1](x) << endl; retry(ans); break; case 5: system("cls"); print_p(p, n); cout << "Выберите полином: "; do { cin >> ind_1; } while (ind_1 < 0 || ind_1 > n); system("cls"); cout << "f" << ind_1 << " = "; cout << p[ind_1]; res.Diff(p[ind_1]); cout << "f'" << ind_1 << " = "; cout << res; retry(ans); break; default: cout << "ERROR" << endl; } } } catch (const char* exc) { cout << exc << endl; return 1; } delete[] p; return 0; }<file_sep>#ifndef _HEADER_H #define _HEADER_H #include <string> #include <cstring> using namespace std; struct Date { int day; int month; int year; }; class Product { private: string name; string unit; double price; int number; Date data; public: Product(void); Product(string name, string unit, double price, int number,int day,int month,int year); // friend void fill_sklad(Product*& p, int size, const string filename); friend ostream& operator <<(ostream& stream,const Product& p); friend void find_NULL(Product*& p, int size); void SetRes( string _name, string _unit, double _price, int _number, int _day, int _month, int _year); }; void fill_sklad(Product*& p, int size, const string filename); int cntLines(const string filename); void allocate_stock(Product*& p, int size); void free_stock(Product*& p); //int cntLines(const string filename); //void fill_sklad(Product*& p, Date*& d, int size, const string filename); //void find_null(Product*& p, Date*& d, int size); #endif<file_sep>cmake_minimum_required(VERSION 3.23) project(untitled C) set(CMAKE_C_STANDARD 23) add_executable(untitled main.c) <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <tchar.h> #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <time.h> #include <string.h> #include <time.h> #include<tchar.h> WIN32_FIND_DATA names[MAX_PATH]; WIN32_FIND_DATA File; HANDLE hfile; int F_main_work(wchar_t** fname[], int* size, int* size1); void F_init(int* ind, wchar_t** fname[]); void Bubble_sort(int size[], int quantity); void Insert(int b[], int N); void Merge(int get[], int l, int mid, int r); void Merge_sort(int a[], int N); void Merge_sort_lr(int a[], int l, int r); void Swap(int* a, int* b); void Input(); void Sorting(int size1[], int size[], wchar_t** fname[], int i); int Index(int size1[], int size[], int quantity, int k); int main() { setlocale(LC_ALL, "Russian"); int i = 0, k; int ind[200]; int* size = (int*)malloc(200 * sizeof(int)); int* size1 = (int*)malloc(200 * sizeof(int)); wchar_t** fname = (wchar_t**)malloc(MAX_PATH * sizeof(wchar_t*)); F_init(ind, fname); Input(); i = F_main_work(fname,size,size1); Sorting(size1, size, fname, i); return 0; } void Input() { char* a = (char*)malloc(MAX_PATH); wchar_t* path = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); do { printf("Enter the open path of the directory with the files: \n"); //translating the path to wchar_t scanf("%s", a); strcat(a, "\\*.*"); mbstowcs(path, a, strlen(a) + 1); hfile = FindFirstFileW(path, &File); } while (hfile == INVALID_HANDLE_VALUE); printf("Your path: %s \n", a); } void Sorting(int size1[], int size[], wchar_t** fname[], int i) { int j, k, n, r, index; clock_t start, end; double elapsed; do { printf("\nSelect the sort type(enter a number) or '0' to exit: \n1 - Bubble\n2 - Inserts\n3 - Merge\n"); scanf("%d", &n); } while ((n < 0) || (n > 3)); while (n != 0) { for (j = 0; j < i; j++) { size1[j] = size[j]; } if (n != 0) { start = clock(); if (n == 1) Bubble_sort(size1, i-1); else if (n == 2) Insert(size1, i); else if (n == 3) Merge_sort (size1, i); do { printf("Select the output type(enter a number)\n1)Ascending order\n2)Descending order\n"); scanf("%d", &r); if (r == 1) { printf("Names: %50c Size(Bytes):\n", ' '); for (k = 0; k < i; k++) { if (size1[k] <= 0) continue; else { index = Index(size1, size, i, k); printf("\n%-60S", fname[index]); printf("%d \n", (size1[k])); } } } else if (r == 2) { printf("Names: %50c Size(Bytes):\n", ' '); for (k = i; k > 0; k--) { if (size1[k] <= 0) continue; else { index = Index(size1, size, i, k); printf("\n%-60S", fname[index]); printf("%d \n", (size1[k])); } } } } while ((r < 1) || (r > 2)); end = clock(); elapsed = ((double)(end - start)) / CLOCKS_PER_SEC; printf("\nTime: %.3f seconds\n", elapsed); do { printf("Select the sort type(enter a number) or '0' to exit:\n1 - Bubble\n2 - Inserts\n3 - Merge\n"); scanf("%d", &n); } while ((n < 0) || (n > 3)); } else break; } } int Index(int size1[], int size[], int quantity, int k) { int i, ind; for (i = 0; i < quantity; i++) if (size1[k] == size[i]) ind = i; return ind; } void Bubble_sort(int size[], int quantity) { int i, j; for (i = 0; i < quantity; i++) { for (j = 0; j < quantity - i; j++) { if (size[j + 1] < size[j]) { Swap(&size[j + 1], &size[j]); } } } } void Insert(int size[], int quantity) { int i, j, tmp; for (i = 1; i < quantity; i++) { tmp = size[i]; j = i - 1; while ((j >= 0) && (size[j] > tmp)) { Swap(&size[j + 1], &size[j]); j--; } } } void Swap(int* a, int* b) { int tmp = *a; *a = *b; *b = tmp; } void Merge(int get[], int l, int mid, int r) { int k = 0, i = 0, j = 0; int N = mid - l; int M = r - mid + 1; int* c = (int*)malloc((r - l + 1) * sizeof(int)); i = l; j = mid; while (((i - l) < N) && ((j - mid) < M)) { if (get[i] < get[j]) { c[k] = get[i]; k++; i++; } else { c[k] = get[j]; k++; j++; } } while ((i - l) < N) { c[k] = get[i]; k++; i++; } while ((j - mid) < M) { c[k] = get[j]; k++; j++; } for (i = l; i < r + 1; i++) { get[i] = c[i - l]; } } void Merge_sort(int a[], int N) { Merge_sort_lr(a, 0, N - 1); } void Merge_sort_lr(int a[], int l, int r) { int mid; if (l >= r) return; mid = l + (r - l) / 2; Merge_sort_lr(a, l, mid); Merge_sort_lr(a, mid + 1, r); Merge(a, l, mid + 1, r); } int F_main_work(wchar_t** fname[], int* size, int* size1) { int i = 0; printf("Data in your directory: \n"); printf("Names: %50c Size(Bytes):\n", ' '); do { if ((i == 0) || (i == 1)) { i++; continue; } names[i] = File; fname[i] = names[i].cFileName; size[i] = names[i].nFileSizeLow; size1[i] = names[i].nFileSizeLow;//size of file printf("\n%-60S", fname[i]);//name of file if (size[i] == 0) printf("This is a folder, the size is undefined\n"); else printf("%d \n", (size[i])); i++; } while (FindNextFileW(hfile, &File) != NULL); return i; } void F_init(int* ind, wchar_t** fname[]) { int i; for (int i = 0; i < MAX_PATH; i++) { fname[i] = (wchar_t*)malloc(200 * sizeof(wchar_t)); fname[i] = L" "; } for (int i = 0; i < 200; i++) { ind[i] = i; } }<file_sep>#include <tchar.h> #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <time.h> #include <string.h> #include <time.h> #include<tchar.h> WIN32_FIND_DATA names[MAX_PATH]; WIN32_FIND_DATA File; HANDLE hfile; void Choice(int a[], int N); void Insert(int b[], int N); void Quicksort(int c[], int low, int high); void swap(int* a, int* b); void Index(int a[], int b[], int size, int check[]); void Input() { char* a = (char*)malloc(MAX_PATH); wchar_t* path = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); do { printf("Enter the open path to the existing directory with the files: \n"); //translating the path to wchar_t scanf("%s", a); strcat(a, "\\*.*"); mbstowcs(path, a, strlen(a) + 1); hfile = FindFirstFileW(path, &File); } while (hfile == INVALID_HANDLE_VALUE); printf("Your path: %s \n", a); } int PrintFile(int size[], int size1[], wchar_t** fname[]) { int i = 0; printf("Data in your directory: \n"); printf("Names: %50c Size(Bytes):\n", ' '); do { if ((i == 0) || (i == 1)) { i++; continue; } names[i] = File; fname[i] = names[i].cFileName; size[i] = names[i].nFileSizeLow; size1[i] = names[i].nFileSizeLow;//size of file printf("\n%-60S", fname[i]);//name of file if (size[i] == 0) printf("This is a folder, the size is undefined\n"); else printf("%d \n", (size[i])); i++; } while (FindNextFileW(hfile, &File) != NULL); return i; } void Sorting(int a[], int b[], wchar_t** fname[], int i) { int k, n, r, index, c; int* d = (int*)malloc(MAX_PATH * sizeof(int)); int* check = (int*)malloc(MAX_PATH * sizeof(int)); clock_t start, end; double elapsed; do { printf("\nSelect the sort type(enter a number) or '0' to exit:\n1)Sorting by choice\n2)Sorting by inserts\n3)Quick sorting\n"); scanf("%d", &n); } while ((n < 0) || (n > 3)); while (n != 0) { if (n != 0) { for (c = 0; c < i; c++) d[c] = a[c]; start = clock(); if (n == 1) Choice(d, i); else if (n == 2) Insert(d, i); else if (n == 3) Quicksort(d, 0, i - 1); do { printf("Select the output type(enter a number)\n1)Ascending order\n2)Descending order\n"); scanf("%d", &r); if (r == 1) { printf("Names: %50c Size(Bytes):\n", ' '); Index(d, b, i, check); for (k = 0; k < i; k++) { if (d[k] <= 0) continue; else { index = check[k]; printf("\n%-60S", fname[index]); printf("%d \n", (d[k])); } } } else if (r == 2) { printf("Names: %50c Size(Bytes):\n", ' '); Index(d, b, i, check); for (k = i; k > 0; k--) { if (d[k] <= 0) continue; else { index = check[k]; printf("\n%-60S", fname[index]); printf("%d \n", (d[k])); } } } } while ((r < 1) || (r > 2)); end = clock(); elapsed = ((double)(end - start)) / CLOCKS_PER_SEC; printf("\nTime: %.3f seconds\n", elapsed); do { printf("Select the sort type(enter a number) or '0' to exit:\n1)Sorting by choice\n2)Sorting by inserts\n3)Quick sorting\n"); scanf("%d", &n); } while ((n < 0) || (n > 3)); } else break; } } void Index(int c[], int v[], int size, int check[]) { int i, j, l, flag; for (i = 0; i < size; i++) for (j = 0; j < size; j++) { flag = 0; if (c[i] == v[j]) { for (l = 0; l < size; l++) if (check[l] == j) { flag = 1; break; } if (flag == 0) check[i] = j; else continue; break; } } } int main() { setlocale(LC_ALL, "Russian"); int i, k; int* size = (int*)malloc(MAX_PATH * sizeof(int)); int* size1 = (int*)malloc(MAX_PATH * sizeof(int)); wchar_t** fname = (wchar_t**)malloc(MAX_PATH * sizeof(wchar_t*)); for (int i = 0; i < MAX_PATH; i++) { fname[i] = (wchar_t*)malloc(200 * sizeof(wchar_t)); fname[i] = L" "; } Input(); i = PrintFile(size, size1, fname); Sorting(size1, size, fname, i); return 0; } void Choice(int a[], int N) { int i, j, min, ind, tmp; for (i = 0; i < N; i++) { min = a[i]; ind = i; for (j = i + 1; j < N; j++) if (a[j] < min) { min = a[j]; ind = j; } swap(&a[i], &a[ind]); } } void Insert(int b[], int N) { int i, j, tmp; for (i = 1; i < N; i++) { tmp = b[i]; j = i - 1; while ((j >= 0) && (b[j] > tmp)) { swap(&b[j + 1], &b[j]); j--; } } } void Quicksort(int c[], int low, int high) { int mid, count; int l = low, h = high; mid = c[(l + h) / 2]; //calculation of the reference element do { while (c[l] < mid) l++; while (c[h] > mid) h--; if (l <= h) //rearranging elements { count = c[l]; c[l] = c[h]; c[h] = count; l++; h--; } } while (l < h); if (low < h) Quicksort(c, low, h); if (l < high) Quicksort(c, l, high); } void swap(int* a, int* b) { int tmp = *a; *a = *b; *b = tmp; }<file_sep>#include "Base.h" #include "Product.h" #include <iostream> #include <fstream> using namespace std; //Base ifstream& operator>>(ifstream& buf, Base& Date) { buf >> Date.product >> Date.count; return buf; } istream& operator>>(istream& buf, Base& Date) { buf >> Date.product >> Date.count; return buf; } ostream& operator<<(ostream& buf, const Base& Date) { buf << Date.product << Date.count << endl; return buf; } bool Base::operator == (const string& str) const { return product == str; } bool Base::operator == (const Base& base) const { return product == base.product; } bool Base::operator != (const Base& base) const { return !(*this == base); } Base& Base::operator+=(const int& ucount) { if (ucount) { count += ucount; } return *this; } Product Base::get_product() const { return product; } int Base::get_count() const { return count; } void Base::set_count(const int ucount) { count = ucount; } <file_sep>#include <stdio.h> #include <math.h> #include <locale.h> /* 1) The circles are equal 2) They don't touch 3) External touch 4) Inner touch 5) One circle inside another 6) Сrossing at 2 points */ void main() { setlocale(LC_ALL, "rus"); float x1, y1, r1, x2, y2, r2, M, m, dl; printf("Circle 1 (x1, y1, r1) = "); scanf("%f %f %f", &x1, &y1, &r1); printf("Circle 2 (x2, y2, r2) = "); scanf("%f %f %f", &x2, &y2, &r2); if (r1 > r2) { M = r1; m = r2; } else { M = r2; m = r1; } dl = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if (x1 == x2 && y1 == y2 && r1 == r2) printf("1) The circles are equal"); // 1 1 1 1 1 1 else { if (dl > (r1 + r2)) printf("2) They don't touch"); // 1 1 1 4 1 1 else if (dl == (r1 + r2)) printf("3) External touch"); // 1 1 1 3 1 1 else if (dl == (M - m)) printf("4) Inner touch"); // 1 1 4 4 1 1 else if (dl < (M - m)) printf("5) One circle inside another"); // 1 1 4 2 1 1 else printf("6) Crossing at 2 points "); // 0 0 2 2 0 1 } }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include "triangle.h" #include <stdlib.h> #include <math.h> char* read_string(FILE* stream) { int buffer_size = 16; int buffer_size_divizer = 1; int offset = 0; int additional_length; char* buffer = (char*)malloc(buffer_size); if (buffer == NULL) { return NULL; } buffer[0] = '\0'; while (1) { if (fgets(buffer + offset, buffer_size / buffer_size_divizer, stream) == NULL) { free(buffer); return NULL; } else { additional_length = strlen(buffer + offset); if (buffer[offset + additional_length - 1] != '\n') { buffer_size *= 2; buffer = (char*)realloc(buffer, buffer_size); offset += additional_length; buffer_size_divizer = 2; } else { buffer[offset + additional_length - 1] = '\0'; break; } } } return buffer; } char* getPath() { char* file_path; while (1) { printf("Enter the path to file : "); file_path = read_string(stdin); if (file_path != NULL) break; } return file_path; } Triangle* ReadTriangleFile(char* file_path, int* number_of_triangles) { FILE* file = fopen(file_path, "r"); if (file == NULL) { printf("\nRead file error.\n"); } Triangle* triangles = (Triangle*)malloc(sizeof(Triangle)); *number_of_triangles = 1; while (1) { Triangle current_triangle = ReadTriangleEntity(file); triangles[*number_of_triangles - 1] = current_triangle; if (read_string(file) == NULL) { break; } else { triangles = (Triangle*)realloc(triangles, (*number_of_triangles + 1) * sizeof(Triangle)); *number_of_triangles += 1; } } fclose(file); return triangles; } Triangle ReadTriangleEntity(FILE* file) { float x1= atoi(read_string(file)); float y1 = atoi(read_string(file)); float x2 = atoi(read_string(file)); float y2 = atoi(read_string(file)); float x3 = atoi(read_string(file)); float y3 = atoi(read_string(file)); Coord c1 = { x1, y1 }; Coord c2 = { x2, y2 }; Coord c3 = { x3, y3 }; Triangle triangle = { {c1, c2, c3} }; return triangle; } float CountSquare(Triangle triangle) { float s = (abs(((triangle.vertices[1].x - triangle.vertices[0].x) * (triangle.vertices[2].y - triangle.vertices[0].y)) - ((triangle.vertices[2].x - triangle.vertices[0].x) * (triangle.vertices[1].y - triangle.vertices[0].y)))) / 2; printf("S = %f \n", s); } float* Sides(Triangle triangle) { float sides[3]; sides[0] = sqrt((triangle.vertices[1].x - triangle.vertices[0].x) * (triangle.vertices[1].x - triangle.vertices[0].x) + (triangle.vertices[1].y - triangle.vertices[0].y) * (triangle.vertices[1].y - triangle.vertices[0].y)); sides[1] = sqrt((triangle.vertices[2].x - triangle.vertices[0].x) * (triangle.vertices[2].x - triangle.vertices[0].x) + (triangle.vertices[2].y - triangle.vertices[0].y) * (triangle.vertices[2].y - triangle.vertices[0].y)); sides[2] = sqrt((triangle.vertices[2].x - triangle.vertices[1].x) * (triangle.vertices[2].x - triangle.vertices[1].x) + (triangle.vertices[2].y - triangle.vertices[1].y) * (triangle.vertices[2].y - triangle.vertices[1].y)); return sides; } float CountPerimeter(Triangle triangle) { float* sides = Sides(triangle); float p = sides[0] + sides[1] + sides[2]; printf("P = %f \n", p); } float* Height(Triangle triangle) { float s = (abs(((triangle.vertices[1].x - triangle.vertices[0].x) * (triangle.vertices[2].y - triangle.vertices[0].y)) - ((triangle.vertices[2].x - triangle.vertices[0].x) * (triangle.vertices[1].y - triangle.vertices[0].y)))) / 2; float heights[3]; float* sides = Sides(triangle); heights[0] = 2 * s / sides[0]; heights[1] = 2 * s / sides[1]; heights[2] = 2 * s / sides[2]; printf("H1 = %f, H2 = %f, H3 = %f \n", heights[0], heights[1], heights[2]); } void PrintTriangleType(Triangle triangle) { float* sides = Sides(triangle); float max = fmax(sides[0], sides[1], sides[2]); float min = fmin(sides[0], sides[1], sides[2]); float sr = sides[0] + sides[1] + sides[2] - max - min; if (max * max < (min * min + sr * sr)) printf("The triangle is sharp \n"); else if (max * max == (min * min + sr * sr)) printf("The triangle is straight \n"); else if (max * max > (min * min + sr * sr)) printf("The triangle is blunt \n"); } <file_sep>#ifndef _TRIANGLE_H #define _TRIANGLE_H #include <string> #include <iostream> using namespace std; struct Coord { float x, y; }; class Triangle { private: Coord vertices[3]; public: Triangle(); Triangle(Coord* vertices_); void CountSquare() const; void CountPerimeter() const; float* Sides() const; void Height() const; int TriangleType() const; friend std::ostream& operator<<(ostream& output_stream, const Triangle& triangles); }; enum types { straight, sharp, blunt }; int read(Triangle*& triangles, const string& f); #endif _TRIANGLE_H<file_sep>#include "ClientSide.h" std::string get_first_input() { std::string input_action; do { std::cout << "If you want to create new receipt - enter '1'\n"; std::cout << "If you want to complete - enter '0'\n >>> "; getline(std::cin, input_action); if (input_action != "1" and input_action != "0") { std::cout << "Uncorrect input. Try again\n"; } } while (input_action != "1" and input_action != "0"); return input_action; } std::string get_receipt_action() { std::string user_input; do { getline(std::cin, user_input); if (user_input != "#" and user_input != "-" and user_input != "+") { std::cout << "Uncorrect input! Try again following the input instructions\n >>> "; } } while (user_input != "#" and user_input != "-" and user_input != "+"); return user_input; } void Add_new_receipt(TContainer<TReceipt>& receipts, TReceipt& rec) { if (rec.Get_num_products() == 0) { std::cout << "You have completed the purhase, BUT you haven't added any products! So the reciept hasn't created\n"; } else { rec.Get_data_n_time(); receipts.insert(rec); std::cout << receipts.current(); } } void work_with_client(TProductsDatabase& db) { std::cout << "\nWelcome!\n"; TContainer<TReceipt> receipts; while (1) { std::string input_action = get_first_input(); if (input_action == "0") { break; } TReceipt curr_rec; bool receiptCompleted = false; while (!receiptCompleted) { std::cout << "If you want to scan new product - enter '+'.\n"; std::cout << "If you want to complete this receipt and print it - enter '#'.\n"; std::cout << "If you want to delete some product - enter '-'.\n >>> "; std::string user_input = get_receipt_action(); if (user_input == "#") { receiptCompleted = true; } else if (user_input == "-") { curr_rec.Delete(db); } else if (user_input == "+") { curr_rec.Add(db); } } Add_new_receipt(receipts, curr_rec); } db.create_updating_db(); }<file_sep>#include <stdio.h> #include <stdlib.h> #include "zagolovok.h" Owners* read_inf() { FILE* f; int n; char* path = (char*)malloc(sizeof(char)*100); gets(path); //1 f = fopen(path, "r"); if (f == NULL) { printf("File not found\n"); } else printf("file opened successfully\n"); fscanf(f, "%d", &n); Owners* owner = (Owners*)malloc(sizeof(Owners) * n); printf("number of owners = %d\n", n); for (int i = 0; i < n; i++) { owner[i].n = n; owner[i].name = (char*)malloc(sizeof(char) * 12); owner[i].surname = (char*)malloc(sizeof(char) * 12); owner[i].patronymic = (char*)malloc(sizeof(char) * 20); owner[i].date = (char*)malloc(sizeof(char) * 12); owner[i].carnum = (char*)malloc(sizeof(char) * 12); owner[i].phnum = (char*)malloc(sizeof(char) * 13); fscanf(f, "%s %s %s %s %s %d %s %d", owner[i].name, owner[i].surname, owner[i].patronymic, owner[i].date, owner[i].carnum, &owner[i].gibdd, owner[i].phnum, &owner[i].tehpas); } fclose(f); free(path); return owner; } void print_inf(Owners* owner, int n) { for (int i = 0; i < n; i++) { printf("%s %s %s\n %s\n %s\n %d\n %s\n %d\n\n", owner[i].name, owner[i].surname, owner[i].patronymic, owner[i].date, owner[i].carnum, owner[i].gibdd, owner[i].phnum, owner[i].tehpas); } } int search_owner(Owners* owner, int n) { int flag = 0, g; while (flag == 0) { printf("input number of gibdd = "); scanf("%d", &g); printf("\n"); for (int i = 0; i < n; i++) { if (owner[i].gibdd == g) { flag++; printf("%s %s %s\n %s\n %s\n %d\n %s\n %d\n\n", owner[i].name, owner[i].surname, owner[i].patronymic, owner[i].date, owner[i].carnum, owner[i].gibdd, owner[i].phnum, owner[i].tehpas); } } if (flag == 0) { printf("incorrect number of gibdd\n"); } } return 0; } void free_inf(Owners** owner, int n) { int i; for (i = 0; i < n; i++) { free((*owner)[i].name); free((*owner)[i].surname); free((*owner)[i].patronymic); free((*owner)[i].date); free((*owner)[i].carnum); free((*owner)[i].phnum); } free(*owner); }<file_sep>//табличные значения для ДСП: 650 кг/м^3, ДВП: 800 кг/м^3, дерева 550 кг/м^3// #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { double h, w, d, back_wall, side_walls, lids, shelves, doors, a; int i = 0; printf("Enter cabinet dimensions in centimeters: height, width, depth: "); //запрос габаритов scanf("%lf %lf %lf", &h, &w, &d); //ввод габаритов if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) //проверка { printf("Data entered incorrectly"); return 1; } a = h; h = h * 0.01; w = w * 0.01; d = d * 0.01; back_wall = h * w * 0.005 * 800; side_walls = h * d * 0.015 * 650 * 2; lids = (w - 0.03) * d * 0.015 * 650 * 2; while (a >= 40) //количество полок { a = a - 40; i++; } shelves = d * (w - 0.03) * 0.015 * 650 * i; doors = h * w * 0.01 * 550; printf("Total cabinet weight is %lf", back_wall + side_walls + lids + shelves + doors, "kg\n"); return 0; }<file_sep>#define CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> #include <malloc.h> #define N 5 int l; void unique_number_pc(int* p1) { int i=0, n = 0, digit, g=0, count = 0; printf("Input length of riddled number: \n"); do { scanf("%d", &l); } while (l < 2 || l > 5); for (i = 0; i < l; i++) { digit = 0 + rand() % (9 - 0 + 1); //generator sifr p1[i] = digit; for (g = 0; g < l; g++) { if (p1[i] == p1[g]) { count += 1; } if (count >= 2) { digit = 0 + rand() % (9 - 0 + 1); p1[i] = digit; count = 0; g = -1; } } count = 0; } } void unique_number_user(int *p2) { int status; int i, j; int k; int number; do { status = 1; printf("Enter a unique number of length %d: \n", l); scanf("%d", &number); i = 1; while (number > 0) { k = number % 10; p2[l - i] = k; number = number / 10; i++; } for (i = 0; i < l; i++) { for (j = i + 1; j < l; j++) { if (p2[j] == p2[i]) { status = 0; break; } } if (status == 0) { break; } } if (status == 0) { for (i = 0; i < l; i++) { p2[i] = -1; } i = 0; } } while (status == 0); } int main() { srand(time(NULL)); int i, j; int cows=0, bulls=0; int arr_pc[N]; unique_number_pc(arr_pc); do { int arr_user[N]; unique_number_user(arr_user); for (i = 0; i < l; i++) { for (j = 0; j < l; j++) { if (arr_user[i] == arr_pc[j] && i == j) { bulls += 1; } else if(arr_user[i] == arr_pc[j] && j != i){ cows += 1; } } } if (bulls != l) { printf("cows: %d\n", cows); printf("bulls: %d\n", bulls); cows = 0; bulls = 0; } } while (bulls != l); printf("My congratulations!You won!\n"); return 0; } <file_sep>#ifndef _CARS_H #define _CARS_H #include <string> #include <vector> using namespace std; class Car { private: string brand; string color; string serial_number; string registration_number; string count_door; string year; string price; public: Car(); Car(string brand, string color, string serial_number, string registration_number, string count_door, string year, string price); bool operator<(const Car& guest_car) const; friend std::ostream& operator<<(std::ostream& output_stream, const Car& car); }; string GetFilePath(); Car ReadCarEntity(ifstream& file); vector<Car> ReadCarFile(const string& filepath); Car FindOldestCar(const vector<Car>& cars); #endif _CARS_H <file_sep>#ifndef _Star #define _Star typedef struct { char name[50]; float dist; float magnitude; float deg; float min; float sec; }Star; typedef struct { char name[50]; int count; Star* stars; }Constellation; void Callocate(Constellation** cns, int c); void Sallocate(Star** st, int c); void cfree(Constellation** cns); void cnst_table(Constellation* cns, int count); void read_data(Constellation** cns, int* count); void print_data(Constellation* cns, int n); void choice(Constellation* cns, int count); #endif <file_sep>#pragma once #ifndef _BANKI_H #define _BANKI_H #include <string> using namespace std; struct vkladstruct { string vkladname; float rate; int times; bool operator==(const string& vkladType) const; bool operator!=(const string& vkladType) const; friend ostream& operator<<(ostream& os, const vkladstruct& our_vklad); }; struct bankstruct { int count; string bankname; string banktype; bool smotr; vkladstruct* our_vklad; friend ostream& operator<<(ostream& os, const bankstruct& banki); }; struct banklib { bankstruct* banki; int count; string vkladType; banklib() {} banklib(const string& path); ~banklib(); banklib& search(float sum, int kMonths, string vkladType); banklib(const banklib& banks); //banklib& operator=(const banklib& banks);//опер. присваивания friend ostream& operator << (ostream& out, const banklib& banks); }; string getfile(); #endif<file_sep>#include <stdio.h> int main() { const double WOOD_DENSITY = 0.00055; //kg*cm^3 const double DSP_DENSITY = 0.00065; const double DVP_DENSITY = 0.0008; double h, w, d; double shelves_mass, back_wall_mass, door_mass, upper_and_lower_cover_mass, sidewalls_mass, wardrobe_mass; int shelf_count = 4; //The minimum possible number of shelves (follows from the minimum height of the wardrobe) printf("Enter the height, width and depth of the wardrobe in centimeters... \n"); scanf("%lf%lf%lf", &h, &w, &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) { printf("The entered data is invalid!"); return 1; } if (h > 200) shelf_count = 5; //The maximum possible number of shelves (follows from the maximum height of the wardrobe) back_wall_mass = DVP_DENSITY * (h * w * 0.5); door_mass = WOOD_DENSITY * (h * w * 1); sidewalls_mass = 2 * DSP_DENSITY * h * d * 1.5; //Subtract the thickness of the overhead doors and the back wall upper_and_lower_cover_mass = 2 * DSP_DENSITY * d * (w - 3) * 1.5; shelves_mass = DSP_DENSITY * shelf_count * (w - 3) * d * 1.5; wardrobe_mass = back_wall_mass + door_mass + sidewalls_mass + upper_and_lower_cover_mass + shelves_mass; printf("Wardrobe mass is: %lf", wardrobe_mass); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <tchar.h> #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <time.h> #include <string.h> #include <time.h> #include<tchar.h> WIN32_FIND_DATA names[MAX_PATH]; WIN32_FIND_DATA File; HANDLE hfile; void Choice(int a[], wchar_t** b[], int N); void Insert(int a[], wchar_t** b[], int N); void merge_sort(int a[], wchar_t** name[], int N); void output(int size[], wchar_t** name[], int N); void merge_sort_lr(int a[], wchar_t** name[], int l, int r); void merge(int get[], wchar_t** name[], int l, int mid, int r); int form_array(int size[], wchar_t** name[], wchar_t** path[]); int main() { printf("2 \n"); int i = 0, N = 0, number, flag = 1; int* size = (int*)malloc(MAX_PATH * sizeof(int)); wchar_t** name = (wchar_t**)malloc(MAX_PATH * sizeof(wchar_t*)); wchar_t* path = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); N=form_array(size, name, path); sorting(size, name, N); return 0; } int sorting(int size[], wchar_t** name[], int N) { int i, number, flag; long long time1, time2; int* size_copy = (int*)malloc(MAX_PATH * sizeof(int)); wchar_t** name_copy = (wchar_t**)malloc(MAX_PATH * sizeof(wchar_t*)); do { for (i = 0; i < N; i++) { size_copy[i] = size[i]; name_copy[i] = name[i]; } printf("Choose the type of sorting: 1-selection sorting, 2-insertion sorting, 3-merge sorting "); scanf("%d", &number); if ((number < 1) || (number > 3)) { printf("Invalid number. \n"); continue; } else if (number == 1) { QueryPerformanceCounter(&time1); Choice(size_copy, name_copy, N); QueryPerformanceCounter(&time2); } else if (number == 2) { QueryPerformanceCounter(&time1); Insert(size_copy, name_copy, N); QueryPerformanceCounter(&time2); } else if (number == 3) { QueryPerformanceCounter(&time1); merge_sort(size_copy, name_copy, N); QueryPerformanceCounter(&time2); } if ((number >= 1) || (number <= 3)) output(size_copy, name_copy, N); printf("\nThe time it took to sort the bubble = %lld milliseconds\n\n", time2 - time1); printf("\n"); printf("If you want to finish, write 0, if not - 1: "); scanf("%d", &flag); } while (flag == 1); } int form_array(int size[], wchar_t** name[], wchar_t** path[]) { char* a = (char*)malloc(MAX_PATH); int i = 0, N = 0;; printf("Enter the path to the directory (Example: D:\\photo\\1\) \n"); scanf("%s", a); strcat(a, "\\*.*"); mbstowcs(path, a, strlen(a) + 1); hfile = FindFirstFileW(path, &File); FindNextFileW(hfile, &File); while (FindNextFileW(hfile, &File) != NULL) { names[i] = File; name[i] = names[i].cFileName; size[i] = names[i].nFileSizeLow; i++; } N = i; return N; } void output(int size_copy[], wchar_t** name_copy[], int N) { int i = 0; for (i = 0; i < N; i++) { printf("\n%-60S ", name_copy[i]); printf("%d ", size_copy[i]); } } void Choice(int a[], wchar_t** b[], int N) //сортировка выбором (2) { int i, j, min, ind, tmp; wchar_t* t = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); for (i = 0; i < N; i++) { min = a[i]; ind = i; for (j = i + 1; j < N; j++) if (a[j] < min) { min = a[j]; ind = j; } tmp = a[ind]; a[ind] = a[i]; a[i] = tmp; t = b[ind]; b[ind] = b[i]; b[i] = t; } } void Insert(int a[], wchar_t** b[], int N) //сортировка вставками (3) { int i, j, tmp, k; wchar_t* t = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); for (i = 1; i < N; i++) { tmp = a[i]; t = b[i]; j = i - 1; while ((j >= 0) && (a[j] > tmp)) { a[j + 1] = a[j]; b[j + 1] = b[j]; j--; } a[j + 1] = tmp; b[j + 1] = t; } } void merge(int get[], wchar_t** name[], int l, int mid, int r) //функция слияния { int k = 0, i = 0, j = 0; int N = mid - l; int M = r - mid + 1; int* c = (int*)malloc((r - l + 1) * sizeof(int)); wchar_t** name_c = (wchar_t**)malloc((r - l + 1) * sizeof(wchar_t*)); i = l; j = mid; while (((i-l) < N) && ((j-mid)< M)) { if (get[i] < get[j]) { c[k] = get[i]; name_c[k] = name[i]; k++; i++; } else { c[k] = get[j]; name_c[k] = name[j]; k++; j++; } } while ((i-l) < N) { c[k] = get[i]; name_c[k] = name[i]; k++; i++; } while ((j - mid) < M) { c[k] = get[j]; name_c[k] = name[j]; k++; j++; } for (i = l; i < r + 1; i++) { get[i] = c[i - l]; name[i] = name_c[i - l]; } } void merge_sort(int a[], wchar_t** name[], int N) { merge_sort_lr(a, name, 0, N - 1); } void merge_sort_lr(int a[], wchar_t** name[], int l, int r) { int mid; if (l >= r) return; mid = l + (r - l) / 2; merge_sort_lr(a, name, l, mid); merge_sort_lr(a, name, mid + 1, r); merge(a, name, l, mid+1, r); } <file_sep>#include <string.h> #include <stdlib.h> #include <stdio.h> #include "banki.h" #define LENGTH 512 #define LEN 30 #define _CRT_SECURE_NO_WARNINGS int strcount(char* path) { int count = 0; char* s = (char*)malloc(1000 * sizeof(char)); FILE* file = fopen(path, "r"); if (file == NULL) { printf("ERROR: Could not open file!\n"); return 1; } while (1) { if (fgets(s, 1000, file) != NULL) { if (strcmp(s, "\n") != 0) { count++; } } else { break; } } fclose(file); free(s); return count; } char* getfile() { char* path = (char*)malloc(_MAX_PATH * sizeof(char)); do { printf("Enter the full location of the file\n"); scanf("%s", path); FILE* file = fopen(path, "r"); if (file == NULL) { printf("ERROR: Could not open file!\n"); } else { fclose(file); return path; } } while (1); } bankstruct** allocbanki(int stringcount) { int i = 0; int j = 0; bankstruct** banki = (bankstruct**)malloc(sizeof(bankstruct*) * stringcount); for (i = 0; i < stringcount; i++) { banki[i] = (bankstruct*)malloc(sizeof(bankstruct)); banki[i]->bankname = (char*)malloc(sizeof(char) * LEN); banki[i]->banktype = (char*)malloc(sizeof(char) * LEN); banki[i]->our_vklad = (vkladstruct**)malloc(sizeof(bankstruct*)*stringcount); } return banki; } void workfile(bankstruct** banki, char* path, int stringcount) { char* token; char delim[] = " ,\n"; int i = 0; int j = 0; int l = 0; FILE* file = fopen(path, "r"); char str[LENGTH]; if (file == NULL) {//проверка printf("ERROR: Could not open file!\n"); return 1; } while (1) { if (fgets(str, 512, file) != NULL) { for (token = strtok(str, delim); token; token = strtok(NULL, delim)) { switch (i) { case 0: strcpy(banki[j]->bankname, token); break; case 1: strcpy(banki[j]->banktype, token); break; case 2: banki[j]->count = strtof(token, NULL); for (l = 0; l < banki[j]->count; l++) { banki[j]->our_vklad[l].vkladname = (char*)malloc(sizeof(char) * LEN); } break; case 3: strcpy(banki[j]->our_vklad[0].vkladname, token); break; case 4: banki[j]->our_vklad[0].rate = strtof(token, NULL); break; case 5: banki[j]->our_vklad[0].times = strtof(token, NULL); if (banki[j]->count == 1) { i = -1; j++; } break; case 6: strcpy(banki[j]->our_vklad[1].vkladname, token); break; case 7: banki[j]->our_vklad[1].rate = strtof(token, NULL); break; case 8: banki[j]->our_vklad[1].times = strtof(token, NULL); if (banki[j]->count == 2) { i = -1; j++; } break; case 9: strcpy(banki[j]->our_vklad[2].vkladname, token); break; case 10: banki[j]->our_vklad[2].rate = strtof(token, NULL); break; case 11: banki[j]->our_vklad[2].times = strtof(token, NULL); if (banki[j]->count == 3) { i = -1; j++; } break; } i++; } } else { break; } } fclose(file); } void data_input(int* sumvkl, int* your_month, char* your_type) { printf("Enter count of money\n"); scanf("%d", sumvkl); printf("For how long is the contribution made\n"); scanf("%d", your_month); printf("Enter type of vklad(saving, debit or cumulative).\n"); scanf("%s", your_type); if ((strcmp(your_type,"saving") != 0) && (strcmp(your_type, "debit") != 0) && (strcmp(your_type, "cumulative") != 0)){ printf("ERROR!This type of vklad does not exist\n"); } } void choosebest(int sumvkl, int your_month, bankstruct** banki, int stringcount, char* your_type) { int a = 0; if (strcmp(your_type, "saving") == 0) { a = 0; } else if ((strcmp(your_type, "debit") == 0)) { a = 1; } else if ((strcmp(your_type, "cumulative") == 0)) { a = 2; } int maxI = 0; int i; float maxproc = -1; int koef = 0; for (i = 1; i < stringcount; i++) { if (banki[i]->count >= (a + 1)) { if (banki[i]->our_vklad[a].rate > maxproc && your_month >= banki[i]->our_vklad[a].times) { koef = (int)your_month / banki[i]->our_vklad[a].times; maxproc = banki[i]->our_vklad[a].rate; maxI = i; } } } int j = 0; double summa = sumvkl; double s = (double)banki[maxI]->our_vklad[a].times / 12; for (j = 0; j < koef; j++) { summa *= (double)(1.00 + maxproc * s / 100); } if (maxproc == -1) { printf("The debit invest is not suitable for the terms\n"); } else { printf("Best %s invest: BANK- %s, in the next year you will receive %.2lf \n", banki[maxI]->our_vklad[a].vkladname, banki[maxI]->bankname, summa); } } void freebanki(bankstruct** banki, int stringcount) { int i = 0; int j = 0; for (i = 0; i < stringcount; i++) { free(banki[i]->bankname); free(banki[i]->banktype); free(banki[i]->our_vklad[j].vkladname); free(banki[i]->our_vklad); free (banki[i]); } free(banki); } <file_sep>#ifndef _FILEPROCESSING_H #define _FILEPROCESSING_H #include <iostream> #include <string> #include <fstream> #include <Windows.h> enum EducationalForm { DNEV, VECHER, ZAOCH }; struct Spec_t { std::string name; int n_form; EducationalForm* forms; int* examScores; int* costs; Spec_t(); Spec_t(const Spec_t&); ~Spec_t(); Spec_t& operator=(const Spec_t&); }; struct University_t { std::string name; int n_spec; Spec_t* specs; University_t(); University_t(const University_t&); ~University_t(); University_t& operator=(const University_t&); void SearchMinScoreSpeciality(std::string& spec_name, int& score, std::string& form) const; float ComputeAverageScore() const; float ComputeAverageCost() const; }; struct Univ_database_t { int count; University_t* univs; Univ_database_t(); Univ_database_t(int count); Univ_database_t(const std::string& fname); Univ_database_t(const Univ_database_t&); ~Univ_database_t(); University_t& operator[] (const int ind); int SearchVUZ(const std::string& name, University_t& u) const; int SearchSpecialties(const std::string& name, Spec_t*& specs, std::string*& names_univ) const; int find_num_univ(const std::string& fname) const; int try_to_open_file(const std::string& fname); }; std::ostream& operator<<(std::ostream& out, const University_t& un); std::ostream& operator<<(std::ostream& out, const Spec_t& sp); #endif<file_sep>#include <stdio.h> #include <stdlib.h> #include "Header.h" #define MAX_PATH 100 // Max path length int main() { int n; BanksData* data; do { n = read(&data); } while (n == 0); print_data(data, n); int user_year; float user_money; input_user_data(&user_year, &user_money); pair ans = comparing(data, n, user_year, user_money); printf("\n The best suggestion for you in %s %s.\n \n if you would invest %.2f in %s deposit at a %.2f per year\n \nYour benefit in %d years will be %.2f rubles \n", data[ans.id1].ownership, data[ans.id1].name, user_money, data[ans.id1].deposits[ans.id2].name, data[ans.id1].deposits[ans.id2].conditions, user_year, ans.profit); freedata(&data, n); free(data); return 0; }<file_sep>#include "person.h" #include <iostream> #include <fstream> #include <sstream> using namespace std; string getPath() { string path; while (true) { cout << "Enter the name of your file:" << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } cout << "ERROR:The file isn`t open\n" << endl; } } int persons_list::person_count(const string& path) { int count = 0; string line; ifstream file(path); while (getline(file, line)) { if (!line.empty()) { count++; } } file.close(); return count; } persons_list::persons_list(const string& path) { this->count = person_count(path); this->persons = new person[count]; ifstream file(path); if (file.is_open()) { string line; int index = 0; while (getline(file, line)) { stringstream ss(line); string token; getline(ss, token, ';'); // Фамилия persons[index].Surname = token; getline(ss, token, ';'); // Имя persons[index].Name = token; getline(ss, token, ';'); // Отчество persons[index].Middle_name = token; getline(ss, token, ';'); // Пол persons[index].Gender = (token == "M") ? male : female; getline(ss, token, ';'); // Национальность persons[index].Nation = token; getline(ss, token, ';'); // Дата рождения stringstream date_ss(token); getline(date_ss, token, '.'); // День persons[index].date.day = stoi(token); getline(date_ss, token, '.'); // Месяц persons[index].date.mounth = stoi(token); getline(date_ss, token, '.'); // Год persons[index].date.year = stoi(token); getline(ss, token, ';'); // Рост persons[index].Height = stof(token); getline(ss, token, ';'); // Вес persons[index].Weight = stof(token); getline(ss, token, ';'); // Телефонный номер persons[index].phone_number = stoll(token); getline(ss, token, ';'); // Почтовый индекс persons[index].address.postal_code = stoi(token); getline(ss, token, ';'); // Страна persons[index].address.Country = token; getline(ss, token, ';'); // Область persons[index].address.Region = token; getline(ss, token, ';'); // Район persons[index].address.Area = token; getline(ss, token, ';'); // Город persons[index].address.City = token; getline(ss, token, ';'); // Улица persons[index].address.Street = token; getline(ss, token, ';'); // Номер дома persons[index].address.House = stoi(token); getline(ss, token, ';'); // Номер квартиры persons[index].address.Apart = stoi(token); index++; } file.close(); } } persons_list::~persons_list() { delete[] persons; } void persons_list::surname_sort() { person* temp = new person; for (int i = 0; i < count; i++) { for (int j = i + 1; j < count; j++) { if (persons[j].Surname != persons[i].Surname) { if (persons[j].Surname < persons[i].Surname) { *temp = persons[i]; persons[i] = persons[j]; persons[j] = *temp; } } else { if (persons[j].Name < persons[i].Name) { *temp = persons[i]; persons[i] = persons[j]; persons[j] = *temp; } } } } } void menu(const persons_list& ps) { int flag_sorted_list; do { cout << "\nHow to output a sorted array?\n1. From A to Z\n2. From Z to A\nEnter a number: "; cin >> flag_sorted_list; if ((flag_sorted_list == 1) || (flag_sorted_list == 2)) { if (flag_sorted_list == 1) { cout << "\n"; for (int i = 0; i < ps.count; i++) cout << ps.persons[i]; } if (flag_sorted_list == 2) { cout << "\n"; for (int i = ps.count - 1; i >= 0; i--) cout << ps.persons[i]; } } else cout << "ERROR: Enter values from the list to display a sorted list" << endl; } while ((flag_sorted_list <= 0) || (flag_sorted_list > 2)); } ostream& operator<<(ostream& out, const person& p) { string gender[]{ "male", "female" }; out << "===========================================" << endl; out << "FIO: " << p.Surname << " " << p.Name << " " << p.Middle_name << endl; out << "Gender: " << gender[p.Gender] << endl; out << "Nation: " << p.Nation << endl; out << "Date: " << p.date.day << "." << p.date.mounth << "." << p.date.year << endl; out << "Height: " << p.Height << endl; out << "Weight: " << p.Weight << endl; out << "Phone number: " << p.phone_number << endl; out << "Postal code: " << p.address.postal_code << endl; out << "Country: " << p.address.Country << endl; out << "Region: " << p.address.Region << endl; out << "Address: city: " << p.address.City << endl; out << "Area: " << p.address.Area << endl; out << "Street: " << p.address.Street << endl; out << "House: " << p.address.House << endl; out << "Apartament: " << p.address.Apart << endl; return out; } ostream& operator<<(ostream& out, const persons_list& pl) { for (int i = 0; i < pl.count; i++) { out << pl.persons[i]; } return out; }<file_sep>#pragma once #ifndef _TAGENCUBOOK_H #define _TAGENCYBOOK_H #include "TAgency.h" enum class FileExeption { NullPtrFile = -1 };//enumeration for file errors class TAgencyBook { private: TAgency** agencies; int count_agencies;//num no european countries void CountAgencies(ifstream& file); int* CountTServices(ifstream& file);//count directions int* counter_euro_countries();//count euro countries int counter_euro_agencies();//count euro agencies void search_string(ifstream& file);//look for the first occurrence of the string вишнёвый_пирожок file_reader(ifstream& file); public: TAgencyBook(void); TAgencyBook(const string& path);//initialising TAgencyBook + call constructor TAgency TAgencyBook(const TAgencyBook& object);//copy_object ~TAgencyBook(); TAgencyBook Get_Europe_Countries();//find european countries and create european massive const TAgencyBook& operator=(const TAgencyBook& obj); friend ostream& operator<<(ostream& stream, const TAgencyBook& obj);//overloading for TAgencyBook }; #endif<file_sep>#include <iostream> #include <fstream> #include <string.h> #include <string> #include "person.h" using namespace std; Person::Person() { surname = " "; name = " "; patronymic = " "; gender = " "; nation = " "; date.day = 0; date.month = 0; date.year = 0; height = " "; weight = " "; num_phone = " "; postal_code = " "; ad.country = " "; ad.region = " "; ad.city = " "; ad.district = " "; ad.street = " "; ad.house = " "; ad.apartament = " "; } Person::Person(string surname, string name, string patronymic, string gender, string nation, int day, int month, int year, string height, string weight, string num_phone, string postal_code, string country, string region, string city, string district, string street, string house, string apartament) { this->surname = surname; this->name = name; this->patronymic = patronymic; this->gender = gender; this->nation = nation; this->date.day = day; this->date.month = month; this->date.year = year; this->height = height; this->weight = weight; this->num_phone = num_phone; this->ad.country = country; this->ad.region = region; this->ad.city = city; this->ad.district = district; this->ad.street = street; this->ad.house = house; this->ad.apartament = apartament; } void Person::set_info(const string& p_surname, const string& p_name, const string& p_patronymic, const string& p_gender, const string& p_nation, const int& p_day, const int& p_month, const int& p_year, const string& p_height, const string& p_weight, const string& p_num_phone, const string& p_postal_code, const string& p_country, const string& p_region, const string& p_city, const string& p_district, const string& p_street, const string& p_house, const string& p_apartament) { surname = p_surname; name = p_name; patronymic = p_patronymic; gender = p_gender; nation = p_nation; date.day = p_day; date.month = p_month; date.year = p_year; height = p_height; weight = p_weight; num_phone = p_num_phone; postal_code = p_postal_code; ad.country = p_country; ad.region = p_region; ad.city = p_city; ad.district = p_district; ad.street = p_street; ad.house = p_house; ad.apartament = p_apartament; } void read(Person** p, int n, string& f) { fstream file; file.open(f); if (!file.is_open()) throw "File open error"; string surname, name, patronymic, nation, gender, height, weight, num_phone, postal_code, country, region, city, district, street, house, apartament; int day, month, year; for (int i = 0; i < n; i++) { string str = ""; int flag = 0; while ((getline(file, str, ';')) && (flag < 18)) { if (flag == 0) { if (i != 0) removeFirstN(str, 1); surname = str; } if (flag == 1) name = str; if (flag == 2) patronymic = str; if (flag == 3) gender = str; if (flag == 4) nation = str; if (flag == 5) day = stoi(str); if (flag == 6) month = stoi(str); if (flag == 7) year = stoi(str); if (flag == 8) height = str; if (flag == 9) weight = str; if (flag == 10) num_phone = str; if (flag == 11) postal_code = str; if (flag == 12) country = str; if (flag == 13) region = str; if (flag == 14) city = str; if (flag == 15) district = str; if (flag == 16) street = str; if (flag == 17) house = str; flag++; } apartament = str; p[i] = new Person(); p[i]->set_info(surname, name, patronymic, gender, nation, day, month, year, height, weight, num_phone, postal_code, country, region, city, district, street, house, apartament); } file.close(); } ostream& operator<<(ostream& out, const Person& p) { out << "FIO: " << p.surname << " " << p.name << " " << p.patronymic << endl; out << "Gender: " << p.gender << endl; out << "Nation: " << p.nation << endl; out << "Date: " << p.date.day << "." << p.date.month << "." << p.date.year << endl; out << "Height: " << p.height << endl; out << "Weight: " << p.weight << endl; out << "Phone number: " << p.num_phone << endl; out << "Postal code: " << p.postal_code << endl; out << "Country: " << p.ad.country << endl; out << "Region: " << p.ad.region << endl; out << "Address: city: " << p.ad.city << ", "; out << p.ad.district << " district, "; out << p.ad.street << " street, "; out << "house number: " << p.ad.house; out << ", apartament: " << p.ad.apartament << endl; out << "<===========================================>" << endl; return out; } int cntStruct(string& f) { fstream file; file.open(f); char* str = new char[1024]; int i = 0; if (!file.is_open()) throw "File open error"; while (!file.eof()) { file.getline(str, 1024, '\n'); i++; } delete[]str; file.close(); return i; } void Sort(Person** p, int n) { Person* tmp; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { if (p[j]->get_surname() != p[i]->get_surname()) { if (p[j]->get_surname() < p[i]->get_surname()) { tmp = p[i]; p[i] = p[j]; p[j] = tmp; } } else { if (p[j]->get_name() < p[i]->get_name()) { tmp = p[i]; p[i] = p[j]; p[j] = tmp; } } } } void removeFirstN(string& str, int n) { str.erase(0, n); }<file_sep>#include "title.h" void main() { const string adress = "shops.txt"; List list(adress); cout << list; cout << "Our shops: " << endl; List our; our.correct_base(list); cout << our; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<math.h> int main() { float h, w, d, t_zad, t_side, t_top_bottom, t_door, t_shelf, m_zad, m_side, m_top_bottom, m_door, m_shelf, distance_shelf, m_cabinet, count_shelf; int count; float density_dsp = 800; float density_dvp = 750; float density_tree = 640; printf("Enter the height of the cabinet (from 180 to 220 cm): "); scanf("%f", &h); if ((h < 180) || (h > 220)) { printf("You entered incorrect data (from 180 to 220 cm)."); return 0; } h = h / 100; printf("Enter the width of the cabinet: (from 80 to 120 cm): "); scanf("%f", &w); if ((w < 80) || (w > 120)) { printf("You entered incorrect data (from 80 to 120 cm)."); return 0; } w = w / 100; printf("Enter the depth of the cabinet: (from 50 to 90 cm): "); scanf("%f", &d); if ((d < 50) || (d > 90)) { printf("You entered incorrect data (from 50 to 90 cm)."); return 0; } d = d / 100; t_zad = 0.005; t_side = 0.015; t_top_bottom = 0.015; t_door = 0.01; t_shelf = 0.015; distance_shelf = 0.4; m_zad = density_dvp * h * w * t_zad; m_side = 2 * density_dsp * h * d * t_side; m_top_bottom = 2 * density_dsp * (w-0.03) * d * t_top_bottom; m_door = density_tree * h * w * t_door; count_shelf = h / 0.415 - 1.015; count = (int)count_shelf; m_shelf = count * density_dsp * (w-0.03) * d * t_shelf; m_cabinet = m_zad + m_side + m_top_bottom + m_door + m_shelf; printf("Cabinet weight : %f", m_cabinet); return 0; }<file_sep>#include <iostream> #include <fstream> #include "polynom.h" using namespace std; TPolynom::TPolynom(void) { // По умолчанию degree = 0; coeff = new float[degree + 1]; for (int i = degree; i >= 0; i--) coeff[i] = 0; } TPolynom::TPolynom(const TPolynom& p) { // Копирование degree = p.degree; coeff = new float[degree + 1]; for (int i = degree; i >= 0; i--) coeff[i] = p.coeff[i]; } TPolynom::TPolynom(int _degree) { // Преобразование типа degree = _degree; coeff = new float[degree + 1]; for (int i = degree; i >= 0; i--) coeff[i] = 0; } TPolynom::TPolynom(int _degree, float _coeff) { // Инициализатор, все coeff = _coeff degree = _degree; coeff = new float[degree + 1]; for (int i = degree; i >= 0; i--) coeff[i] = _coeff; } TPolynom::~TPolynom(void) { // Деконструктор if (degree + 1) delete[] coeff; degree = 0; } bool TPolynom::operator==(const TPolynom& p) const { if (degree != p.degree) return false; for (int i = degree; i >= 0; i--) if (coeff[i] != p.coeff[i]) return false; return true; } bool TPolynom::operator!=(const TPolynom& p) const { return !(*this == p); } const TPolynom& TPolynom::operator=(const TPolynom& p) { if (this != &p) { if (degree != p.degree) { delete[] coeff; degree = p.degree; coeff = new float[degree + 1]; } for (int i = degree; i >= 0; i--) coeff[i] = p.coeff[i]; } return (*this); } TPolynom TPolynom::operator+(const TPolynom& p) { TPolynom res(max_d(degree, p.degree)); if (degree >= p.degree) { for (int i = degree; i >= 0; i--) res.coeff[i] = coeff[i]; for (int i = p.degree; i >= 0; i--) res.coeff[i] += p.coeff[i]; } else { for (int i = p.degree; i >= 0; i--) res.coeff[i] = p.coeff[i]; for (int i = degree; i >= 0; i--) res.coeff[i] += coeff[i]; } if (res.coeff[res.degree] == 0) res.Rebuffer(); return res; } TPolynom TPolynom::operator-(const TPolynom& p) { TPolynom res(max_d(degree, p.degree)); for (int i = res.degree; i >= 0; i--) res.coeff[i] = 0.f; for (int i = degree; i >= 0; i--) res.coeff[i] = coeff[i]; for (int i = p.degree; i >= 0; i--) res.coeff[i] -= p.coeff[i]; if (res.coeff[res.degree] == 0) res.Rebuffer(); return res; } TPolynom TPolynom::operator*(const TPolynom& p) { TPolynom res(degree + p.degree); for (int i = degree; i >= 0; i--) for (int j = p.degree; j >= 0; j--) res.coeff[i + j] += coeff[i] * p.coeff[j]; return res; } float TPolynom::operator()(float _x) { float res = 0.0f, x = 1.0f; for (int i = degree; i >= 0; i--) { res += coeff[i] * x; x *= _x; } return res; } TPolynom& TPolynom::operator+=(const TPolynom& p) { if (p.degree > degree) this->Resize(p.degree); for (int i = p.degree; i >= 0; i--) coeff[i] += p.coeff[i]; if (coeff[degree] == 0) this->Rebuffer(); return *this; } TPolynom& TPolynom::operator-=(const TPolynom& p) { if (p.degree > degree) this->Resize(p.degree); for (int i = p.degree; i >= 0; i--) coeff[i] -= p.coeff[i]; if (coeff[degree] == 0) this->Rebuffer(); return *this; } TPolynom& TPolynom::operator*=(const TPolynom& p) { int tmp_d = degree + p.degree; TPolynom tmp(tmp_d); for (int i = degree; i >= 0; i--) for (int j = p.degree; j >= 0; j--) tmp.coeff[i + j] += coeff[i] * p.coeff[j]; this->Rebuffer(tmp_d); for (int i = tmp_d; i >= 0; i--) coeff[i] = tmp.coeff[i]; return *this; } void read_file(TPolynom*& p, int& n) { /* Чтение происходит из файла "data.txt" -В первой строке - количество полиномов -В второй строке перечисленны степени каждого полинома -В последующих строках перечисленны коэффициенты полиномов !!!Предполагается, что введенные данные верны!!! */ int dgr; ifstream file; file.open("data.txt"); if (!file.is_open()) throw "Файл данных не открыт"; file >> n; p = new TPolynom[n]; for (int i = 0; i < n; i++) { file >> dgr; p[i].Rebuffer(dgr); } for (int i = 0; i < n; i++) { for (int j = p[i].degree; j >= 0; j--) file >> p[i].coeff[j]; if (!p[i].coeff[p[i].degree]) p[i].Rebuffer(); } file.close(); } void TPolynom::Fill_hand() { for (int i = degree; i >= 0; i--) { cout << "x^" << i << " = "; cin >> coeff[i]; } cout << endl; } void TPolynom::Copy(const TPolynom& p) { this->Rebuffer(p.degree); for (int i = degree; i >= 0; i--) coeff[i] = p.coeff[i]; } TPolynom TPolynom::Diff(const TPolynom& p) { this->Rebuffer(0); if (p.degree) { this->Rebuffer(p.degree - 1); for (int i = p.degree - 1; i >= 0; i--) coeff[i] = p.coeff[i + 1] * (i + 1); } return *this; } TPolynom& TPolynom::DiffEq() { int tmp_d = degree - 1; TPolynom tmp(tmp_d); if (degree == 0) return *this; else { for (int i = tmp_d; i >= 0; i--) tmp.coeff[i] = coeff[i + 1] * (i + 1); } this->Rebuffer(tmp_d); for (int i = tmp_d; i >= 0; i--) coeff[i] = tmp.coeff[i]; return *this; } void TPolynom::Rebuffer(int newDegree) { // Изменяет кол-во коэф-ов и зануляет их if (degree + 1) delete[] coeff; degree = newDegree; coeff = new float[degree + 1]; for (int i = degree; i >= 0; i--) coeff[i] = 0.f; } void TPolynom::Rebuffer() { // Проверяет, есть ли у высоких степеней коэф 0. Если да, то уменьшается степень с копированием коэф-ов int tmp_dgr = degree; for (int i = degree; i >= 0; i--) if (coeff[i]) { tmp_dgr = i; break; } if (tmp_dgr != degree) { float* tmp = new float[degree + 1]; _coeffcopy(tmp, coeff); if (degree + 1) delete[] coeff; degree = tmp_dgr; coeff = new float[degree + 1]; for (int i = tmp_dgr; i >= 0; i--) coeff[i] = tmp[i]; delete[] tmp; } } void TPolynom::Resize(int newDegree) { int tmp_degree = degree; float* tmp = new float[tmp_degree]; _coeffcopy(tmp, coeff); if (degree + 1) delete[] coeff; degree = newDegree; coeff = new float[degree + 1]; for (int i = degree; i > tmp_degree; i--) coeff[i] = 0.f; for (int i = tmp_degree; i >= 0; i--) coeff[i] = tmp[i]; delete[] tmp; } void TPolynom::_coeffcopy(float* copy, float* from) { for (int i = degree; i >= 0; i--) copy[i] = from[i]; } float power(float x, int n) { float res = 1.f; for (int i = 0; i < n; i++) res *= x; return res; } <file_sep>#include <stdio.h> #include <time.h> #include <stdlib.h> int main() { char mode; int ch_num; srand((unsigned int)time(NULL)); printf("Hello, let's play a guessing game! Please, choose a mode: 1 or 2\n"); do { scanf_s("%c", &mode, 1); } while (mode != '1' && mode != '2'); if (mode == '1') { // programm choose some number and user try to guess it int c = 0; int gnum; ch_num = rand() % 100; printf("I made a choice in [0, 100]! Please, guess!\n"); while (1) { do { scanf_s("%d", &gnum); } while (gnum > 100 || gnum < 0); if (gnum < ch_num) { printf("No, my number is greater, Try again\n"); c++; } else if (gnum > ch_num) { printf("No, my number is less, Try again\n"); c++; } else { printf("YOU WIN!\n"); printf("You have made %d attempts\n", c + 1); break; } } printf("The End"); } else { int l = 0, r = 1000, try_num, c = 0;; printf("Choose some number in [0, 1000], I try to guess how faster how I can!\n "); while (1) { char ans; try_num = (l + r) / 2; if (r - l == 2) { printf("YAY, I'm a WINNER\nBecause your number is %d!\nI have made %d attemps\n", try_num, c); break; } printf("Your number is %d ?\n'y' - if this is your num\n'g' - if your num is greater\n'l' - if your num is less:\n", try_num); do { scanf_s("%c", &ans, 1); } while (ans != 'g' && ans != 'l' && ans != 'y'); if (ans == 'g') { l = try_num; c++; } else if (ans == 'l') { r = try_num; c++; } else if (ans == 'y') { c++; printf("YAY, I'm a WINNER\nI have made %d attemps\n", c); break; } } printf("The End"); } return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main() { double r1, r2, x1, x2, y1, y2, d; printf("Characteristics of the first cicrle: "); scanf("%lf%lf%lf", &x1, &y1, &r1); printf("Characteristics of the second cicrle: "); scanf("%lf%lf%lf", &x2, &y2, &r2); d = sqrt(x2 * x2 - 2 * x2 * x1 + x1 * x1 + y2 * y2 - 2 * y1 * y2 + y1 * y1); if ((r1 == r2) && (x1 == x2) && (y1 == y2)) { printf("circles are equal."); return 0; } if (d > (r1 + r2)) { printf("Circles do not intersect."); return 0; } if (d < fabs(r1 - r2)) { printf("One circle is located inside the other one"); return 0; } if (d == (r1 + r2)) { printf("circles are intersect externally."); return 0; } if (d == fabs(r1 - r2)) { printf("circles are intersect intermally."); return 0; } if ((d > 0) && (d < fabs(r1 - r2))) { printf("circles do not intersect."); return 0; } if ((d > fabs(r1 - r2)) && (d < (r1 + r2))) { printf("circles have two points of intersection."); return 0; } return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #define N 10 char* barcodes[N] = { "0101", "0202", "0303", "1212", "1414", "2323", "4545", "5236", "5632", "7845" }; char* products[N] = { "Milk", "Bread", "Butter", "Cheese", "Sugar", "Juice", "Chicken", "Jam", "Beer", "Pie" }; int cost[10] = { 20, 10, 15, 80, 90, 150, 100, 40, 60, 70 }; float discount[10] = { 0.05, 0.03, 0.04, 0.15, 0.19, 0.10, 0.18, 0.03, 0.04, 0.09 }; void scan(int* a) { char b[N]; int count[10] = { 0 }; int out=1; int get = 1; printf("Enter codes: \n"); while (out==1) { gets(b); for (int i = 0; i < N; i++) { if (strcmp(barcodes[i], b) == 0) { printf("%s, price: %.2d rubles, diccount: %.2f percent\n", products[i], cost[i], discount[i]); a[i] += 1; printf("If there are no more products in the basket, then enter - 0, if there is - 1: \n"); scanf(" %d", &get); if (get == 0) out = 0; else printf("Enter codes: \n"); break; } } } } void bill(int* a) { float totalCost = 0; printf("List of products:\n"); for (int i = 0; i < N; i++) { if (a[i] == 0) continue; printf("%s, cost per unit: %d, count: %d, price including discount: %.2f\n", products[i], cost[i], a[i], (cost[i] - discount[i] * cost[i]) * a[i]); totalCost += (cost[i] - discount[i] * cost[i]) * a[i]; } printf("Total amount - %.2f", totalCost); } int main() { int counts[N] = { 0 }; scan(counts); bill(counts); return 0; } <file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { float* x; int n; } TMatrix; void allocate_matrix(TMatrix** matrix, int n); void free_matrix(TMatrix** matrix); void fill_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix); TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* add_const(TMatrix* matrix, float c); TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* multi_const(TMatrix* matrix, float c); #endif _MATRIX_H <file_sep>#include "card.h" int main() { int sectionCount; char** section; char* path = menu(); int stringCount = strCount(path); int act = authorsCount(path, stringCount); cardIndex* cards = alloc(stringCount, act); readFile(cards, path, stringCount, act); section = booksBySection(cards, stringCount, act, &sectionCount); selectBook(cards, section, stringCount, act, sectionCount); memoryFree(cards, stringCount, section, act, sectionCount, path); return 0; } //C:\\Users\\nikit\\Desktop\\12.txt<file_sep>#ifndef _CONTAINER_H #define _CONTAINER_H template <typename T> class Container { public: Container() : step(5), size(0), capacity(0), currentIndex(0), elements(new T[0]) {} Container(int capacity, int step = 5) : capacity(capacity), step(step), elements(new T[capacity]), size(0), currentIndex(0) {} ~Container() { delete[] elements; elements = nullptr; } void add(const T& element) { if (size == capacity) { resize(); } elements[size] = element; size++; } void remove(const T& element) { int i; for (i = 0; i < size; i++) { if (elements[i] == element) break; } for (i; i < size - 1; i++) { elements[i] = elements[i + 1]; } size--; } void remove(int index) { if (index >= size || index < 0) { return; } for (int i = index; i < size - 1; i++) { elements[i] = elements[i + 1]; } size--; } int getSize() const { return size; } T& operator[](int index) { return elements[index]; } bool isEnd() const { return currentIndex == size - 1; } void next() { if (isEnd() || size == 0) return; currentIndex++; } void prev() const { if (currentIndex == 0) return; currentIndex--; } T getCurrent() const { if (size == 0) throw ("error"); return elements[currentIndex]; } void resetIndex() { currentIndex = 0; } void reset() { delete[] elements; elements = new T[0]; size = 0; capacity = 0; currentIndex = 0; } void insertBefore(const T& element){ if (size == capacity) { resize(size + 1); } for (size_t i = size; i > currentIndex; i--) { elements[i] = elements[i - 1]; } elements[currentIndex] = element; size++; } void insertAfter(const T& element){ if (size == capacity) { resize(size + 1); } for (size_t i = size; i > currentIndex + 1; i--) { elements[i] = elements[i - 1]; } elements[currentIndex + 1] = element; size++; } void insertAtBeginning(const T& element){ if (size == capacity) { resize(size + 1); } for (size_t i = size; i > 0; i--) { elements[i] = elements[i - 1]; } elements[0] = element; size++; currentIndex++; } int find(const T& element) const{ for (int i = 0; i < size; i++) { if (elements[i] == element) { return i; } } return -1; } Container(const Container& other) : currentIndex(other.currentIndex), size(other.size), capacity(other.capacity), step(other.step), elements(new T[other.capacity]) { for (int i = 0; i < size; i++) { elements[i] = other.elements[i]; } } Container& operator=(const Container& other) { if (this != &other) { delete[] elements; currentIndex = other.currentIndex; size = other.size; capacity = other.capacity; step = other.step; elements = new T[other.capacity]; for (int i = 0; i < size; i++) { elements[i] = other.elements[i]; } } return *this; } private: T* elements; int currentIndex; int size; int capacity; int step; void resize() { T* newElements = new T[capacity + step]; for (int i = 0; i < size; i++) { newElements[i] = elements[i]; } delete[] elements; elements = newElements; capacity += step; } }; #endif // !_CONTAINER_H <file_sep>//Поделючение библиотек #include <stdlib.h> #include <time.h> #include <stdio.h> int main() { char mode_game; printf("Select the game mode: \n1) Mode 1. The program makes a number from 0 to 1000. The user has to guess the number\n2) Mode 2. The user makes a number from 0 to 1000. The program must guess the number\n"); do { scanf("%c", &mode_game); } while ((mode_game != '1') && (mode_game != '2'));//Проверка на корректность ввода if (mode_game == '1') { int i = 0, supposition_play_1, hidden_number;//i - счётчик попыток srand((unsigned int)time(NULL)); hidden_number = rand() % 1001;//Загадывание числа printf("Game start\n"); do { i++; scanf("%d", &supposition_play_1); if (hidden_number == supposition_play_1) { printf("You Win\n Your number of attempts = %d", i); return 0; } else if (supposition_play_1 < hidden_number) printf("Probably the hidden number is more\n"); else printf("Probably the hidden number is less\n"); } while (1);//Бесконечный цикл }; if (mode_game == '2') { int start = 1, finish = 1001, mid, attempts = 0; //mid - текущее среднее значение char symbols = 'n'; // Переменная куда записывается ответ пользователя printf("Tell me, please. Your number > or < or = than need"); while (symbols != '=') { mid = ((start + finish) / 2); printf("\n I think your number is %d\n", mid); scanf(" %c", &symbols); if (symbols == '=' || symbols == '>' || symbols == '<') attempts++; if (symbols == '>') start = mid; else if (symbols == '<') finish = mid; else if (symbols == '=') printf("Hooray, I guessed it in %d attempts", attempts); } } return 0; } <file_sep>#include <stdio.h> #include<time.h> int main() { int a; printf("Vvedite 1, esli hotite sami ugadivat chislo ili vvedite 0, esli hotite chtob computer ygadival chislo"); do { scanf("%d", &a); } while ((a != 1) && (a != 0)); if (a == 1) { int n, x, k = 0; srand((unsigned int)time(NULL)); n = rand() % 1000; printf("vvedite pervuyu popitku"); do { k++; scanf("%d", &x); if (x == n) { printf("vi otgadali"); printf("kolichestvo popitok = %d", k); return 0; } if (x < n) { printf("bolshe"); } if (x > n) { printf("menshe"); } } while ((x >= 0) && (x <= 1000)); } else { int x, y = 0, zmax = 1000, zmin = 0, o = 0; srand((unsigned int)time(NULL)); printf("Mehshe = 0, Ravno = 1, Bolshe = 2 "); do { o++; x = zmin + rand() % (zmax - zmin + 1); printf("\n%d", x); scanf("%d", &y); switch (y) { case 0: { zmax = x; break; } case 1: { printf("Zagannoe chislo = %d ", x); printf("\nKolichestvo popitok = %d", o); return 0; } case 2: { zmin = x; break; } } } while (y != 1); } } <file_sep>#pragma once typedef struct { int n; double* x; } matrix; void alloc_matrix(matrix** m, int n); void free_matrix(matrix** m); void fill_matrix(matrix* m); void print_matrix(matrix* m); matrix* add_matrix(matrix* m1, matrix* m2); matrix* add_scalar(matrix* m, double c); matrix* multi_matrix(matrix* m1, matrix* m2); matrix* multi_scalar(matrix* m, double c);<file_sep>#ifndef _CARD_H #define _CARD_H #define LENGTH 128 typedef enum availability{ AVAILABLE, UNAVAILABLE }; typedef struct { char** authors; char title[LENGTH]; char publisher[LENGTH]; char section[LENGTH]; enum availability avb; float evaluation; } cardIndex; cardIndex* alloc(int stringCount, int authorsCount); void memoryFree(cardIndex* card, int stringCount, char** section, int authorsCount, int sectionCount, char* path); int strCount(char* path); char* menu(); void readFile(cardIndex* cards, char* path, int stringCount, int authorsCount); char** booksBySection(cardIndex* cards, int stringCount, int authorsCount, int* ct); void selectBook(cardIndex* card, char** section, int stringCount, int authorsCount, int sectionCount); int authorsCount(char* path, int stringCount); #endif // !_CARD_H<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> int r(int l, int r) { return rand() % (r - l + 1) + l; } void main() { int N, i, j, x, k_cow, k_bull; //main int ans, k, t; //additional int num[5], a_num[5], digits[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };//arrays srand((unsigned int)time(NULL)); printf("BULLS & COWS\n\n"); printf("Choose the length of the hidden number (from 2 to 5):\n"); do { scanf("%d", &N); if (N < 2 || N > 5) printf("Incorrect length. Choose another:\n"); } while (N < 2 || N > 5); // Number generanion x = r(1, 9); num[0] = x; digits[x] = -1; for (i = 1; i < N; i++) { do x = r(0, 9); while (digits[x] == -1); num[i] = x; digits[x] = -1; } // Generated number for debugging for (i = 0; i < N; i++) printf("%d", num[i]); printf("\n"); // Search for a number printf("Try to guess an %d-digit number:\n\n", N); do { do { scanf("%d", &x); t = x; k = 0; while (t > 0) { t /= 10; k++; } if (k != N) printf("Incorrect lenght, try another:\n\n"); } while (k != N); ans = x; i = N - 1; while (x > 0) { a_num[i] = x % 10; x /= 10; i--; } k_cow = 0; k_bull = 0; for (i = 0; i < N; i++) for (j = 0; j < N; j++) { if (num[i] == a_num[j] && i == j) k_bull++; if (num[i] == a_num[j] && i != j) k_cow++; } printf("Cows = %d\n", k_cow); printf("Bulls = %d\n\n", k_bull); printf("==================\n"); } while (k_bull != N); printf("Congratulations!\nThe hidden number is %d\n", ans); }<file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { int n; float* x; } TMatrix; void alloc_matrix(TMatrix** matrix, int n); void free_matrix(TMatrix** matrix); void scan_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix); TMatrix* matrix_add_const(TMatrix* matrix, float c); TMatrix* matrix_multiply_const(TMatrix* matrix, float c); TMatrix* matrixes_multiply(TMatrix* matrix1, TMatrix* matrix2); #endif<file_sep>#include "receipt.h" #include "container.h" #include <iostream> #include <fstream> #include <sstream> #include <ctime> int Product::getCode() const { return code; } float Product::getPrice() const { return price; } string Product::getName() const { return name; } Product* ReceiptLine::getProduct() const { return product; } int ReceiptLine::getCount() const { return count; } float ReceiptLine::getSumm() const { return summ; } void ReceiptLine::setCount(int count) { this->count = count; } void ReceiptLine::setSumm(int summ) { this->summ = summ; } dataBase::dataBase(const string& path) { ifstream file(path); string line; while (getline(file, line)) { if (line.empty()) { continue; } stringstream ss(line); string name, code, price, count; getline(ss, code, ';'); getline(ss, name, ';'); getline(ss, price, ';'); getline(ss, count, ';'); Product* product = new Product(stoi(code), name, stof(price)); data.push_back(make_pair(product, stoi(count))); } } Product* dataBase::searchProductByCode() { bool isFound = false; int code; while (!isFound) { cout << "Enter product code: "; cin >> code; for (auto& pair : data) { if ((*pair.first).getCode() == code && pair.second > 0) { return pair.first; isFound = true; } } if (!isFound) { cout << "Invalid code or the product is out of stock " << endl; } } } void dataBase::writeData(const string& path) { ofstream out; out.open(path); for (int i = 0; i < data.size(); i++) { out << data[i].first->getCode() << ";" << data[i].first->getName() << ";" << data[i].second << endl; } } void Receipt::addItem(Product* product, dataBase& db) { int quantity; bool isCorrectQuantity = false; while (!isCorrectQuantity) { cout << "Enter quantity: "; cin >> quantity; for (auto& pair : db.data) { if (pair.first->getCode() == (* product).getCode() && pair.second > quantity&& quantity > 0) { isCorrectQuantity = true; break; } } if (!isCorrectQuantity) { cout << "Wrong quantity " << endl; } } for (int i = 0; i < pr.getSize(); i++) { if ((*pr[i].getProduct()).getCode() == (*product).getCode()) { pr[i].setCount(pr[i].getCount() + quantity); pr[i].setSumm((*pr[i].getProduct()).getPrice() * pr[i].getCount()); return; } } ReceiptLine line(product, quantity); pr.add(line); } void Receipt::removeItem(Product* product) { int i; for (i = 0; i < pr.getSize(); i++) { if ((*pr[i].getProduct()).getCode() == (*product).getCode()) { pr.remove(i); return; } } cout << "The product is not in the receipt " << endl; } double Receipt::getTotal() { double total = 0; for (int i = 0; i < pr.getSize(); i++) { total += pr.getCurrent().getSumm(); pr.next(); } return total; } void Receipt::dataUpdate(dataBase& data) { for (int i = 0; i < pr.getSize(); i++) { for (auto& pair : data.data) { if (pr[i].getProduct()->getCode() == pair.first->getCode()) { pair.second -= pr[i].getCount(); } } } } void Receipt::reset() { setTime(); pr.reset(); } void Receipt::setTime() { time_t now = time(nullptr); tm* localTime = localtime(&now); time_.hour = localTime->tm_hour; time_.minute = localTime->tm_min; date.day = localTime->tm_mday; date.mounth = localTime->tm_mon + 1; date.year = localTime->tm_year + 1900; } Product::Product() : code(0), name(""), price(0) {} Product::Product(int code, const string& name, double price) : code(code), name(name), price(price) {} ReceiptLine::ReceiptLine() : count(0), summ(0) {} ReceiptLine::ReceiptLine(Product* product, int count) { this->product = product; this->count = count; summ = (*product).getPrice() * count; } Receipt::Receipt() { setTime(), code = 0; } Receipt::Receipt(int code) { this->code = code, setTime(); } Receipt::Receipt(const Receipt& other) : code(other.code), time_(other.time_), date(other.date), pr(other.pr) {} dataBase::~dataBase() { for (auto& pair : data) { delete pair.first; } data.clear(); } ostream& operator<<(ostream& os, Receipt& receipt) { cout << endl; cout << "receipt number: " << receipt.code << " " << receipt.time_.hour << ":" << receipt.time_.minute << " " << receipt.date.day << "." << receipt.date.mounth << "." << receipt.date.year << endl; for (int i = 0; i < receipt.pr.getSize(); i++) { ReceiptLine receiptLine = receipt.pr[i]; Product* product = receiptLine.getProduct(); os << "Product: " << (*product).getName() << " - " << (*product).getPrice() << " Count: " << receiptLine.getCount() << " Total: " << receiptLine.getSumm() << endl; } return os; } Receipt& Receipt::operator=(const Receipt& other) { if (this != &other) { code = other.code; time_ = other.time_; date = other.date; pr = other.pr; } return *this; }<file_sep>#ifndef _OUTLET_H #define _OUTLET_H typedef enum { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } Day; typedef struct { int hour; int minute; } Time; typedef struct { char* street; int house_number; } address; // структура для хранения рабочих дней магазина typedef struct { Day* days; Time* opens; Time* closes; int workingDaysCount; } workingDays; // структура для хранения сведений о торговой точке typedef struct { char* name; address address; int phone_number; char* specialization; workingDays working_days; } outlet; int count(char* path); outlet* allocateMemory(int outletCount, char* path); char* start(); void readDataFromFile(outlet* retail_outlets, char* path, int count); void all_time(outlet* retail_outlets, int count); void memoryFree(outlet* retail_outlets, int count); #endif // !_OUTLET_H <file_sep>#include <string.h> #include <stdlib.h> #include <stdio.h> #include "outlet.h" char* start() { char* path = (char*)malloc(_MAX_PATH * sizeof(char));//выделение памяти под путь do { printf("Enter path\n"); scanf("%s", path);//считываем у пользователя строку FILE* fp = fopen(path, "r"); //буквально открываем файл на чтение if (fp == NULL) { //если пользователь ввёл неверный путь, то fp(указатель) будет указывать на NULL printf("Wrong path!!!\n"); //соответственно пишем что не верный путь } else {//иначе, если путь к файлу верный, мы закрываем файл и возвращаем строку с путём fclose(fp); return path; } } while (1); } int count(char* path) { int count = 0; //исходное количество торговых точек char* s = (char*)malloc(512 * sizeof(char)); //строка, которую мы будем получать при чтении файла FILE* file = fopen(path, "r"); //открываем файл while (1) { if (fgets(s, 512, file) != NULL) {// если строки существуют мы их считываем if (strcmp(s, "\n") != 0) { count++; } } else { break; } } fclose(file);//закрываем файл и освобождаем памить из под строки(т.к она была динамической) free(s); return count; } int countSubs(char* string, char* sub) {//подсчитывает подстроки в строке, нужна для подсчёта рабочих дней int l = strlen(sub); int n = 0; while ((string = strstr(string, sub)) != NULL) { ++n; string += l; } return (n + 1) / 3; } void daysCount(char* path, int count, outlet* outlets) {//считает количество дней и записывает это значение каждому магазину в поле workingDaysCount char* token; char delim[] = ";\n"; int i = 0, j = 0;//счётчики FILE* file = fopen(path, "r"); char str[512]; while (1) { if (fgets(str, 512, file) != NULL) { for (token = strtok(str, delim); token; token = strtok(NULL, delim)) { switch (i) { case 5: outlets[j].working_days.workingDaysCount = countSubs(token, ",");//записываем количество дней i = -1; j++; break; } i++; } } else { break; } } fclose(file); } outlet* allocateMemory(int outletCount, char* path) {//выделение памяти outlet* retail_outlets = malloc(sizeof(outlet) * outletCount); if (retail_outlets == NULL) { perror("Ошибка выделения памяти"); return NULL; } for (int i = 0; i < outletCount; i++) { daysCount(path, outletCount, retail_outlets); // Выделение памяти для имени магазина retail_outlets[i].name = malloc(sizeof(char) * 100); // Предполагаем максимальную длину имени 100 символов retail_outlets[i].specialization = malloc(sizeof(char) * 100); // Выделение памяти для названия улицы retail_outlets[i].address.street = malloc(sizeof(char) * 100); // Предполагаем максимальную длину названия улицы 100 символов // Выделение памяти для массива рабочих дней retail_outlets[i].working_days.days = malloc(sizeof(Day) * retail_outlets[i].working_days.workingDaysCount); // Выделение памяти для массивов времени открытия и закрытия retail_outlets[i].working_days.opens = malloc(sizeof(Time) * retail_outlets[i].working_days.workingDaysCount); retail_outlets[i].working_days.closes = malloc(sizeof(Time) * retail_outlets[i].working_days.workingDaysCount); } return retail_outlets; } void readDataFromFile(outlet* retail_outlets, char* path, int count) {//считывает данные из файла и записывает в элементы массива retail_outlets FILE* file = fopen(path, "r"); if (file == NULL) { perror("Ошибка открытия файла"); return; } char line[512]; int outletIndex = 0; while (fgets(line, 512, file) != NULL) { if (line[0] == '\n') { continue; // игнорируем пустые строки(\n) } char* token; token = strtok(line, ";"); strcpy(retail_outlets[outletIndex].name, token); token = strtok(NULL, ";"); strcpy(retail_outlets[outletIndex].address.street, token); token = strtok(NULL, ";"); retail_outlets[outletIndex].address.house_number = atoi(token); token = strtok(NULL, ";"); retail_outlets[outletIndex].phone_number = atoi(token); token = strtok(NULL, ";"); strcpy(retail_outlets[outletIndex].specialization, token); token = strtok(NULL, ","); int i = 0; while (token != NULL) { // Обработка данных для каждого дня Day currentDay; Time opens, closes; if (strcmp(token, "Monday") == 0) currentDay = Monday; else if (strcmp(token, "Tuesday") == 0) currentDay = Tuesday; else if (strcmp(token, "Wednesday") == 0) currentDay = Wednesday; else if (strcmp(token, "Thursday") == 0) currentDay = Thursday; else if (strcmp(token, "Friday") == 0) currentDay = Friday; else if (strcmp(token, "Saturday") == 0) currentDay = Saturday; else if (strcmp(token, "Sunday") == 0) currentDay = Sunday; token = strtok(NULL, ":"); opens.hour = atoi(token); token = strtok(NULL, ","); opens.minute = atoi(token); token = strtok(NULL, ":"); closes.hour = atoi(token); token = strtok(NULL, ","); closes.minute = atoi(token); // Запись данных в массивы структуры retail_outlets[outletIndex].working_days.days[i] = currentDay; retail_outlets[outletIndex].working_days.opens[i] = opens; retail_outlets[outletIndex].working_days.closes[i] = closes; i++; token = strtok(NULL, ","); } outletIndex++; } fclose(file); } void memoryFree(outlet* retail_outlets, int count) { int i; for (i = 0; i < count; i++) { free(retail_outlets[i].name); free(retail_outlets[i].specialization); free(retail_outlets[i].address.street); free(retail_outlets[i].working_days.days); free(retail_outlets[i].working_days.opens); free(retail_outlets[i].working_days.closes); } free(retail_outlets); } void print(outlet* retail_outlets, int index) {//стандартный вывод элемента массива retail_outlets(т.е торговой точки) int i; const char* dayNames[] = { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" }; printf("________________________________\n"); printf("%s\n", retail_outlets[index].name); printf("Adress: %d, %s\n", retail_outlets[index].address.house_number, retail_outlets[index].address.street); printf("Telephone: %d\n", retail_outlets[index].phone_number); printf("Specialization: %s\n", retail_outlets[index].specialization); printf("Working schedule:\n"); for (i = 0; i < retail_outlets[index].working_days.workingDaysCount; i++) { printf("%s: %02d:%02d - %02d:%02d\n", dayNames[retail_outlets[index].working_days.days[i]], retail_outlets[index].working_days.opens[i].hour, retail_outlets[index].working_days.opens[i].minute, retail_outlets[index].working_days.closes[i].hour, retail_outlets[index].working_days.closes[i].minute); } } void all_time(outlet* retail_outlets, int count) {//вывод круглосуточных магазинов int i, j; printf("24/7 Shops:\n"); for (i = 0; i < count; i++) {//перебираем все магазины, если какой-то соответствует условию, то пишем его int altm = 0; for (j = 0; j < retail_outlets[i].working_days.workingDaysCount; j++) { if (retail_outlets[i].working_days.opens[j].hour == retail_outlets[i].working_days.closes[j].hour && retail_outlets[i].working_days.opens[j].minute == retail_outlets[i].working_days.closes[j].minute) {//круглосуточным магазином будем считать тот, у которого время открытия и время закрытия равны altm++; } } if (retail_outlets[i].working_days.workingDaysCount == altm) print(retail_outlets, i); } }<file_sep> #include <stdio.h> #include "matrixx.h" #include <stdio.h> int main() { TMatrix* matrix_dynamic, * m1, * m2, * res; matrix_alloc(&matrix_dynamic, 2); scan_matrix(matrix_dynamic); print_matrix(matrix_dynamic); free_matrix(&matrix_dynamic); matrix_alloc(&m1, 3); matrix_alloc(&m2, 3); scan_matrix(m1); printf("Your Matrix 1\n"); print_matrix(m1); scan_matrix(m2); printf("Your Matrix 2\n"); print_matrix(m2); printf("Matrix 1 + Matrix 2\n"); res = matrix_add_matrix(m1, m2); print_matrix(res); free_matrix(&res); printf("Matrix 1 * Constant(100)\n"); res = matrix_multi_constant(m1, 100); print_matrix(res); free_matrix(&res); printf("Matrix 1 + Constnt(1000)\n"); res = matrix_add_constant(m1, 1000); print_matrix(res); free_matrix(&res); printf("Matrix 1 * Matrix 2\n"); res = matrix_multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#include "matrix.h" #include <stdio.h> #include <stdlib.h> void alloc_matrix(TMatrix** matrix, int n) { (*matrix) = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n; (*matrix)->x = (float*)malloc(sizeof(float) * n * n); } void free_matrix(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } void fill_matrix(TMatrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { scanf("%f", &(matrix->x[matrix->n * i + j])); } } } void print_matrix(TMatrix* matrix) { int i = 0, j; for (; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { printf("%.3f ", (matrix->x[matrix->n * i + j])); } printf("\n"); } printf("\n"); } TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; int i = 0; if (matrix1->n != matrix2->n) { printf("ERROR: Matrix should have the same lenght.\n"); return NULL; } alloc_matrix(&res, matrix1->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix1->x[i] + matrix2->x[i]; } return res; } TMatrix* add_constant(TMatrix* matrix, float c) { TMatrix* res; int i = 0; alloc_matrix(&res, matrix->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix->x[i] + c; } return res; } TMatrix* multi_constant(TMatrix* matrix, float c) { TMatrix* res; int i = 0; alloc_matrix(&res, matrix->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix->x[i] * c; } return res; } TMatrix* multi_matrix(TMatrix* matrix, TMatrix* matrix2) { TMatrix* res; int i, j, k; alloc_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = 0; for (k = 0; k < res->n; k++) res->x[i * res->n + j] += matrix->x[i * res->n + k] * matrix2->x[k * res->n + j]; } } return res; }<file_sep>#include "person.h" #include <iostream> using namespace std; int main() { string path = getPath(); PersonsList pl(path); cout << pl << endl; pl.surname_sort(); cout << "Sorted persons list:\n" << pl << endl; return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" int main() { TMatrix* m1, *m2, *res; int n; printf("enter matrix size\t"); scanf("%d", &n); printf("enter the elements of the first matrix\n"); allocate_matrix(&m1, n); fill_matrix(m1, n); print_matrix(m1, n); printf("enter the elements of the second matrix\n"); allocate_matrix(&m2, n); fill_matrix(m2, n); print_matrix(m2, n); res = add_matrix(m1, m2, n); printf("add_matrix result:\n"); print_matrix(res, n); free_matrix(&res); res = add_const(m1, 2); printf("add_const result:\n"); print_matrix(res, n); free_matrix(&res); res = multi_const(m1, 2); printf("multi_const result:\n"); print_matrix(res, n); free_matrix(&res); res = multi_matrix(m1, m2, n); printf("multi_matrix result:\n"); print_matrix(res, n); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#include "stdafx.h" vacancy::vacancy() { employee = " "; nameCompany = " "; salary = 0; request = " "; workCond = " "; } string vacancy::getInfoVacancy(int select) { switch (select) { case 1: return employee; case 2: return nameCompany; case 3: return to_string(salary); case 4: return workCond; case 5: return request; default: return "Неправильный ввод параметра"; } } ostream& operator<<(ostream& os, const vacancy& vac) { os << vac.employee << endl; os << "Название компании: " << vac.nameCompany << endl; os << "Оплата труда: " << vac.salary << " в месяц." << endl; os << "Условия труда: " << vac.workCond << endl; os << "Требования к соискателю: " << vac.request << endl; return os; } istream& operator>>(istream& is, vacancy& vac) { string salary, empty; getline(is, vac.employee); getline(is, vac.nameCompany); getline(is, salary); vac.salary = atoi(salary.c_str()); getline(is, vac.workCond); getline(is, vac.request); getline(is, empty); return is; } string enter_path() { string path; cout << "Введите путь: "; cin >> path; return path; } ifstream vacancyLib::read_list(const string& path) { ifstream read(path); if (!read) cerr << "Файл не удалось открыть!" << endl; else cout << "Файл по пути " << path << " был успешно открыт!" << endl; return read; } int vacancyLib::count_vacancy(ifstream& stream) { string text; int count = 1; while (getline(stream, text)) count++; count /= 6; if (count == 0) return NULL; return count; } vacancy* vacancyLib::fill_from_txt(ifstream& stream, int countVacancy) { vacancy* Vacancy = new vacancy[countVacancy]; int i = 0; stream.clear(); stream.seekg(0); while (i < countVacancy) { stream >> Vacancy[i]; i++; } return Vacancy; } vacancyLib vacancyLib::search_vacancy() { string search; int i = 0, j = 0; cout << "Введите название профессии, которую вы ищете: "; getchar(); getline(cin, search); int* index = new int[count]; for (int k = 0; k < count; k++) index[k] = -1; while (i < count) { if (Vacancy[i].getInfoVacancy(1).compare(search) == 0) { index[j] = i; j++; } i++; } vacancy* srchVacancy = new vacancy[j]; for (i = 0; i < j; i++) { srchVacancy[i] = Vacancy[index[i]]; //cout << srchVacancy[i]; } vacancyLib res(srchVacancy, j); return res; } ostream& operator<<(ostream& os, const vacancyLib& vacLib) { for (int i = 0; i < vacLib.count; i++) { os << "----------------------------------------" << endl; os << vacLib.Vacancy[i]; os << "----------------------------------------" << endl << endl << endl; } return os; } vacancyLib::vacancyLib() { count = 0; Vacancy = nullptr; } vacancyLib::vacancyLib(const string& path) { ifstream read; read = read_list(path); if (!read) throw - 1; count = count_vacancy(read); Vacancy = new vacancy[count]; Vacancy = fill_from_txt(read, count); read.close(); } vacancyLib::vacancyLib(vacancy* OutVacancy, int OutCount) { count = OutCount; Vacancy = new vacancy[count]; for (int i = 0; i < count; i++) Vacancy[i] = OutVacancy[i]; } vacancyLib::vacancyLib(const vacancyLib& vac_copy) { Vacancy = new vacancy[vac_copy.count]; count = vac_copy.count; for (int i = 0; i < count; i++) Vacancy[i] = vac_copy.Vacancy[i]; } vacancyLib::~vacancyLib() { delete[] Vacancy; } vacancyLib& vacancyLib::operator= (const vacancyLib& cp_vac) { if (this == &cp_vac) { // проверяем, что мы не присваиваем объект самому себе return *this; } if (count != cp_vac.count) { // проверяем, если количество элементов изменилось, то освобождаем память и выделяем новую delete[] Vacancy; count = cp_vac.count; Vacancy = new vacancy[count]; } for (int i = 0; i < count; i++) { // копируем значения из объекта cp_vac в текущий Vacancy[i] = cp_vac.Vacancy[i]; } return *this; // возвращаем ссылку на текущий объект } <file_sep>#include "userSide.h" #include "fileProcessing.h" std::string switch_form(EducationalForm form) { std::string name_form; switch (form) { case DNEV: name_form = "Дневная"; break; case VECHER: name_form = "Вечерняя"; break; case ZAOCH: name_form = "Заочная"; break; } return name_form; } std::string main_entering_mode() { std::string in; getline(std::cin, in); while ((in != "1") && (in != "2") && (in != "0")) { std::cout << "Не корректный ввод, попробуйте ещё раз, следуйте инструкциям!\n"; getline(std::cin, in); } return in; } std::string entering_mode() { std::string in; getline(std::cin, in); while ((in != "1") && (in != "2")) { std::cout << "Не корректный ввод, попробуйте ещё раз, следуйте инструкциям!\n"; getline(std::cin, in); } return in; } // University info: void about_univercity(Univ_database_t& unsdata) { std::string in; University_t curr_univ; int univ_ind; std::cout << "Выберите интересующую вас информацию:\n"; std::cout << "Всё о конкретном ВУЗе - введите 1;\nСпециальность с минимальным баллом в конкретном ВУЗе - введите 2;\n"; in = entering_mode(); if (in == "1") { int cost, score, code; std::string name; std::cout << "Вы выбрали 'Всё о конкретном ВУЗе'\nВведите название вуза:\n"; do { getline(std::cin, name); code = unsdata.SearchVUZ(name, curr_univ); if (code == -1) std::cout << "ВУЗа с таким названием нет в базе, попробуйте ещё раз\n"; } while (code == -1); cost = curr_univ.ComputeAverageCost(); score = curr_univ.ComputeAverageScore(); std::cout << curr_univ; std::cout << "Средний балл для поступления по ВУЗу: " << score << "\n"; std::cout << "Средняя стоимость обучения по ВУЗу : " << cost << "\n\n"; } else if (in == "2") { std::string name; Spec_t s; int code; std::cout << "вы выбрали 'специальность с минимальным баллом в конкретном вузе'\nвведите название вуза:\n"; do { getline(std::cin, name); code = unsdata.SearchVUZ(name, curr_univ); if (code == -1) std::cout << "ВУЗа с таким названием нет в базе, попробуйте ещё раз\n"; } while (code == -1); int min_score; std::string name_form, spec_name; curr_univ.SearchMinScoreSpeciality(spec_name, min_score, name_form); std::cout << "Минимальный балл для поступления в ВУЗе " << curr_univ.name << ": " << min_score << "\n"; std::cout << "Это специальность: " << spec_name << ", Форма обучения: " << name_form << std::endl; } } // Specialty at a university: void print_all_about_spec(Spec_t* spec_arr, int c, std::string* names_univs) { std::cout << "Специальность " << spec_arr[0].name << " присутствует в следующем перечне ВУЗов:\n"; for (int i = 0; i < c; i++) { std::cout << "ВУЗ " << names_univs[i] << ":\n"; std::cout << spec_arr[i]; } } void print_min_score_for_spec(Spec_t* spec_arr, int c, std::string* names_univs) { int min = 1000; std::string name_form, name_univ; EducationalForm edForm; for (int i = 0; i < c; i++) { for (int z = 0; z < spec_arr[i].n_form; z++) { if (spec_arr[i].examScores[z] < min) { min = spec_arr[i].examScores[z]; edForm = spec_arr[i].forms[z]; name_form = switch_form(edForm); name_univ = names_univs[i]; } } } std::cout << "По указанной специальности минимальный проходной балл по ВУЗам НН составляет: " << min << ". ВУЗ: "; std::cout << name_univ << ", форма обучения: " << name_form << std::endl; } void about_spec(Univ_database_t& unsdata) { std::cout << "Выберите интересующую вас информацию:\n"; std::cout << "Всё о специальности - введите 1;\nМинимальный балл по специальности среди вузов - введите 2;\n"; std::string in; in = entering_mode(); if (in == "1") { std::string name; int count_such_specs = 0; Spec_t* specs; std::string* names_univs; std::cout << "Вы выбрали 'Всё о специальности'\nВведите название специальности:\n"; do { getline(std::cin, name); count_such_specs = unsdata.SearchSpecialties(name, specs, names_univs); if (count_such_specs == 0) { std::cout << "Специальности с таким названием ни в одном ВУЗе из базы данных нет!, попробуйте ещё раз\n"; } } while (count_such_specs == 0); print_all_about_spec(specs, count_such_specs, names_univs); } else if (in == "2") { std::string name; int count_such_specs = 0; Spec_t* specs; std::string* names_univs; printf("Вы выбрали 'Минимальный балл по специальности среди вузов'\nВведите название специальности:\n"); do { getline(std::cin, name); count_such_specs = unsdata.SearchSpecialties(name, specs, names_univs); if (count_such_specs == 0) { std::cout << "Специальности с таким названием ни в одном ВУЗе из базы данных нет!, попробуйте ещё раз\n"; } } while (count_such_specs == 0); print_min_score_for_spec(specs, count_such_specs, names_univs); } } void working_with_user(Univ_database_t& unsdata) { int end = 1; std::cout << "Что бы вы хотели узнать?\n"; while (end) { std::string in; std::cout << "Если интересует информация о конкретном ВУЗе - нажмите 1, если о конкретной специальности - 2;\n"; std::cout << "Если же узнали всю необходимую информацию и хотите завершить сессию - нажмите 0;\n\n"; in = main_entering_mode(); if (in == "1") { about_univercity(unsdata); } else if (in == "2") { about_spec(unsdata); } else if (in == "0") { std::cout << "Спасибо, что выбрали нас, до скорых встреч!\n"; end = 0; } std::cout << "\n"; } }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Film.h" int main() { // get path to file with films char* path = getInput("Enter the path to file : "); puts(path); // read file and save info about Films to array int count_of_films; Film* films = ReadFileWithFilms(path, &count_of_films); // get films by procuder char* producer_info = getInput("Enter producer's name and surname separated by a space: "); int count_of_found_films = 0; Film* found_films = getFilmsByProducer(films, count_of_films, getProducerFromString(producer_info), &count_of_found_films); // print answer printf("Count of found films by entered producer = %d\n\n", count_of_found_films); for (int i = 0; i < count_of_found_films; ++i) { PrintFilm(found_films[i]); } return 0; } <file_sep>#include <iostream> #include <fstream> #include <string> #include "triangle.h" #include <math.h> using namespace std; int main() { Triangle* triangles; string f; cout << "Enter filename or path: "; cin >> f; int n = read(triangles, f); for (int i = 0; i < n; i++) { cout << triangles[i]; } int t = 0; int type; while (1) { printf("Select an operation : 1 - area, 2 - perimeter, 3 - height, 4 - type of triangle: "); cin >> t; for (int i = 0; i < n; i++) { if (t == 1) triangles[i].CountSquare(); else if (t == 2) triangles[i].CountPerimeter(); else if (t == 3) triangles[i].Height(); else if (t == 4) { type = triangles[i].TriangleType(); if (type == straight) cout << "straight" << endl; else if (type == sharp) cout << "sharp" << endl; else if (type == blunt) cout << "blunt" << endl; } } cout << "If you want to exit, enter 0: "; cin >> t; if (t == 0) break; } delete[] triangles; return 0; }<file_sep>#include "Client.h" #include <fstream> #include <sstream> void create_updating_db(TProductsDatabase& db) { ofstream ofc; ofc.open("basenew.txt",ios::out|ios::trunc); for (int i = 0; i < db.Get_num_prods(); i++) { ofc << db[i].product.code << ";"; ofc << db[i].product.name << ";"; ofc << db[i].product.price << ";"; ofc << db[i].count << ";"; ofc << "\n"; } ofc.close(); } string get_action(string action) { do { cout << "Enter '1' for create new receipt " << endl; cout << "Enter '0' to complete " << endl; getline(cin, action); if ((action) != "1" && (action != "0")) { cout << "Uncorrect input." << endl; } } while (action != "1" && action != "0"); return action; } int get_barcode_to_add(TProductsDatabase& db, string user_input) { int search; bool available; do { available = true; search = db.barcode_search(stol(user_input)); if (search == -1) { cout << "No the product with this barcode" << endl; getline(cin, user_input); } if (db[search].count == 0) { available = false; cout << "Product is out. Add another " << endl; getline(cin, user_input); } } while (search == -1 || !available); return search; } void work_with_client(TProductsDatabase& db) { TContainer<TReceipt> receipts; while (1) { string action; action = get_action(action); if (action == "0") { break; } TReceipt curr_receipt; bool f = false; while (!f) { string user_input; cout << "Enter barcode."<<endl; cout << "Enter '#' to complete this receipt and print it " << endl; cout << "Enter '-' to delete some product " << endl; getline(cin, user_input); if (user_input == "#") { f = true; } else if (user_input == "-") { curr_receipt.Delete(db); } else { int search = get_barcode_to_add(db, user_input); curr_receipt.Add(db, search); } } if (curr_receipt.Get_num_products() == 0) { cout << "You haven't added any products. The reciept hasn't created\n"; } else { curr_receipt.SetTime(); receipts.insert(curr_receipt); cout << receipts.current(); } } create_updating_db(db); }<file_sep>#ifndef _SCHOOL_H #define _SCHOOL_H typedef struct{ char* FIO; int Class; char* Gender; char* Date; char* Address; } TSchool; void allocation(TSchool** school, int n); void release(TSchool** school, int n); int counting(); void read_file(TSchool* school); void print_file(TSchool* school, int n); void sorting(TSchool* school, int n); #endif<file_sep>#include <stdlib.h> #include <stdio.h> #include "matrixx.h" void matrix_alloc(TMatrix** matrix, int n) { (*matrix) = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n; (*matrix)->x = (float*)malloc(sizeof(float) * n * n); } void scan_matrix(TMatrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { scanf("%f", &(matrix->x[matrix->n * i + j])); } } } void print_matrix(TMatrix* matrix) { int i = 0, j; for (; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { printf("%.3f ", (matrix->x[matrix->n * i + j])); } printf("\n"); } printf("\n"); } void free_matrix(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } TMatrix* matrix_add_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; int i = 0; if (matrix1->n != matrix2->n) { printf("Brrr: Matrix aren`t the same size.\n"); return NULL; } matrix_alloc(&res, matrix1->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix1->x[i] + matrix2->x[i]; } return res; } TMatrix* matrix_multi_matrix(TMatrix* matrix, TMatrix* matrix2) { TMatrix* res; int i, j, k; matrix_alloc(&res, matrix->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = 0; for (k = 0; k < res->n; k++) res->x[i * res->n + j] += matrix->x[i * res->n + k] * matrix2->x[k * res->n + j]; } } return res; } TMatrix* matrix_add_constant(TMatrix* matrix, float c) { TMatrix* res; int i = 0; matrix_alloc(&res, matrix->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix->x[i] + c; } return res; } TMatrix* matrix_multi_constant(TMatrix* matrix, float c) { TMatrix* res; int i = 0; matrix_alloc(&res, matrix->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix->x[i] * c; } return res; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> char codes[10][4] = { "1234","2345","3456","4567","5678","6789","7891","8912","9123","9999" }; char names[10][7] = { "salt ","sugar ","bread ", "milk ","eggs ","tea ","cheese ","meat ","honey ","oil " }; int cost[10] = { 50, 60, 40, 80, 80, 50, 200, 300, 150, 75 }; double sale[10] = { 0.1, 0.2, 0.05, 0.05, 0.1, 0.2, 0.04, 0.04, 0.1, 0.2}; void f_init(double* cost_sale, double* sale_r); void f_main_work(char* pr, int* k_pr, double* sale_r, double* cost_sale); void scan_pr(char* a); int ind_pr(char* b); void info_pr(int ind, double* a, double* b); void f_cheque(int* k_pr, double* cost_sale); void f_total(double a, double b, double c, int* k, double* arrA, double* arrB); int main() { char pr[4]; int i, flag = 0; int ind; int counter; int k_pr[10] = { 0 }; double total_not_sale = 0, total_sale = 0, total_with_sale = 0; double cost_sale[10] = { 0 }; double sale_r[10] = { 0 }; f_init(cost_sale, sale_r); f_main_work(pr, k_pr, sale_r, cost_sale); f_cheque(k_pr, cost_sale); f_total(total_not_sale, total_sale, total_with_sale, k_pr, sale_r, cost_sale); return 0; } void f_init(double* cost_sale, double* sale_r) { int i; for (i = 0; i < 10; i++) { cost_sale[i] = cost[i] * (1 - sale[i]); } for (i = 0; i < 10; i++) { sale_r[i] = cost[i] * sale[i]; } } void f_main_work(char* pr, int* k_pr, double* sale_r, double* cost_sale) { int flag = 1, ind; char counter; char tmp; while (flag == 1) { printf("Scan the product \n"); scan_pr(pr); ind = ind_pr(pr); if (ind == -1) continue; k_pr[ind] += 1; info_pr(ind, sale_r, cost_sale); printf("Do you have any more products? y/n \n"); scanf("%c", &tmp); if (tmp == '\n') { scanf("%c", &counter); } else { counter = tmp; } while ((counter != 'n') && (counter != 'y')) { printf("You need to enter y(yes) or n(no). Try again:\n"); scanf("%c", &tmp); if (tmp == '\n') { scanf("%c", &counter); } else { counter = tmp; } } if (counter == 'n') flag = 0; if (counter == 'y') continue; } } void scan_pr(char* a) { int i; char tmp; scanf("%c", &tmp); if (tmp == '\n') { for (i = 0; i < 4; i++) { scanf("%c", &a[i]); } } else { a[0] = tmp; for (i = 1; i < 4; i++) { scanf("%c", &a[i]); } } } int ind_pr(char* b) { int i, j, flag = 1; for (i = 0; i < 10; i++) { flag = 1; for (j = 0; j < 4; j++) { if (codes[i][j] != b[j]) { flag = 0; } } if (flag == 1) return i; } printf("Incorrect data. Try again:\n"); return -1; } void info_pr(int ind,double* a, double* b) { int i; for (i = 0; i <= 6; i++) printf("%c" , names[ind][i]); printf("cost = %d ", cost[ind]); printf("sale = %g ", a[ind]); printf("total %g \n", b[ind]); } void f_cheque(int* k_pr, double* cost_sale) { int i, j; double total_cost[10] = { 0 }; printf("\n"); printf("Your cheque: \n"); for (i = 0; i < 10; i++) { total_cost[i] = k_pr[i] * cost_sale[i]; } for (i = 0; i < 10; i++) { if (k_pr[i] != 0) { for (j = 0; j <= 6; j++) printf("%c", names[i][j]); printf("cost %g ", cost_sale[i]); printf("quantity = %d ", k_pr[i]); printf("total cost = %g \n", total_cost[i]); } } } void f_total(double a, double b, double c, int* k, double* arrA, double* arrB) { int i, a1, b1, c1; for (i = 0; i < 10; i++) { a += k[i] * cost[i]; b += k[i] * arrA[i]; c += k[i] * arrB[i]; } a1 = (int)a; b1 = (int)b; c1 = (int)c; printf("Cost without discount = %d \nThe amount of discounts = %d\nCost including discounts = %d\n", a1, b1, c1); }<file_sep>#include <stdlib.h> #include <stdio.h> #include "matrix.h" int main() { TMatrix* m1, * m2, * res; alloc_matrix(&m1, 3); alloc_matrix(&m2, 3); fill_matrix(m1); fill_matrix(m2); print_matrix(m1); print_matrix(m2); res = add_scalar(m1, 1); print_matrix(res); free_matrix(&res); res = multi_scalar(m1, 10); print_matrix(res); free_matrix(&res); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <locale.h> int main() { float x1, y1, r1; float x2, y2, r2; float d; printf("Enter the coordinates of the center and the radius of the first circle: "); scanf("%f %f %f", &x1, &y1, &r1); printf("Enter the coordinates of the center and the radius of the second circle: "); scanf("%f %f %f", &x2, &y2, &r2); d = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); if (d == 0) { if (r2 == r1) printf("Circles match "); else printf("One circle lies inside another "); } else if (d < abs(r1 - r2)) printf("One circle lies inside another "); else if (d == abs(r1 - r2)) printf("The circles touch each other from the inside "); else if (d > abs(r1 - r2) && d < r1 + r2) printf("Circles intersect "); else if (d == r1 + r2) printf("Circles touch each other on the outside "); else printf("The circles lie apart from each other "); return 0; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include "workers.h"; #define N 100 char* get_Path() { char* path = (char*)malloc(_MAX_PATH * sizeof(char)); do { printf("Enter the file path:"); gets(path); FILE* file = fopen(path, "r"); if (file == NULL) { printf("Ooops.....Something went wrong......\n"); } else { fclose(file); return path; } } while (1); } void allocate_workers(worker** w, int n) { (*w) = (worker*)malloc(sizeof(worker) * n); for (int i = 0; i < n; i++) { (*w + i)->id = (char*)malloc(sizeof(char) * N); (*w + i)->profession = (char*)malloc(sizeof(char) * N); (*w + i)->education = (char*)malloc(sizeof(char) * N); (*w + i)->last_job = (char*)malloc(sizeof(char) * N); (*w + i)->rsn_dismiss = (char*)malloc(sizeof(char) * N); (*w + i)->family_status = (char*)malloc(sizeof(char) * N); } } int amount(char* path) { int amount = 0; char* str = (char*)malloc(N * sizeof(char)); FILE* file = fopen(path, "r"); while (1) { if (fgets(str, N, file) != NULL) { if (strcmp(str, "\n") != 0) { amount++; } } else { break; } } free(str); return amount; } void adding(worker* w, char* path) { char* token; char srch[] = ";\n"; int i = 0; int j = 0; FILE* file = fopen(path, "r"); char* str = (char*)malloc(1024 * sizeof(char)); while (1) { if (fgets(str, 1000, file) != NULL) { for (token = strtok(str, srch); token; token = strtok(NULL, srch)) { switch (i) { case 0: strcpy(w[j].id, token); break; case 1: strcpy(w[j].profession, token); break; case 2: strcpy(w[j].education, token); break; case 3: strcpy(w[j].last_job, token); break; case 4: strcpy(w[j].rsn_dismiss, token); break; case 5: strcpy(w[j].family_status, token); break; case 6: w[j].contact_info = atoi(token); i = -1; j++; break; } i++; } } else { break; } } free(str); } void higher_education(worker* w, int count) { float counter = 0; int i; printf("All employees with higher education from the database:\n"); for (i = 0; i < count; i++) { if (strcmp(w[i].education, "no") != 0) { printf("%-5s %20s\n", w[i].id, w[i].education); counter++; } } printf("Percentage of employees with higher education:%.3f%%\n ", (counter / count) * 100); } void free_workers(worker** w, int n) { for (int i = 0; i < n; i++) { free((*w + i)->id); free((*w + i)->profession); free((*w + i)->education); free((*w + i)->last_job); free((*w + i)->rsn_dismiss); free((*w + i)->family_status); } free(*w); } <file_sep>#ifndef _prototypes_h #define _prototypes_h #define LEN 1024 typedef struct // list of service { char* country; char* travel_conditions; char* excursion_services; char* host_service; char* ticket_price; } TService; typedef struct // Tourist agency { int num_services; char* name; TService *services; } TAgency; int CountAgencies(FILE* fptr);//count agencies int* CountTServices(FILE* fptr);//count directions void allocate_TAgency(TAgency** pointer);//allocating guide list... void allocate_TServices(TAgency* ptr, int count_services);//allocating list of service int file_reader(FILE* fptr, TAgency*** list);//reading data void search_string(FILE* fptr); void output_all_data(FILE* fptr, TAgency** list, int num_agencies);//all data void output_data_EZONES(FILE* fptr, TAgency** list, int num_agencies);//data about euro zones void free_memory(TAgency** pointer, int num_agencies);//freeing up memory #endif<file_sep>#include "outlet.h" #include <stdlib.h> #include <stdio.h> int main() { char* path = start(); int outletCount = count(path); // функция считает количество торговых точек outlet* retail_outlets = allocateMemory(outletCount, path);//выделение памяти readDataFromFile(retail_outlets, path, outletCount);//считывает данные из файла и записывает в элементы массива retail_outlets all_time(retail_outlets, outletCount);//выводит круглосуточные магазины memoryFree(retail_outlets, outletCount);//освобождение памяти return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include "functions.h" void main() { char filename[31]; if (fgets(filename, 30, stdin) != NULL) filename[strlen(filename) - 1] = '\0'; struct EmployeesInfo_t* g_empls; struct Pasports_t* g_pspts; int n = 12; allocstructmem(n, filename, &g_empls, &g_pspts); age_scan(n, g_empls, g_pspts); struct_free(g_empls, g_pspts); } <file_sep>#ifndef _CLIENTSIDE_H #define _CLIENTSIDE_H #include "Header.h" void work_with_client(TProductsDatabase& db); #endif<file_sep>#include <iostream> #include <string> #include "display.h" #include "receipt.h" using namespace std; void dsp::StartMenu() { cout << "Добро пожаловать на кассу!\n" << endl; cout << "1. Начать" << endl; cout << "0. Выход\n" << endl; } void dsp::MainMenu() { Line("-", 50); cout << "1. Отсканировать товары" << endl; cout << "2. Оплатить" << endl; cout << "3. Посмотреть корзину" << endl; cout << "4. Удалить товар из корзины" << endl; cout << "0. Выход" << endl; Line("-", 50); cout << endl; } void dsp::ScanAns(int& ans) { do { cin >> ans; } while (ans < 0 || ans > mainmenu); } void dsp::MenuScanAns(int& ans) { do { cin >> ans; } while (ans < 0 || ans > menuscanproduct); } void dsp::Line(string l, int count) { for (int i = 0; i < count; i++) cout << l; cout << endl; } void dsp::Press2Continue() { int tmp; cout << "\nНажмите любую клавишу, чтобы продолжить.\n" << endl; cin >> tmp; }<file_sep>#ifndef _SORTS_H #define _SORTS_H typedef struct { char* name; int l; } file_t; #define LENGTH 50 void merge(file_t* a, int left, int mid, int right); void mergeSort(file_t* a, int left, int right); void BubbleSort(file_t* a, int len); void QuickSort(file_t* a, int low, int high); #endif <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <time.h> #include <math.h> #define N 5 int main() { int len, i, a, k, d, j, fl, s, get, buk, korova, check, m; int arr[N] = { 0 }; int b[N] = { 0 }; srand((unsigned int)time(NULL)); printf("Choose the length of the number (from 2 to 5): "); do { scanf(" %d", &len); if ((len > 5) || (len < 2)) { printf("Incorrect number entered. Try again: "); } } while ((len > 5) || (len < 2)); arr[0] = 1+ (rand() % 9); d = 0; fl = 1; for (i = 1; i < len; i++) { fl = 1; while (1) { d = rand() % 10; fl = 1; for (j = 0; j < i; j++) { if (arr[j] == d) { fl = 0; break; } } if (fl == 1) { arr[i] = d; break; } } } get = 0; buk = 0; korova = 0; check = 10; for (i = 1; i < len - 1; i++) { check = check * 10; } while (buk != len) { printf("Try to guess the number: "); do { scanf(" %d", &get); if ((get < check) || (get >= check*10)) { printf("Incorrect number entered. Try again: "); } else { m = get; while (m > 0) { if ((m % 10) == (m / 10 % 10)) { printf("Incorrect number entered. Try again: "); break; } m = m / 10; } } } while ((get < check) || (get >= check * 10)); i = len - 1; while (get > 0) { b[i] = get % 10; get = get / 10; i--; } buk = 0; korova = 0; for (i = 0; i < len; i++) { if (arr[i] == b[i]) { buk++; } } for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { if (arr[i] == b[j]) { if (i!=j) korova++; } } } printf("Number of bulls: %d. Number of cows: %d\n", buk, korova); } printf("Congratulations!"); }<file_sep>#include <stdio.h> int main() { double h, w, d, backwall, sidewall, lids, doors, shelves_height, shelves = 0, m; printf("Enter the back wall height h(sm.)="); scanf("%lf", &h); printf("Enter back wall width w(sm.)="); scanf("%lf", &w); printf("Enter sidewall depth d(sm.)="); scanf("%lf", &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) { printf("Invalid data entered"); return 1; } backwall = h * w * 0.5 * 0.8; sidewall = 2 * h * d * 1.5 * 0.65; lids = 2 * (w-3) * d * 1.5 * 0.65; doors = h * w * 0.55; shelves_height = 41.5; while (shelves_height < h) { shelves += d * (w - 3) * 1.5 * 0.65; shelves_height += 41.5; } printf("Total cabinet weight(kg.)=%lf", (backwall + sidewall + lids + doors + shelves) / 1000); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { char ind; printf("Take the letter (A or B) \n"); do{ scanf("%c", &ind); } while ((ind!='A') && (ind!='B')); if (ind=='A'){ int i=0; int n, comm; srand(time(NULL)); n=rand()%1000; printf("Write a number\n"); do { i++; scanf("%d",&comm); if (comm==n) { printf("Correct\n"); printf("Number of attempts: %d", i); printf("\n"); } if (comm<n) { printf("More\n"); printf("Write a number\n"); } if (comm>n) { printf("Less\n"); printf("Write a number\n"); } } while (comm!=n); } else { int znach=0, init, mini=1, maxi=1000, count=0; char com; printf("Rules: \n"); printf("More==M, Less==L, Correct==C\n"); printf("Pick a number\n"); do { scanf("%d",&init); } while ((init<0)||(init>1000)); do { count++; znach=(mini+maxi)/2; printf("It's %d", znach); printf("?\n"); do { scanf("%c",&com); } while ((com != 'M')&&(com != 'L')&&(com != 'C')); if (com == 'M'){ mini=znach; } else if (com == 'L'){ maxi=znach; } else { printf("It's a number %d", znach); printf("!\n"); printf("Number of attempts %d", count); return 0; } } while(1); } return 0; } <file_sep>#include "Header.h" #include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> using namespace std; //Date void Date::now() { time_t rawtime; //creates and object of the built in time function time(&rawtime); //gets the time from the computer timeinfo = localtime(&rawtime); //store that time here /* year = timeinfo->tm_year + 1900; month = timeinfo->tm_mon + 1; day = timeinfo->tm_mday; hour = timeinfo->tm_hour; min = timeinfo->tm_min; sec = timeinfo->tm_sec; */ std::cout << asctime(timeinfo) << endl; } //Cart bool Cart::operator == (const Cart& tmp) const { if (tmp.product == nullptr) return product == nullptr; return (*(product) == *(tmp.product)); } bool Cart::operator == (const Base & tmp) const { return (*product == tmp.get_product()); } bool Cart::operator != (const Cart& tmp) const { return !(product == tmp.product); } bool Cart::operator == (const string& tmp) const { return *product == tmp; } bool Cart::operator <= (const int& ncount) const { return count <= ncount; } Cart& Cart::operator = (const Cart& tmp) { product = tmp.product; count = tmp.count; cost = tmp.cost; return *this; } Cart& Cart::operator += (const int& ncount) { count += ncount; return *this; } Cart& Cart::operator -= (const int& ncount) { count -= ncount; return *this; } Product* Cart::get_product() const { return product; } int Cart::get_count() const { return count; } double Cart::get_cost() const { return cost; } //Receipt const Receipt& Receipt::operator=(const Receipt& receipt) { if (*this == receipt) return *this; num = receipt.num; size = receipt.size; Date = receipt.Date; cart = receipt.cart; return *this; } //functions void Receipt::add(const Cart& product, const int& count) { int id = cart.find_id(product); if (id != -1) { if (cart[id] == product) { cart[id] += count; return; } } size += 1; cart.push_back(product); } void Receipt::add(const Product& product, const int& count ) { Cart tmp(product, count, product.get_cost()); add(tmp, count); } void Receipt::remove(const Cart& product, const int& count) { int id = cart.find_id(product); if (id != -1) { if (cart[id] <= count) { cart.pop_id(id); size--; } else { cart[id] -= count; } } } double Receipt::sum() const { double sum = 0; for (int i = 0; i < size; i++) { sum = sum + cart[i].get_cost() * cart[i].get_count(); } return sum; } void Receipt::print_cart() const { if (!size) { cout << "Nothing in the cart. Add something!" << endl; return; } cout << "\nYour products:\n "; cout << cart << endl; } void Receipt::pdata() { Date.now(); } void Receipt::set_num(const int& q) { (q > 0) ? num = q : num = 1; } Cart* Receipt::find(const Base& product) const { for (int i = 0; i < size; i++) { if (cart[i] == product) return &cart[i]; } return nullptr; } Cart* Receipt::find(const string& product) const { Cart tmp; for (int i = 0; i < size; i++) { if (cart[i] == product) return &cart[i]; } return nullptr; } int Receipt::len() const { return size; } bool Receipt::empty() const { return size == 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "person.h" #define const_c 30 int cntStruct(FILE* file) { int cnt = 0; int any; FILE* f = fopen(file, "r"); if (f == NULL) { return -1; } do { any = fgetc(f); if (any == '\n') { cnt++; } } while (any != EOF); fclose(f); return cnt; } void allocate_person(Person** p) { (*p) = (Person*)malloc(sizeof(Person) * 1); (*p)->surname = (char*)malloc(sizeof(char) * const_c); (*p)->name = (char*)malloc(sizeof(char) * const_c); (*p)->patronymic = (char*)malloc(sizeof(char) * const_c); (*p)->gender = (char*)malloc(sizeof(char) * const_c); (*p)->nation = (char*)malloc(sizeof(char) * const_c); (*p)->date = (char*)malloc(sizeof(char) * const_c); (*p)->height = (char*)malloc(sizeof(char) * const_c); (*p)->weight = (char*)malloc(sizeof(char) * const_c); (*p)->num_phone = (char*)malloc(sizeof(char) * const_c); (*p)->postal_code = (char*)malloc(sizeof(char) * const_c); (*p)->ad.country = (char*)malloc(sizeof(char) * const_c); (*p)->ad.region = (char*)malloc(sizeof(char) * const_c); (*p)->ad.city = (char*)malloc(sizeof(char) * const_c); (*p)->ad.district = (char*)malloc(sizeof(char) * const_c); (*p)->ad.street = (char*)malloc(sizeof(char) * const_c); (*p)->ad.house = (char*)malloc(sizeof(char) * const_c); (*p)->ad.apartament = (char*)malloc(sizeof(char) * const_c); } void fill_data(Person* p, FILE* file) { char str[200], sep[10] = ";"; char* istr; int flag = 0; fgets(str, 200, file); istr = strtok(str, sep); while (str != NULL) { if (flag == 0) strcpy(p->surname, istr); if (flag == 1) strcpy(p->name, istr); if (flag == 2) strcpy(p->patronymic, istr); if (flag == 3) strcpy(p->gender, istr); if (flag == 4) strcpy(p->nation, istr); if (flag == 5) strcpy(p->date, istr); if (flag == 6) strcpy(p->height, istr); if (flag == 7) strcpy(p->weight, istr); if (flag == 8) strcpy(p->num_phone, istr); if (flag == 9) strcpy(p->postal_code, istr); if (flag == 10) strcpy(p->ad.country, istr); if (flag == 11) strcpy(p->ad.region, istr); if (flag == 12) strcpy(p->ad.city, istr); if (flag == 13) strcpy(p->ad.district, istr); if (flag == 14) strcpy(p->ad.street, istr); if (flag == 15) strcpy(p->ad.house, istr); if (flag == 16) strcpy(p->ad.apartament, istr); if (flag == 17) break; istr = strtok(NULL, sep); flag++; } } void read(Person*** p, int* n, const FILE* file) { int i, j; file = fopen(file, "r"); if (file == NULL) { printf("FiLe error"); return 1; } (*n) = cntStruct("people.txt"); // считаем количество структур *p = (Person**)malloc(sizeof(Person*) * (*n));// выделяем под структуры for (i = 0; i < (*n); i++) { allocate_person(&((*p)[i])); // выделяем память для каждой структуры fill_data((*p)[i], file);// заполняем структуру } fclose(file); } void print_persons(Person* p) { printf("\nFIO: %s ", p->surname); printf("%s ", p->name); printf("%s \n", p->patronymic); printf("Gender: %s \n", p->gender); printf("Nation: %s \n", p->nation); printf("Date: %s \n", p->date); printf("Height: %s \n", p->height); printf("Weight: %s \n", p->weight); printf("Phone number: %s \n", p->num_phone); printf("Postal code: %s \n", p->postal_code); printf("Country: %s \n", p->ad.country); printf("Region: %s region \n", p->ad.region); printf("Address: city: %s, ", p->ad.city); printf("%s district, ", p->ad.district); printf("%s street, ", p->ad.street); printf("house number: %s, ", p->ad.house); printf("apartament: %s \n", p->ad.apartament); printf("===================================================================================="); } void Sort(Person** p, int n) { Person* tmp; allocate_person(&tmp); int i, j; for (i = 0; i < n; i++) for (j = i + 1; j < n; j++) { if (strcmp(p[j]->surname, p[i]->surname) != 0) { if (strcmp(p[j]->surname, p[i]->surname) < 0) { tmp = p[i]; p[i] = p[j]; p[j] = tmp; } } else { if (strcmp(p[j]->name, p[i]->name) < 0) { tmp = p[i]; p[i] = p[j]; p[j] = tmp; } } } } void free_person(Person** p) { free((*p)->ad.apartament); free((*p)->ad.house); free((*p)->ad.street); free((*p)->ad.district); free((*p)->ad.city); free((*p)->ad.region); free((*p)->ad.country); free((*p)->postal_code); free((*p)->num_phone); free((*p)->weight); free((*p)->height); free((*p)->date); free((*p)->nation); free((*p)->gender); free((*p)->patronymic); free((*p)->name); free((*p)->surname); free(*p); }<file_sep>#ifndef _PRODUCTS_H #define _PRODUCTS_H #include <iostream> #include <iomanip> // setfill(), setw() #include <string> using namespace std; class TProduct { private: string code; string name; double cost; public: TProduct(const string& _code = "", const string& _name = "", const double _cost = 0); void Set(const string _code, const string _name, const double _cost); string GetCode() const { return code; } string GetName() const { return name; } double GetCost() const { return cost; } bool operator==(const TProduct& p) const; const TProduct& operator=(const TProduct& p); // Печать всех данных о продукте без форматирования void Print() { cout << code << ' ' << name << ' ' << cost; } ostream& ostreamProduct(ostream& out); // Печать с выделенным количеством места (с форматированием) friend ostream& operator<<(ostream& out, const TProduct& p) { int NameLeng = 35; int CostLeng = 5; char NameFill = ' '; char CostFill = ' '; string tmp_name = p.name; if (tmp_name.length() > NameLeng) tmp_name.erase(NameLeng, tmp_name.length()); out << p.code << ' '; out << setfill(NameFill) << setw(NameLeng) << tmp_name << ' '; out << setfill(CostFill) << setw(CostLeng) << p.cost << ' '; return out; } }; #endif // !_PRODUCTS_H <file_sep>#include <iostream> #include <fstream> #include <string.h> #include <string> #include "person.h" using namespace std; void read(Person*& p, int& n) { string f; cout << "Enter filename or path: "; cin >> f; n = cntStruct(f); p = new Person[n]; fill_data(p, n, f); } void fill_data(Person*& p, int n, string& f) { fstream file; file.open(f); if (!file.is_open()) throw "File open error"; for (int i = 0; i < n; i++) { string str = ""; int flag = 0; while ((getline(file, str, ';')) && (flag < 16)) { if (flag == 0) { if (i != 0) removeFirstN(str, 1); p[i].surname = str; } if (flag == 1) p[i].name = str; if (flag == 2) p[i].patronymic = str; if (flag == 3) p[i].nation = str; if (flag == 4) p[i].gender = str; if (flag == 5) p[i].date = str; if (flag == 6) p[i].height = str; if (flag == 7) p[i].weight = str; if (flag == 8) p[i].num_phone = str; if (flag == 9) p[i].postal_code = str; if (flag == 10) p[i].ad.country = str; if (flag == 11) p[i].ad.region = str; if (flag == 12) p[i].ad.city = str; if (flag == 13) p[i].ad.district = str; if (flag == 14) p[i].ad.street = str; if (flag == 15) p[i].ad.house = str; flag++; } p[i].ad.apartament = str; } file.close(); } ostream& operator<<(ostream& out, const Person& p) { out << "FIO: " << p.surname << " " << p.name << " " << p.patronymic << endl; out << "Gender: " << p.gender << endl; out << "Nation: " << p.nation << endl; out << "Date: " << p.date << endl; out << "Height: " << p.height << endl; out << "Weight: " << p.weight << endl; out << "Phone number: " << p.num_phone << endl; out << "Postal code: " << p.postal_code << endl; out << "Country: " << p.ad.country << endl; out << "Region: " << p.ad.region << endl; out << "Address: city: " << p.ad.city << ", "; out << p.ad.district << " district, "; out << p.ad.street << " street, "; out << "house number: " << p.ad.house; out << ", apartament: " << p.ad.apartament << endl; out << "<===========================================>" << endl; return out; } int cntStruct(string& f) { fstream file; file.open(f); char* str = new char[1024]; int i = 0; if (!file.is_open()) throw "File open error"; while (!file.eof()) { file.getline(str, 1024, '\n'); i++; } delete[]str; file.close(); return i; } void Sort(Person*& p, int n) { Person* tmp = new Person[1]; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { if (p[j].surname != p[i].surname) { if (p[j].surname < p[i].surname) { *tmp = p[i]; p[i] = p[j]; p[j] = *tmp; } } else { if (p[j].name < p[i].name) { *tmp = p[i]; p[i] = p[j]; p[j] = *tmp; } } } } void removeFirstN(string& str, int n) { str.erase(0, n); }<file_sep>#ifndef _HEADER_H #define _HEADER_H using namespace std; struct date { int day; int month; int year; date(); date(const string& str); const date& operator= (const date& e); friend ostream& operator<<(ostream& out, const date& d) { out << d.day << "." << d.month << ".19" << d.year; return out; }; }; class pasport { private: int series; int number; string auth; string reg; date issue; date birth; public: pasport(); pasport(const string* str); bool isElderly() const; const pasport& operator= (const pasport& e); friend ostream& operator<<(ostream& out, const pasport& p) { out << p.birth; return out; }; }; class employee { private: pasport pspt; string name; string edu; string spec; string unit; string appnt; date dateofappnt; date lastdate; public: employee(); employee(const string& str); pasport givepasport(); const employee& operator= (const employee& e); friend ostream& operator<<(ostream& out, const employee& e) { out << e.name << " - " << e.pspt; return out; }; }; class lib { private: int emp_amount; employee* empls; public: lib(int n); lib(const lib& l); lib(const string& filename); ~lib(); employee& operator[](int ind); friend ostream& operator<<(ostream& out, const lib& l) { for (int i = 0; i < l.emp_amount; i++) { out << l.empls[i] << endl; } return out; } lib output() const; }; string get_string(ifstream& file); #endif //!_HEADER_H<file_sep>#include"Sorts.h" void merge(file_t* a, int left, int mid, int right) { int i0 = 0, i1 = 0, i2 = left; file_t b[LENGTH]; while ((i0 < (mid - left + 1)) && (i1 < (right - mid))) { if (a[left + i0].l <= a[mid + i1 + 1].l) { b[i2] = a[left + i0]; i0++; } else { b[i2] = a[mid + i1 + 1]; i1++; } i2++; } while (i0 < (mid - left + 1)) { b[i2] = a[left + i0]; i0++; i2++; } while (i1 < (right - mid)) { b[i2] = a[mid + i1 + 1]; i1++; i2++; } for (int j = left; j < i2; j++) { a[j] = b[j]; } } void mergeSort(file_t* a, int left, int right) { if (left < right) { int mid; mid = (left + right) / 2; mergeSort(a, left, mid); mergeSort(a, mid + 1, right); merge(a, left, mid, right); } } void BubbleSort(file_t* a, int len) { file_t tmp; tmp.name = ' '; tmp.l = -1; for (int g = 0; g < len; g++) { for (int j = 0; j < len - g - 1; j++) { if (a[j + 1].l < a[j].l) { tmp = a[j + 1]; a[j + 1] = a[j]; a[j] = tmp; } } } } void QuickSort(file_t* a, int low, int high) { int pivot, j = high, g = low; file_t tmp; pivot = a[(low + (high - low) / 2)].l; do { while (a[g].l < pivot) { g++; } while (a[j].l > pivot) { j--; } if (g <= j) { if (a[g].l > a[j].l) { tmp = a[g]; a[g] = a[j]; a[j] = tmp; } g++; if (j > 0) { j--; } } } while (g <= j); if (g < high) { QuickSort(a, g, high); } if (j > low) { QuickSort(a, low, j); } }<file_sep>#ifndef _RECEIPT_H #define _RECEIPT_H #include <iostream> #include <string> #include "products.h" #include "container.h" #include "datentime.h" #include "database.h" #include "display.h" using namespace std; class TReceiptLine { private: int count; double sum; TProduct* product; public: TReceiptLine(); bool Scan(TDataBase& data, const string& code, const int _count = 1); void AddCount(int _count = 1); string GetCode() const { return (*product).GetCode(); } string GetName() const { return (*product).GetName(); } double GetCost() const { return (*product).GetCost(); } int GetCount() const { return count; } double GetSum() const { return sum; } bool operator==(const TReceiptLine& rl); const TReceiptLine& operator=(const TReceiptLine& rl); friend ostream& operator<<(ostream& out, const TReceiptLine& rl) { out << *(rl.product) << "*" << rl.count << " =" << rl.sum; return out; } }; class TReceipt { private: int index; string code; // Èíäèâèäóàëüíûé êîä ÷åêà TContainer<TReceiptLine> products; TDate date; TTime time; double sum; double money; double odd_money; public: TReceipt(); void Add(const TReceiptLine& product, int _count = 1); void Del(int index); void Del(const TReceiptLine& product); void Change(int ind, int _count); void Cart(); int Count() const; double GetSum() const { return sum; } void SetCode(int _code); void Show() const; void Payment(TDataBase& data, const double _money); void Clear(); void LastScan(); void SetIndex(int _index) { _index = index; } void SetCLOCK() { date.setCurrentDay(); time.setCurrentTime(); } int _find(const TReceiptLine& rl) const { return products._find(rl); } int FindCount(const TReceiptLine& rl); const TReceipt& operator=(const TReceipt& r); TReceiptLine operator[](int ind); bool operator==(const TReceipt& r) const; friend ostream& operator<<(ostream& out, const TReceipt& r) { cout << "×åê #" << r.code << endl; cout << r.date << ' ' << r.time << "\n" << endl; cout << r.products << endl; cout << "Èòîãîâàÿ ñóììà ê îïëàòå: " << r.sum << " ðóá." << endl; cout << "Âû îïëàòèëè: " << r.money << " ðóá." << endl; cout << "Âàøà ñäà÷à: " << r.odd_money << " ðóá.\n" << endl; cout << "ÑÏÀÑÈÁÎ ÇÀ ÏÎÊÓÏÊÓ! ÆÄÅÌ ÂÀÑ ÑÍÎÂÀ!!!" << endl; } }; #endif // !_RECEIPT_H<file_sep>#include "Header.h" #include <iostream> #include <fstream> using namespace std; int PathError() { std::cout << "This file isn`t exist. Be sure, that u writed a correct path with type *.<type>" << endl; return 1; } string input_path() { string path; std::cout << "Input a path: \n "; cin >> path; ifstream file(path); if (!file) { throw PathError(); } return path; } double operator+(int& f, Cart s) { double tmp = f; tmp += s.get_cost(); return tmp; } void user() { NewContainer<Base> base; NewContainer<Base>::read(input_path(), base); Receipt q; q.set_num(1); //Base* e = base.get_elements(); std::cout << "Hi. Lets start.\n\nThis is all our products:\n "; cout << base << endl; while (true) { std::cout << "Choose what do u wanna do " << endl; std::cout << "Input 0 :kill the programm 1: add some products 2: remove some products 3: output receipt(cart) 4: print all products " << endl; int user, f = 1; cin >> user; if (user == 0) { f = 0; std::cout << "Have a nice day! " << endl; break; } if (user == 1) { f = 0; std::cout << "Which one do u wanna add ? Pls input code of product" << endl; string product; cin >> product; int count = 0, ucount; // if we dont have the product if (base.find(product) == nullptr) { std::cout << "Sorry, we dont have this product now" << endl; continue; } //now we know, that we have this product "pr" Base pr = *base.find(product); count = pr.get_count(); cout << "\nYour product: " << pr.get_product() << endl; std::cout << "\nInput a count of products between 0 and " << count << endl; cin >> ucount; //changing count in the base if (ucount < 0 || ucount > count) { std::cout << "Wrong count. Try again" << endl; continue; } if (ucount == 0) continue; base[base.find_id(pr)].set_count(pr.get_count() - ucount); //add if (q.find(pr) != nullptr) q.add(*q.find(pr), ucount); else { q.add(pr.get_product(), ucount); } cout << "\nDone! \n\n" << endl; } if (user == 2) { f = 0; q.print_cart(); if (q.empty()) { cout << "Nothing in the cart. Add something!\n" << endl; continue; } std::cout << "Which one do u wanna remove ? Pls input code of product" << endl; string product; cin >> product; int ucount; //find element in the cart Cart* tmp = q.find(product); if (tmp == nullptr) { std::cout << "Sorry, we dont have this product in the cart " << endl; continue; } //user count std::cout << "Input a count of products between 0 and " << tmp->get_count() << endl; cin >> ucount; if (ucount < 0 || ucount > tmp->get_count()) { std::cout << "Wrong count. Try again" << endl; continue; } // add deleted from the cart elements to the base int index = base.find_id(product); if (index >= 0 && index < base.len()) { base[index] += ucount; } //remove q.remove(*tmp, ucount); cout << "\nDone!" << endl; q.print_cart(); } if (user == 3) { f = 0; if (q.empty()) { cout << "Nothing in the cart. Add something.\n" << endl; continue; } cout << "Time of receipt formation: " << endl; q.pdata(); q.print_cart(); cout << "Total cost: " << q.sum() << endl; } if (user == 4) { cout << " " << base; f = 0; } if (f) cout << "Input Date is wrong. Try again. " << endl; } string filename; cin >> filename; dump_data_base(base, filename); std::cout << "Have a nice day! " << endl; } template <typename Type> void dump_data_base(const NewContainer<Type>& base, const string& filename) { std::ofstream file(filename); if (file.is_open()) { file << base << endl; file << "DONE!!!" << endl; } file.close(); } <file_sep>#include <stdio.h> #include <stdlib.h> #include "polynom.h" void allocate_polynom(TPolynom** polynom, int degree) { (*polynom) = (TPolynom*)malloc(sizeof(TPolynom) * 1); (*polynom)->degree = degree; (*polynom)->coeff = (float*)malloc(sizeof(float) * (degree + 1)); } TPolynom* allocate_polynom_copy(TPolynom** p, TPolynom** tmp) { int i, tmp_dgr = 0; for (i = (*tmp)->degree; i >= 0; i--) if ((*tmp)->coeff[i] != 0) { tmp_dgr = i; break; } allocate_polynom(p, tmp_dgr); for (i = (*p)->degree; i >= 0; i--) (*p)->coeff[i] = (*tmp)->coeff[i]; free_polynom(tmp); return *p; } void free_polynom(TPolynom** polynom) { free((*polynom)->coeff); free(*polynom); } void read_file(TPolynom*** p, int* n) { /* Чтение происходит из файла "data.txt" -В первой строке - количество полиномов -В второй строке перечисленны степени каждого полинома -В последующих строках перечисленны коэффициенты полиномов !!!Предполагается, что введенные данные верны!!! */ int i, dgr; FILE* file; file = fopen("data.txt", "r"); fscanf(file, "%d", n); *(p) = (TPolynom**)malloc(sizeof(TPolynom*) * *(n)); // массив полиномов for (i = 0; i < *(n); i++) { // Инициализация fscanf(file, "%d", &dgr); allocate_polynom(&((*(p))[i]), dgr); } for (i = 0; i < *(n); i++) { // Заполнение fill_polynom((*(p))[i], file); } fclose(file); } void fill_polynom(TPolynom* p, FILE* file) { int i; for (i = p->degree; i >= 0; i--) { fscanf(file, "%f", &(p->coeff[i])); } } void print_polynom(TPolynom* p) { int i; printf("%.2fx^%d ", (p->coeff[p->degree]), (p->degree)); for (i = p->degree - 1; i >= 0; i--) { if (p->coeff[i] > 0) printf("+ %.2fx^%d ", (p->coeff[i]), i); else if (p->coeff[i] < 0) printf("- %.2fx^%d ", -(p->coeff[i]), i); } printf("\n"); } TPolynom* plus_polynom(TPolynom* p1, TPolynom* p2) { TPolynom* res; TPolynom* tmp; int i, tmp_dgr = 0; if ((p1->degree) > (p2->degree)) { allocate_polynom(&tmp, p1->degree); for (i = p1->degree; i >= 0; i--) tmp->coeff[i] = p1->coeff[i]; for (i = p2->degree; i >= 0; i--) tmp->coeff[i] += p2->coeff[i]; } else { allocate_polynom(&tmp, p2->degree); for (i = p2->degree; i >= 0; i--) tmp->coeff[i] = p2->coeff[i]; for (i = p1->degree; i >= 0; i--) tmp->coeff[i] += p1->coeff[i]; } res = allocate_polynom_copy(&res, &tmp); return res; } TPolynom* multi_polynom(TPolynom* p1, TPolynom* p2) { TPolynom* mul; int i, j, D; D = (p1->degree) + (p2->degree); allocate_polynom(&mul, D); for (i = D; i >= 0; i--) mul->coeff[i] = 0; for (i = p1->degree; i >= 0; i--) for (j = p2->degree; j >= 0; j--) mul->coeff[i + j] += p1->coeff[i] * p2->coeff[j]; return mul; } TPolynom* minus_polynom(TPolynom* p1, TPolynom* p2) { TPolynom* res; TPolynom* tmp; int i, tmp_dgr = 0; int M = ((p1->degree) > (p2->degree)) ? (p1->degree) : (p2->degree); allocate_polynom(&tmp, M); for (i = M; i >= 0; i--) tmp->coeff[i] = 0; for (i = p1->degree; i >= 0; i--) tmp->coeff[i] = p1->coeff[i]; for (i = p2->degree; i >= 0; i--) tmp->coeff[i] -= p2->coeff[i]; res = allocate_polynom_copy(&res, &tmp); return res; } TPolynom* diff_polynom(TPolynom* p) { TPolynom* res; int i; if (p->degree == 0) { allocate_polynom(&res, p->degree); res->coeff[0] = 0; } else { allocate_polynom(&res, p->degree - 1); for (i = p->degree - 1; i >= 0; i--) { res->coeff[i] = p->coeff[i + 1] * (i + 1); } } return res; } float value_polynome(TPolynom* p, float _x) { int i; float res = 0.0f, x = 1.0f; for (i = 0; i <= p->degree; i++) { res += p->coeff[i] * x; x *= _x; } return res; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<time.h> #include<locale.h> #define N 5 void main() { int size, comp[N], buff, num, prov, user[N], j = 0; int count = 0; int bulls = 0, cows = 0; setlocale(LC_ALL, "rus"); srand((unsigned int)time(NULL)); do { printf("введите количество цифр в числе от 2 до 5 :");//ввод количества разрядов числа контроль ввода scanf_s("%d", &size); } while ((size < 2) || (size > 5)); //генерация числа int digits = 0, equal; comp[0] = 1 + rand() % 9; digits++; while (digits < size) { buff = rand() % 10; equal = digits; for (int i = 0; i < digits; i++) if (buff != comp[i]) equal--; if (equal == 0) { comp[digits] = buff; digits++; } // digits++; } for (int i = 0; i < size; i++) printf("%d", comp[i]); printf("\n"); //пользователь угадывает число do { bulls = cows = j = 0; do { count = 0; printf("введите ваше число :"); // bulls = 0, cows = 0; scanf_s("%d", &num); prov = num; for (int i = size - 1; i >= 0; --i) { user[i] = num % 10; num /= 10; } // for (int i = 0; i < size; i++) { // printf("user[%d]=%d\n", i, user[i]); // } do { prov /= 10; j++; } while (prov != 0); for (int i = 0; i < size; i++) { for (int l = i + 1; l < size; l++) { if (user[i] == user[l]) { count++; break; } } } if (count != 0) printf("неправильно введеные данные\n"); } while ((count != 0)); // printf("j=%d, size=%d\n", j, size); if (j == size) { for (int i = 0; i < size; i++) { if (user[i] == comp[i]) bulls++; else { for (int l = 0; l < size; l++) { if (user[i] == comp[l]) cows++; } } } printf("bulls=%d, cows=%d\n", bulls, cows); } else printf("неверно введена длина числа\n"); } while (bulls != size); printf("!!! You win !!!"); }<file_sep>#include <stdio.h> int main() { float h = 0, w = 0, d = 0, k, dsp = 650, dvp = 800, wood = 550, m1, m2, m3, m4, m5, m; int i = 0; do { printf("Vvedite visoty shkafa v sm"); scanf("%f", &h); printf("Vvedite shiriny shkafa v sm"); scanf("%f", &w); printf("Vvedite glybiny shkafa v sm"); scanf("%f", &d); } while ((h < 180 && h > 220) && (w < 80 && w > 120) && (d < 50 && d > 90)); printf("Dannye v poryadke "); k = h - 3; h *= 0.01; w *= 0.01; d *= 0.01; m1 = h * w * 0.005 * dvp; m2 = w * d * 0.015 * 2 * dsp; m3 = (w - 0.03) * d * 0.015 * 2 * dsp; m4 = h * w * 0.01 * wood; while (k >= 40) { k -= 40; i++; } m5 = d * (w - 0.03) * 0.015 * i * dsp; m = m1 + m2 + m3 + m4 + m5; printf("Massa shkafa= %f kg", m); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #define TOTAL_N 12 char* names[TOTAL_N] = { "Milk 1L", "Bread", "Butter", "Chokolate", "Cheese", "Ice-cream", "Chicken 800g", "Beef 1kg", "Crisps", "Juice 1L", "Sugar 1kg", "Salt 1kg" }; int prices[TOTAL_N] = { 86, 45, 110, 114, 120, 65, 220, 300, 82, 99, 50, 45 }; int discounts[TOTAL_N] = { 5, 3, 20, 25, 0, 5, 10, 5, 5, 5, 0, 5 }; char barcodes[TOTAL_N][5] = { "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100" }; int check_exists_bar(char curr[]) { int i, result = -1, n = TOTAL_N; for (i = 0; i < n; i++) { if (strcmp(curr, barcodes[i]) == 0) { result = i; break; } } return result; } void print_cheque(int count[], double curr_price_whoutDisc, double t_curr_price) { int i, n = TOTAL_N; double economy = curr_price_whoutDisc - t_curr_price, perc_economy = (economy / curr_price_whoutDisc) * 100; printf("------------------------------------------------------------------------------\n"); printf("------------------------------------------------------------------------------\n\n"); for (i = 0; i < n; i++) { if (count[i] > 0) { double price_disc = prices[i] * (1 - (double)discounts[i] / 100.0); double total_pr = price_disc * count[i]; printf("Product: %s || Price with discount: %.2lf || Count: %d || Total price is %.2lf\n\n", names[i], price_disc, count[i], total_pr); } } printf("------------------------------------------------------------------------------\n"); printf("\nTotal cost without discount: %.2lf , BUT in general you have saved %.2lf rubles (i.e. %.2lf percent)\n", curr_price_whoutDisc, economy, perc_economy); printf("To be paid: %.2lf reubles\n", t_curr_price); } // calculates the count of each product and the total price void product_processing(int id, int count[], double* cost_without, double* total_cost) { double price_disc = prices[id] * (1 - (double)discounts[id] / 100.0); count[id]++; *(cost_without) += prices[id]; *(total_cost) += price_disc; } void print_prod_info(int bar) { double price_disc = prices[bar] * (1 - (double)discounts[bar] / 100.0); printf("Product: %s || Price per piece: %d rubles || Discount: %d%% || price with discount: %.2lf rubles\n\n", names[bar], prices[bar], discounts[bar], price_disc); } int get_and_check_barcode() { char curr_bar[5], clean, count_of_ch = 0, ind_prod = -1; int i, n = TOTAL_N, len; printf("Enter barcode or 'C'\n"); gets(curr_bar); len = strlen(curr_bar); // User wants to get cheque if (strcmp(curr_bar, "C") == 0) { return -2; } // check the barcode by 3 parameters: for (i = 0; i < len; i++) { // check for invalid characters if (!((curr_bar[i] == '0') || (curr_bar[i] == '1'))) { printf("The barcodes in our supermarket consist only of '0' and '1'\n\n"); return -1; } } ind_prod = check_exists_bar(curr_bar); // -1 if such a barcode doesn't exist if (ind_prod == -1) { printf("We haven't a product with such barcode!!! Try again\n\n"); return -1; } return ind_prod; } int main() { int count[12] = { 0 }, res_id; double curr_price_whoutDisc = 0, t_curr_price = 0; printf("Welcome to our supermarket!\nThere is a self-service ticket office\nEnter a barcode of each product, or enter 'C' and 2 'ENTER' to get cheque)\n\n"); while (1) { res_id = get_and_check_barcode(); // returns: -1, if sth goes wrong; index of product, if It's OK prod; -2, if CHECK if (res_id != -1 && res_id != -2) { print_prod_info(res_id); product_processing(res_id, count, &curr_price_whoutDisc, &t_curr_price); } if (res_id == -2) { print_cheque(count, curr_price_whoutDisc, t_curr_price); break; } } return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include "cars.h" #include <stdlib.h> // dynamic reading for str char* read_string(FILE* stream) { int buffer_size = 16; int buffer_size_divizer = 1; int offset = 0; int additional_length; char* buffer = (char*)malloc(buffer_size); if (buffer == NULL) { return NULL; } buffer[0] = '\0'; // read string while not face with '\n' while (1) { // read string to buffer with current offset if (fgets(buffer + offset, buffer_size / buffer_size_divizer, stream) == NULL) { free(buffer); // free allocated memory return NULL; } else { additional_length = strlen(buffer + offset); if (buffer[offset + additional_length - 1] != '\n') { // increase buffer_size by 2 times buffer_size *= 2; // realloc new memory buffer = (char*)realloc(buffer, buffer_size); // update offset to number of read elements offset += additional_length; buffer_size_divizer = 2; } else { buffer[offset + additional_length - 1] = '\0'; break; } } } return buffer; } char* getPath() { char* file_path; while (1) { printf("Enter the path to file : "); file_path = read_string(stdin); if (file_path != NULL) break; } return file_path; } Car ReadCarEntity(FILE* file) { char* car_brand = read_string(file); char* car_color = read_string(file); char* car_serial_number = (read_string(file)); char* car_registration_number = (read_string(file)); int car_count_door = atoi(read_string(file)); int car_year = atoi(read_string(file)); int car_price = atoi(read_string(file)); Car new_car = { car_brand, car_color, car_serial_number, car_registration_number, car_count_door, car_year, car_price }; return new_car; } Car* ReadCarFile(char* file_path, int* number_of_cars) { FILE* file = fopen(file_path, "r"); if (file == NULL) { printf("\nRead file error.\n"); } Car* cars = (Car*)malloc(sizeof(Car)); *number_of_cars = 1; // we assume that the file contains information about at least one car while (1) { Car current_car = ReadCarEntity(file); cars[*number_of_cars - 1] = current_car; if (read_string(file) == NULL) { break; } else { cars = (Car*)realloc(cars, (*number_of_cars + 1) * sizeof(Car)); *number_of_cars += 1; } } fclose(file); return cars; } Car FindOldestCar(Car* cars, int count_of_cars) { Car oldest_car = cars[0]; for (int i = 1; i < count_of_cars; ++i) { if (cars[i].year < oldest_car.year) { oldest_car = cars[i]; } } return oldest_car; } void PrintCar(Car car) { printf("Brand: %s\n", car.brand); printf("Color: %s\n", car.color); printf("Serial number: %s\n", car.serial_number); printf("Registration number: %s\n", car.registration_number); printf("Numbers of doors: %d\n", car.count_door); printf("Year of car manufacture: %d\n", car.year); printf("Price: %d\n\n", car.price); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> char barcodes[10][5] = { "1001","1002","1003","1004","1005","1006","1007","1008","1009","1010" }; char products[10][16] = { "eggs","milk", "meat","tea","cheese","bread","pen","bottle of water", "crisps","honey" }; double prices[10] = { 30, 15, 200, 20, 60, 10, 5, 25, 40, 95 }; double discounts[10] = { 0.05, 0.15, 0.3, 0.25, 0.02, 0.02, 0.04, 0.1, 0.12, 0.25 }; int basket[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int findProductIndex(char* barcode) { for (int i = 0; i < 10; i++) { if (strcmp(barcodes[i], barcode) == 0) { return i; } } return -1; } void scanProducts() { char barcode[5]; while (1) { printf("Scan barcode (P - print the check): "); scanf("%4s", barcode); if (strcmp(barcode, "P") == 0 || strcmp(barcode, "p") == 0) { break; } int productIndex = findProductIndex(barcode); if (productIndex == -1) { printf("Product with barcode %s not found\n", barcode); continue; } printf("Product: %s\n", products[productIndex]); basket[productIndex] = basket[productIndex] + 1; } } void printCheck() { double total = 0; double totalPrice = 0; double totalDiscount = 0; for (int productIndex = 0; productIndex < 10; productIndex++) { int numberOfProducts = basket[productIndex]; if (numberOfProducts == 0) { continue; } double price = prices[productIndex]; double discount = discounts[productIndex] * price; double priceWithDiscount = numberOfProducts * (price - discount); printf("Product: %s Price: %.2f Discount: %.2f Count: %i Result: %.2f\n", products[productIndex], price, discount, numberOfProducts, priceWithDiscount); totalPrice = totalPrice + numberOfProducts * price; totalDiscount = totalDiscount + numberOfProducts * discount; total = total + priceWithDiscount; } printf("Price: %.2f Discount: %.2f Total: %.2f\n", totalPrice, totalDiscount, total); } int main() { scanProducts(); printCheck(); } <file_sep>#ifndef FILM_H #define FILM_H #include <string> #include <fstream> #include <vector> class Producer { private: std::string Name; std::string Surname; public: Producer(); Producer(const std::string& name, const std::string& surname); friend std::istream& operator>>(std::istream& input_stream, Producer& p); friend std::ostream& operator<<(std::ostream& output_stream, const Producer& p); bool operator==(const Producer& p) const; const Producer& operator= (const Producer& p); }; class Film { private: std::string film_name; Producer creator; std::string country; int year; int budget; int fees; public: Film(const std::string& film_name, const Producer& creator, const std::string& country, int year, int budget, int fees); friend std::istream& operator>>(std::istream& input_stream, Film& p); friend std::ostream& operator<<(std::ostream& output_stream, const Film& p); Producer getCreator() const; }; std::string getInput(const std::string& message); Producer getProducerFromFile(std::ifstream& file); Producer getProducerFromString(std::string& producer_str); Film ReadFilmEntity(std::ifstream& file); std::vector<Film> ReadFileWithFilms(const std::string& file_path); std::vector<Film> getFilmsByProducer(const std::vector<Film>& all_films, const Producer& creator); #endif<file_sep>#ifndef _PRODUCT_H_ #define _PRODUCT_H_ #include <iostream> #include <fstream> using namespace std; class Product { private: string code; string name; double cost; public: //constructors Product(); Product(const string& ncode, const string& nname, const double& ncost); Product(const Product& new_product); //overloaded operations friend ifstream& operator>>(ifstream& buf, Product& Date); friend istream& operator>>(istream& buf, Product& Date); friend ostream& operator<<(ostream& buf, const Product& Date); const Product& operator=(const Product& new_product); bool operator==(const string& str) const; bool operator==(const Product& prod) const; //getters string get_name() const; string get_code() const; double get_cost() const; }; #endif // !_PRODUCTH_ <file_sep>#include <iostream> #include "Prototypes.h" using namespace std; int main() { const string path = "C://TouristAgences.txt"; TAgencyBook Object(path); TAgencyBook europeCountries = Object.Get_Europe_Countries(); cout << europeCountries; return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { double h, w, d, back_wall, side_wall, upper_n_lower_wall, shelves, doors, q, k = 0, M; printf("Enter cabinet height in cm "); scanf("%lf", &h); if ((h < 180) || (h > 220)) { printf("Cabinet height value out of range"); return 1; } printf("Enter cabinet width in cm "); scanf("%lf", &w); if ((w < 80) || (w > 120)) { printf("Cabinet width is out of range "); return 1; } printf("Enter cabinet depth in m "); scanf("%lf", &d); if ((d < 50) || (d > 90)) { printf("Cabinet depth value out of range"); return 1; } q = h - 2; //k=(int)(h/40.); while (q > 40) { q -= 40; k++; } back_wall = h * w * 0.005 * 800; side_wall = (h - 3) * d * 0.015 * 650 * 2; upper_n_lower_wall = w * d * 0.015 * 650 * 2; shelves = d * (w - 3) * 0.015 * 650 * k; doors = h * w * 0.01 * 550; M = back_wall + side_wall + upper_n_lower_wall + shelves + doors; printf("The weight of the cabinet is: %.3lf kg", M / 10000); return 0; }<file_sep>#include<stdio.h> #include<math.h> void main() { float x1, x2, y1, y2, r1, r2, d; printf("Enter first circle characteristics: "); scanf_s("%f %f %f", &x1, &y1, &r1); printf("Enter second circle characteristics: "); scanf_s("%f %f %f", &x2, &y2, &r2); d = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if (d == r1 + r2){ printf("Circles touch externally"); return 0; } if (d > r1 + r2) { printf("Circles don't have common points"); return 0; } if ((d + r1 == r2) || (d + r2 == r1)) { printf("Circle is inside circle with a touch"); return 0; } if (abs(x1-x2) < r1 || abs(x1-x2) < r2) { printf("One circle inside another"); return 0; } if ((r1 == r2) && (y1 == y2) && (r1 == r2)) { printf("Circles are equal"); return 0; } printf("Circles have two points in common"); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include "matrix.h" #include <stdlib.h> void allocate_matrix(TMatrix** matrix, int n) { (*matrix) = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n; (*matrix)->x = (float*)malloc(sizeof(float) * n * n); } void fill_matrix(TMatrix* matrix) { for (int i = 0; i < matrix->n; i++) { for (int j = 0; j < matrix->n; j++) { scanf("%f", &(matrix->x[i * matrix->n + j])); } printf("\n"); } } void print_matrix(TMatrix* matrix) { int i = 0; for (; i < matrix->n; i++) { int j = 0; for (; j < matrix->n; j++) { printf("%.3f ", matrix->x[i * matrix->n + j]); } printf("\n"); } printf("\n"); } void free_matrix(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; int i = 0; if (matrix1->n != matrix2->n) { printf("ERROR: Matrix should have the same lenght.\n"); return NULL; } allocate_matrix(&res, matrix1->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix1->x[i] + matrix2->x[i]; } return res; } TMatrix* add_const(TMatrix* matrix, float c) { TMatrix* res; allocate_matrix(&res, matrix->n); for (int i = 0; i < res->n * res->n; i++) { res->x[i] = matrix->x[i] + c; } return res; } TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; allocate_matrix(&res, matrix1->n); for (int i = 0; i < matrix1->n; i++) { for (int j = 0; j < matrix1->n; j++) { res->x[i * matrix1->n + j] = 0; for (int k = 0; k < matrix1->n; k++) { res->x[i * matrix1->n + j] += matrix1->x[i * matrix1->n + k] * matrix2->x[k * matrix2->n + j]; } } } return res; } TMatrix* multi_const(TMatrix* matrix, float c) { TMatrix* res; int i = 0; allocate_matrix(&res, matrix->n); for (; i < res->n * res->n; i++) { res->x[i] = matrix->x[i] * c; } return res; }<file_sep>#ifndef CONTAINER_H #define CONTAINER_H #include <iostream> using namespace std; template <typename T> class TContainer { private: T* elements; int max_size; int size; int step; int current_index; void realloc(); public: TContainer(); TContainer(int max_size, int step); TContainer(const TContainer<T>& container); ~TContainer(); int getSize() const; T& operator [] (int index); const T& operator [] (int index) const; void insert(const T& element); void insertBefore(const T& element); void insertAfter(const T& element); int find(const T& element) const; void remove(const T& element); void remove(int index); void reset(); friend std::ostream& operator<<(std::ostream& out, const TContainer<T>& c) { for (int i = 0; i < c.size; i++) { out << c.elements[i] << std::endl; } return out; } T& next(); T& prev(); T& current(); bool IsEnded() const; const TContainer<T>& operator=(const TContainer<T>& other); }; template <typename T> int TContainer<T>::getSize() const { return size; } template <typename T> TContainer<T>::TContainer() { elements = nullptr; max_size = 0; size = 0; current_index = -1; step = 5; } template <typename T> TContainer<T>::TContainer(int max_size, int step) { size = 0; this->step = step; current_index = -1; this->max_size = max_size; elements = new T[max_size]; } template <typename T> TContainer<T>::TContainer(const TContainer<T>& container) { size = container.size; current_index = container.current_index; max_size = container.max_size; elements = new T[max_size]; for (int i = 0; i < size; i++) { elements[i] = container.elements[i]; } } template <typename T> TContainer<T>::~TContainer() { if (elements != nullptr) { delete[] elements; } } template <typename T> const T& TContainer<T>:: operator [] (int index) const { if((index >= size) || (index < 0)) throw exception("Index out of range"); return elements[index]; } template <typename T> T& TContainer<T>::operator[](int index) { if ((index >= size) || (index < 0)) throw exception("Index out of range"); current_index = index; return elements[index]; } template <typename T> void TContainer<T>::realloc() { max_size += step; T* tmp = new T[max_size]; for (int i = 0; i < size; i++) { tmp[i] = elements[i]; } delete[] elements; elements = tmp; } template <typename T> void TContainer<T>::insert(const T& element) { if (max_size == size) realloc(); elements[size] = element; current_index = size; size++; } template <typename T> void TContainer<T>::insertBefore(const T& element) { if (size == max_size) { realloc(); } T* tmp = new T[max_size]; int i; for (i = 0; i <= current_index; i++) { tmp[i] = elements[i]; } tmp[i] = element; for (; i < size; i++) { tmp[i + 1] = elements[i]; } delete[] elements; elements = tmp; current_index++; size++; } template <typename T> void TContainer<T>::insertAfter(const T& element) { if (size == max_size) { realloc(); } T* tmp = new T[max_size]; int i; for (i = 0; i < current_index; i++) { tmp[i] = elements[i]; } tmp[i] = element; for (; i < size; i++) { tmp[i + 1] = elements[i]; } delete[] elements; elements = tmp; size++; } template <typename T> int TContainer<T>::find(const T& element) const { for (int i = 0; i < size; i++) { if (elements[i] == element) { return i; } } return -1; } template <typename T> void TContainer<T>::remove(const T& element) { int i; for ( i = 0; i < size; i++) { if (elements[i] == element) break; } for (i; i < size - 1; i++) { elements[i] = elements[i + 1]; } size--; } template <typename T> void TContainer<T>::remove(int index) { if ((index < 0) || (index > size)) return; for (int i=index; i < size - 1; i++) { elements[i] = elements[i + 1]; } size--; } template <typename T> void TContainer<T>::reset() { current_index = 0; } template <typename T> T& TContainer<T>::next() { if (current_index + 1 == size) throw exception("Index out of range"); current_index++; return elements[current_index]; } template <typename T> T& TContainer<T>::prev() { if (current_index - 1 <= 0) throw exception("Index out of range"); current_index--; return elements[current_index]; } template <typename T> T& TContainer<T>::current() { if (current_index == -1) throw std::exception("Conteiner is Empty! Isert some element in it"); return elements[current_index]; } template <typename T> bool TContainer<T>::IsEnded() const { return current_index == size - 1; } template <typename T> const TContainer<T>& TContainer<T>::operator=(const TContainer<T>& container) { if (this != &container) { delete[] elements; current_index = container.current_index; size = container.size; max_size = container.max_size; step = container.step; elements = new T[container.max_size]; for (int i = 0; i < size; i++) { elements[i] = container.elements[i]; } } return *this; } #endif<file_sep>#ifndef _PERSON_H #define _PERSON_H #include <string> using namespace std; enum gender { male, female }; struct address { int postal_code; string Country; string Region; string City; string Area; string Street; int House; int Apart; }; struct date { int day; int mounth; int year; }; struct person { string Surname; string Name; string Middle_name; gender Gender; string Nation; date date; float Height; float Weight; long long phone_number; address address; friend ostream& operator<<(ostream& out, const person& p); }; struct persons_list { person* persons; int count; persons_list(const string& path); ~persons_list(); int person_count(const string& path); void surname_sort(); friend ostream& operator<<(ostream& out, const persons_list& pl); }; string getPath(); void menu(const persons_list& ps); #endif // !_PERSON_H #pragma once <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include "stars.h" void Callocate(Constellation** cns, int c) { (*cns) = (Constellation*)malloc(sizeof(Constellation) * c); } void Sallocate(Star** st, int c) { (*st) = (Star*)malloc(sizeof(Star) * c); } void cfree(Constellation** cns) { free((*cns)->stars); free(*cns); } void read_data(Constellation** cns, int* count) { FILE* fp; char* path = (char*)malloc(sizeof(char) * 260); int cns_count, stars_count; printf("\nEnter the path: "); scanf("%s", path); fp = fopen(path, "r"); fscanf(fp, "%d", &cns_count); (*count) = cns_count; Callocate(cns, cns_count); for (int i = 0; i < cns_count; i++) { fscanf(fp, "%s %d", (*cns)[i].name, &stars_count); (*cns)[i].count = stars_count; Sallocate(&(*cns)[i].stars, stars_count); for (int j = 0; j < stars_count; j++) { fscanf(fp, "%s %f %f %f %f %f", (*cns)[i].stars[j].name, &(*cns)[i].stars[j].dist, &(*cns)[i].stars[j].magnitude, &(*cns)[i].stars[j].deg, &(*cns)[i].stars[j].min, &(*cns)[i].stars[j].sec); } } free(path); fclose(fp); } void print_data(Constellation* cns, int n) { printf("\n%s:\n", cns[n].name); for (int j = 0; j < cns[n].count; j++) { printf(" % s %-0.3f %0.3f %0.3f° %0.3f\' %0.3f\"\n", cns[n].stars[j].name, cns[n].stars[j].dist, cns[n].stars[j].magnitude, cns[n].stars[j].deg, cns[n].stars[j].min, cns[n].stars[j].sec); } printf("\n"); } void cnst_table(Constellation* cns, int count) { printf("\n"); for (int i = 0; i < count / 2; i++) { printf("%d\. %s \t\t %d\. %s\n", i + 1, cns[i].name, i + 6, cns[i + 5].name); } printf("\nOutput format:\n\n name distance magnitude coordinates(deg, min, sec)\n\n"); } void choice(Constellation* cns, int count) { char con[100]; printf("Choose a constellation\n"); do { int flag = 0; printf(">> "); scanf("%s", con); if (strcmp(con, "stop") == 0) flag = 1; for (int i = 0; i < count && flag == 0; i++) { if (strcmp(con, cns[i].name) == 0) { print_data(cns, i); flag = 1; } } if (!flag) printf("Not found. Please, choose constellation from table\n"); } while (strcmp(con, "stop") != 0); cfree(&cns); }<file_sep>#ifndef _CARS_H #define _CARS_H typedef struct { char* brand; char* color; char* serial_number; char* registration_number; int count_door; int year; int price; } Car; char* read_string(FILE* stream); char* getPath(); Car ReadCarEntity(FILE* file); Car* ReadCarFile(char* file_path, int* number_of_cars); Car FindOldestCar(Car* cars, int count_of_cars); void PrintCar(Car car); #endif _CARS_H<file_sep>#include <iostream> #include <fstream> #include <string.h> #include <string> #include "triangle.h" #include <math.h> using namespace std; Triangle::Triangle() { } Triangle::Triangle(Coord* vertices_) { vertices[0] = vertices_[0]; vertices[1] = vertices_[1]; vertices[2] = vertices_[2]; } ostream& operator<<(ostream &output_stream, const Triangle &triangles) { output_stream << "Coordinates: (" << triangles.vertices[0].x << ", " << triangles.vertices[0].y << "), (" << triangles.vertices[1].x << ", " << triangles.vertices[1].y << "), (" << triangles.vertices[2].x << ", " << triangles.vertices[2].y << ") " << endl; return output_stream; } int read(Triangle*& triangles, const string& f) { fstream file; file.open(f); if (!file.is_open()) throw "File open error"; int n; file >> n; triangles = new Triangle[n]; for (int i = 0; i < n; i++) { float x1, x2, x3, y1, y2, y3; file >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; Coord vertices[3]; vertices[0] = { x1, y1 }; vertices[1] = { x2, y2 }; vertices[2] = { x3, y3 }; triangles[i] = Triangle(vertices); } file.close(); return n; } void Triangle::CountSquare() const { float s = (abs(((vertices[1].x - vertices[0].x) * (vertices[2].y - vertices[0].y)) - ((vertices[2].x - vertices[0].x) * (vertices[1].y - vertices[0].y)))) / 2; cout << "S = " << s << endl; } float* Triangle::Sides() const { float sides[3]; sides[0] = sqrt((vertices[1].x - vertices[0].x) * (vertices[1].x - vertices[0].x) + (vertices[1].y - vertices[0].y) * (vertices[1].y - vertices[0].y)); sides[1] = sqrt((vertices[2].x - vertices[0].x) * (vertices[2].x - vertices[0].x) + (vertices[2].y - vertices[0].y) * (vertices[2].y - vertices[0].y)); sides[2] = sqrt((vertices[2].x - vertices[1].x) * (vertices[2].x - vertices[1].x) + (vertices[2].y - vertices[1].y) * (vertices[2].y - vertices[1].y)); return sides; } void Triangle::CountPerimeter() const { float* sides = Sides(); float p = sides[0] + sides[1] + sides[2]; cout << "P = " << p << endl; } void Triangle::Height() const { float s = (abs(((vertices[1].x - vertices[0].x) * (vertices[2].y - vertices[0].y)) - ((vertices[2].x - vertices[0].x) * (vertices[1].y - vertices[0].y)))) / 2; float heights[3]; float* sides = Sides(); heights[0] = 2 * s / sides[0]; heights[1] = 2 * s / sides[1]; heights[2] = 2 * s / sides[2]; cout << "H1 = " << heights[0] << "; " << "H2 = " << heights[1] << "; " << "H3 = " << heights[2] << "; " << endl; } int Triangle::TriangleType() const { float sides[3]; sides[0] = sqrt((vertices[1].x - vertices[0].x) * (vertices[1].x - vertices[0].x) + (vertices[1].y - vertices[0].y) * (vertices[1].y - vertices[0].y)); sides[1] = sqrt((vertices[2].x - vertices[0].x) * (vertices[2].x - vertices[0].x) + (vertices[2].y - vertices[0].y) * (vertices[2].y - vertices[0].y)); sides[2] = sqrt((vertices[2].x - vertices[1].x) * (vertices[2].x - vertices[1].x) + (vertices[2].y - vertices[1].y) * (vertices[2].y - vertices[1].y)); float max; max = sides[0]; for (int i = 1; i < 3; i++) { if (sides[i] > max) { max = sides[i]; } } float min; min = sides[0]; for (int i = 1; i < 3; i++) { if (sides[i] < min) { min = sides[i]; } } float sr = sides[0] + sides[1] + sides[2] - max - min; float eps = 0.0001; types t; if (abs(max * max - (min * min + sr * sr)) < eps) t = types::straight; else if (max * max < (min * min + sr * sr)) t = types::sharp; else if (max * max > (min * min + sr * sr)) t = types::blunt; return t; }<file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" int main() { int i, j; TMatrix* m1, * m2, * res; allocate_matrix(&m1, 2); allocate_matrix(&m2, 2); fill_matrix(m1); fill_matrix(m2); res = addition_matrix(m1, m2); print_matrix(res); free_matrix(&res); res = addition_const(m1, 5.2f); print_matrix(res); free_matrix(&res); res = multi_const(m1, 3.4f); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#include <stdio.h> #include <math.h> int main() { float x1, x2, y1, y2, r1, r2, s, br, smr; do { scanf("%f %f %f", &x1, &y1, &r1); scanf("%f %f %f", &x2, &y2, &r2); if ((r1 < 0) || (r2 < 0)) { printf("something went wrong"); return 1; } s = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); br = r1; if (r2 > br) { br = r2; smr = r1; } else smr = r2; if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("circumferences are the same"); return 0; } if (r1 + r2 < s) { printf("circumferences doesn't intersect"); } if (r1 + r2 == s) { printf("circumferences touch"); } if ((r1 + r2 > s) && (s >= br)) { printf("circumferences intersect"); } if ((s < br) && (smr < (br - s))) { printf("one circumference is inside another"); } if ((s < br) && (smr == (br - s))) { printf("one circumference is inside another and they touch"); } } while (2); return 0; }<file_sep>#ifndef _CONTAINER_H #define _CONTAINER_H #include <iostream> #include <string> using namespace std; template <typename TELEM> class TContainer { private: TELEM* elem; // Массив хранимых элементов int size; // Размер массива int count; // к-во реально хранимых элементов int sizestep; public: TContainer(int _size = 5, int _sizestep = 10); TContainer(const TContainer& _cnt); ~TContainer(); int Count() const; int Size() const; int Sizestep() const; void Add(const TELEM& _elm); void Del(int index); TELEM& operator[](int index) const; bool operator!=(const TContainer& _cnt) const; bool operator==(const TContainer& _cnt) const; // присваивание контейнеров const TContainer& operator=(const TContainer& _cnt); // объединение контейнеров TContainer operator+(const TContainer& _cnt); // пересечение контейнеров TContainer operator*(const TContainer& _cnt); // разность контейнеров TContainer operator-(const TContainer& _cnt); friend ostream& operator<<(ostream& out, const TContainer<TELEM>& _elm) { for (int i = 0; i < _elm.Count(); i++) out << _elm[i] << endl; return out; } void Clear(); // Выделяет новую память, которую указал пользователь, и меняет размер шага. БЕЗ КОПИРОВАНИЯ ЭЛЕМЕНТОВ void ChangeMemorry(int _size, int _sizestep = 10); // Выделяет новую память без свободных мест для новых элементов контейнера void Compress(); // Найти индекс элемента. -1 - элемент не найден. int _find(const TELEM& _elm) const; // Найти индекс элемента protected: // Изменить размер массива void resize(int dsize = 0); }; // ========== ОБЪЯВЛЕНИЕ ========== // template <typename TELEM> TContainer<TELEM>::TContainer(int _size, int _sizestep) { if (_size <= 0) { string exp = "cntWRONGMEMCOUNT"; throw std::out_of_range(exp); } size = _size; sizestep = _sizestep; count = 0; elem = new TELEM[size]; } template <typename TELEM> TContainer<TELEM>::TContainer(const TContainer& _cnt) { size = _cnt.size; count = _cnt.count; elem = new TELEM[size]; } template <typename TELEM> TContainer<TELEM>::~TContainer() { if (size > 0) { delete[] elem; elem = 0; count = 0; size = 0; } } template <typename TELEM> int TContainer<TELEM>::Count() const { return count; } template <typename TELEM> int TContainer<TELEM>::Size() const { return size; } template <typename TELEM> int TContainer<TELEM>::Sizestep() const { return sizestep; } template <typename TELEM> void TContainer<TELEM>::Add(const TELEM& _elm) { if (_find(_elm) == -1) { if (size == count) resize(); elem[count++] = _elm; } } template <typename TELEM> void TContainer<TELEM>::Del(int index) { if (index > -1 && index < count) for (int i = index; i < count - 1; i++) elem[i] = elem[i + 1]; count--; } template <typename TELEM> TELEM& TContainer<TELEM>::operator[](int index) const { if (index < 0 || index >= count) { string exp = "cntINDOUTOFRANGE"; throw std::out_of_range(exp); } return elem[index]; } template <typename TELEM> bool TContainer<TELEM>::operator!=(const TContainer& _cnt) const { if (this == &_cnt) return false; if (size == _cnt.size && count == _cnt.count && sizestep == _cnt.sizestep) for (int i = 0; i < count; i++) if (elem[i] == _cnt.elem[i]) return false; return true; } template <typename TELEM> bool TContainer<TELEM>::operator==(const TContainer& _cnt) const { if (this == &_cnt) return true; return !((*this) != _cnt); } // присваивание контейнеров template <typename TELEM> const TContainer<TELEM>& TContainer<TELEM>::operator=(const TContainer& _cnt) { if ((*this) != _cnt) { delete[] elem;; size = _cnt.size; count = _cnt.count; sizestep = _cnt.sizestep; elem = new TELEM[size]; for (int i = 0; i < count; i++) elem[i] = _cnt.elem[i]; } return *this; } // объединение контейнеров template <typename TELEM> TContainer<TELEM> TContainer<TELEM>::operator+(const TContainer& _cnt) { int i; TContainer<TELEM> tmp(count + _cnt.count + sizestep); for (i = 0; i < count; i++) tmp.elem[i] = elem[i]; tmp.count = count; for (i = 0; i < _cnt.count; i++) tmp.Add(_cnt.elem[i]); return tmp; } // пересечение контейнеров template <typename TELEM> TContainer<TELEM> TContainer<TELEM>::operator*(const TContainer& _cnt) { int i; int ss = count; if (ss < _cnt.count) ss = _cnt.count; TContainer<TELEM> tmp(ss + sizestep); tmp.count = 0; for (i = 0; i < count; i++) if (_cnt._find(elem[i]) != -1) tmp.elem[tmp.count++] = elem[i]; return tmp; } // разность контейнеров template <typename TELEM> TContainer<TELEM> TContainer<TELEM>::operator-(const TContainer& _cnt) { int i; TContainer<TELEM> tmp(count + sizestep); tmp.count = 0; for (i = 0; i < count; i++) if (_cnt._find(elem[i]) == -1) tmp.elem[tmp.count++] = elem[i]; return tmp; } template <typename TELEM> void TContainer<TELEM>::Clear() { while (count) { Del(count - 1); } } // Выделяет новую память, которую указал пользователь, и меняет размер шага. БЕЗ КОПИРОВАНИЯ ЭЛЕМЕНТОВ template <typename TELEM> void TContainer<TELEM>::ChangeMemorry(int _size, int _sizestep) { // (int _size, int _sizestep = 10) if (size > 0) { delete[] elem; size = _size; sizestep = _sizestep; count = 0; elem = new TELEM[size]; } } // Выделяет новую память без свободных мест для новых элементов контейнера template <typename TELEM> void TContainer<TELEM>::Compress() { int dsize = count - size; if (dsize) resize(dsize); } // Найти индекс элемента. -1 - элемент не найден. template <typename TELEM> int TContainer<TELEM>::_find(const TELEM& _elm) const { int nom = -1; int i = 0; while (i < count && nom == -1) if (elem[i] == _elm) nom = i; else i++; return nom; } template <typename TELEM> void TContainer<TELEM>::resize(int dsize) { // (int dsize = 0) if (dsize == 0) dsize = sizestep; size += dsize; TELEM* tmp = new TELEM[size]; for (int i = 0; i < count; i++) tmp[i] = elem[i]; delete[] elem; elem = tmp; } #endif // !_CONTAINER_H<file_sep>#include <iostream> #include <string> #include <sstream> #include <iomanip> #include "utility.h" using namespace std; string intToString(int num, int minLeng, char fill) { ostringstream oss; oss << setw(minLeng) << setfill(fill) << num; return oss.str(); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> int r(int a, int b) { int n; n = rand() % (b - a + 1) + a; return n; } void mode1() { int num, n, k = 1; num = r(1, 1000); //printf("%d\n", num); printf("Enter the expected number:\n"); scanf("%d", &n); while (n != num) { if (n > num) printf("The hidden number is LESS than the entered one\n"); else printf("The hidden number is GREATER than the entered one\n"); scanf("%d", &n); k++; } printf("Congratuletion! The hidden number is %d\n", num); printf("Number of attempts: %d\n", k); } void mode2() { int num, k = 0, n; int a = 1, b = 1000; printf("Enter the hidden number:\n"); scanf("%d", &num); if (num < 1 || num > 1000) { printf("The hidden number must be 1 <= num <= 1000\n"); mode2(); } else { n = r(a, b); //2 k++; printf("%d) %d\n", k, n); while (n != num) { if (n > num) b = n - 1; else a = n + 1; n = r(a, b); //2 k++; printf("%d) %d\n", k, n); } printf("The program found %d in %d attempts\n", n, k); } } void main() { int m; srand((unsigned int)time(NULL)); printf("Choose mode #1 or mode #2:\n"); scanf("%d", &m); switch (m) { case 1: { mode1(); break; } case 2: { mode2(); break; } default: { printf("There is no such mode here\n\n"); return main(); } } }<file_sep>#include <stdio.h> #include <string.h> #define N 10 char* codes[N] = { "1452", "6254", "3365", "4789", "9933", "1238", "8456", "3495", "0237", "5638" }; char* products[N] = { "Milk", "Chicken", "Tomato", "Potato", "Eggs", "Apples", "Onion", "Cheese", "Bread", "Water" }; float price[N] = { 62.00, 100.00, 50.00, 35.00, 80.00, 73.00, 27.00, 94.00, 15.00, 30.00 }; int discount[N] = { 10, 25, 15, 5, 0, 5, 10, 20, 0, 0, }; int Input(int* c, char* b[50]) { int num_basket = 0, i, j, k, flag; char code[5]; printf("Enter the product code or 'exit' to generate a receipt\n"); while (strcmp(code, "exit")) { scanf("%s", code, 5); flag = 0; if (strcmp(code, "exit")) { for (i = 0; i < N; i++) { if (strcmp(code, codes[i]) == 0) { flag = 1; printf("%s %.2f %d%%\n", products[i], price[i], discount[i]); b[num_basket] = codes[i]; printf("Enter the quantity: "); scanf("%d", &(c[num_basket])); num_basket++; for (j = 0; j < num_basket; j++) for (k = 0; k < num_basket; k++) if ((strcmp(b[j], b[k]) == 0) && (k != j)) { c[j] += c[k]; num_basket--; } } } if (flag == 0) printf("Product is not found\n"); } } return num_basket; } float Print(int* c, char* b[50], int n) { int i, j; int num_basket = 0; float price_disc, s = 0; printf("\nYour receipt\n"); for (i = 0; i < n; i++) { for (j = 0; j < N; j++) if (strcmp(b[i], codes[j]) == 0) { price_disc = (price[j] - (price[j] / 100) * discount[j]) * c[i]; printf("*%s\nprice - %.2f, discount - %d%%, discount price %.2f, count - %d\n", products[j], price[j], discount[j], price_disc, c[i]); s += price_disc; } } return s; } int main() { int counts[100] = { 0 }; char* basket[50]; int num; float sum; num = Input(counts, basket); sum = Print(counts, basket, num); printf("For payment:\n%.2f", sum); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> int bigger(max, k) //random number between k and max { time_t t; int n; srand((unsigned)time(&t)); n = (rand() % (max - k)) + k; return n; } int smaller(min, k) //random number between min and k { time_t t; int n; srand((unsigned)time(&t)); n = (rand() % (k - min)) + min; return n; } void A() //first game { time_t t; int a, n, i = 0; srand((unsigned)time(&t)); n = rand() % 1000; printf("debug: %d\n", n); //checking the machine generated number (just in case) printf("enter your first guess: "); do { i++; scanf("%d", &a); if ((a == n) && (a > 0) && (a < 1000)) { printf("That's it! Attemts count: %d", i); return 0; } else if ((a < n) && (a > 0) && (a < 1000)) { printf("bigger... "); } else if ((a > n) && (a > 0) && (a < 1000)) { printf("smaller... "); } } while (1); //this loop makes program not to break if strng is intodused instead of int } void B() //second game with randomly generated guesses { time_t t; char ch; int n = 0, a, i = 0, k = 0, min = 0, max = 1000; srand((unsigned)time(&t)); printf("enter one natural number to 1000 from 0: "); do { scanf("%d", &a); } while ((a > 1000) || (a < 0)); n = rand() % 1000; do { i++; printf("is it %d", n); printf("? "); do { scanf("%c", &ch); } while ((ch != 'y') && (ch != 'b') && (ch != 's')); if (ch == 'y') { printf("Woohoo! It's %d", n); printf("! Total attemts count: %d", i); return 0; } else if (ch == 'b') { min = n + 1; n = bigger(max, n); } else { max = n - 1; n = smaller(min, n); } } while (1); } void B1() //second game with an optimized algorithm (up to 10 moves (log2(1000))) { time_t t; char ch; int n = 0, a, i = 0, k = 0, min = 1, max = 1000; srand((unsigned)time(&t)); printf("enter one natural number to 1000 from 0: "); do { scanf("%d", &a); } while ((a > 1000) || (a < 0)); do { i++; n = (min + max) / 2; if (n == k) { n -= 1; } printf("is it %d", n); printf("? "); do { scanf("%c", &ch); } while ((ch != 'y') && (ch != 'b') && (ch != 's')); if (ch == 'b') { min = n; } else if (ch == 's') { max = n; } else { printf("gotcha! Total attemts count: %d", i); return 0; } } while (1); } int main() //choosing a game { char a, b; printf("choose game, A or B: "); do { scanf("%c", &a); } while ((a != 'A') && (a != 'B')); if (a == 'B') { printf("choose your regime: 1 is for random, 2 is for optimized "); do { scanf("%c", &b); } while ((b != '1') && (b != '2')); if (b == '1') { B(); } else { B1(); } } else { A(); } return 0; }<file_sep>#ifndef _Header_bankh_ #define _Header_bankh_ #define MAX_NAME 30 typedef struct { char* name; int period; float conditions; } Deposit; typedef struct { char* name; char* ownership; int count; Deposit* deposits; } BanksData; typedef struct { int id1; int id2; float profit; } pair; void input_path(char* path); int read(BanksData** data); void print_data(BanksData* data, int n); void freedata(BanksData** data, int n); void input_user_data(int* user_year, float* user_money); pair comparing(BanksData* data, int n, int user_year, int user_money); #endif <file_sep>#ifndef _Header_bankh_ #define _Header_bankh_ #define MAX_PATH 100 // Max path length #define MAX_NAME 20 // Max name of banks length using namespace std; struct triple { int id1; int id2; float profit; //default constuctor and destructor }; class Deposit { private: string name; int period; float conditions; public: //default contructor axnd destructor int get_period() const; float get_condition() const; string get_name() const; friend ifstream& operator>>(ifstream& buf, Deposit& data); friend ostream& operator<<(ostream& buf, const Deposit& data); }; class BanksData { private: string name; string ownership; int count; int user_year;//можно в public float user_money;//also vector<Deposit> deposits; pair<int, float> best_suggestion; public: //Constructor BanksData() { name = ""; ownership = ""; count = -1; user_money = -1; user_year = -1; best_suggestion.first = -1; best_suggestion.second = -1; deposits.resize(1); } //Destructor ~BanksData() { deposits.resize(0); } //overloading operations pair<int, float> best_deposit(int user_year, float user_money); bool operator>(BanksData sd) { if (best_suggestion.second > sd.best_suggestion.second) return true; return false; } bool operator<(BanksData sd) { if (best_suggestion.second < sd.best_suggestion.second) return true; return false; } friend ifstream& operator>>(ifstream& buf, BanksData& data); friend ostream& operator<<(ostream& buf, const BanksData& data); //input data static int read(BanksData*& data, int* n, const string& path); //Getters pair<int, float> get_best_suggestion() const; string get_name() const; string get_ownership() const; vector<Deposit> get_deposits() const; //Setter void set_best_suggestion(pair<int, float> new_suggesition); }; void input_path(string& path); //void print_data(BanksData* data, int n); void input_user_data(int* user_year, float* user_money); triple comparing(BanksData* data, int user_year, float user_money, int n); #endif<file_sep>#include <stdio.h> #include <locale.h> #include <stdlib.h> #include <time.h> int main() { int game,count=0,Computer_Number,number,left=0,right=1000,middle; char answer; do { printf("Select the game mode (1-You guess the number given by the computer; 2-The computer guesses the number given by you)\n"); scanf_s("%d", &game); if ((game != 1) && (game != 2)) { printf("You made a mistake with the mode selection, try again!\n"); } } while ((game != 1) && (game != 2)); if (game == 1) { srand((unsigned int)time(NULL)); Computer_Number = rand() % 1001; do { count++; do { printf("Try to guess the number\n"); scanf_s("%d", &number); if ((number > 1000) || (number < 0)) { printf("Enter a number from the range\n"); } } while ((number > 1000) || (number < 0)); if (number == Computer_Number) { printf("You guessed the number!\n"); } else if (Computer_Number < number) { printf("The number of the computer is smaller\n"); } else { printf("The number of the computer is bigger\n"); } }while (Computer_Number != number); } else if (game==2) { printf("Guess a number from 1 to 1000 and enter it, the program will try to guess it: \n"); do { scanf_s("%d", &number); if ((number > 1000) || (number < 1)) { printf("Incorrect number entered. Try again\n"); } } while ((number > 1000) || (number < 1)); printf("Rules:\n"); printf("You can use: '=' '>' '<' \n"); do { count++; middle = (left + right) / 2; printf("Is the number = %d\n", middle); do { scanf_s("%c", &answer); } while ((answer!= '=') && (answer != '>') && (answer != '<')); if (answer == '=') { printf("The computer guessed the number\n"); } else if (answer == '>') { left = middle; } else if (answer =='<') { right = middle; } } while (middle != number); } printf("Number of attempts=%d", count); return 0; }<file_sep>#ifndef _OUTLET_H #define _OUTLET_H #include <string> #include <vector> using namespace std; enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; struct Time { int hour; int minute; bool operator==(const Time& other) const; }; struct address { string street; int house_number; }; // структура для хранения рабочих дней магазина struct workingDays { vector<Day> days; vector<Time> opens; vector<Time> closes; }; class outlet {//класс, который хранит сведения о торговой точке public: outlet(string name, address address, int number, string specialization, workingDays wd); ~outlet(); workingDays* getWD(); private: string name; address address_; int phone_number; string specialization; workingDays working_days; friend ostream& operator<<(ostream& os, const outlet& outlet); }; class buyerGuide {//класс, который хранит все наши торговые точки public: buyerGuide(const string& filename); buyerGuide(const vector<outlet>& o); ~buyerGuide(); buyerGuide show_24_outlets(); friend ostream& operator<<(ostream& os, const buyerGuide& bg); private: vector<outlet> outlets; }; string start(); #endif // !_OUTLET_H<file_sep>#include <stdio.h> #include <stdlib.h> int main() { int a; printf("select game mode 1 or 2\n"); scanf_s("%d", &a); if (a == 1) { int num; int flag = 1; int counter = 0; int number_of_machine; srand(time(NULL)); number_of_machine = 1 + rand() % 999; while (flag == 1) { printf("enter a number\n"); scanf_s("%d", &num); if (num == number_of_machine) { printf("gg wp\n"); printf("%d\n", num); printf("number of attempts:\n"); printf("%d", counter); return 0; } if (num < number_of_machine) { printf("the number is bigger than what you wrote\n"); } if (num > number_of_machine) { printf("the number is less then what you wrote\n"); } counter++; } } else if (a == 2) { int start = 0, end = 1000; int count = 0; char ch; printf("write more(+) or less(-), if equal then(=)\n"); do { printf("pc thinks it is: %d\n", (start + end) / 2); while (ch = getchar() != '\n'); scanf_s("%c", &ch, 1); while (ch != '-' && ch != '+' && ch != '=') { while (ch = getchar() != '\n'); printf("invalid input\n"); scanf_s("%c", &ch, 1); } if (ch == '+') start = (start + end) / 2 + 1; else if (ch == '-') end = (start + end) / 2 - 1; else printf("gg wp! Number of attempts: %d", count); count++; } while (ch != '='); } else { printf("select game mode 1 or 2"); } return 0; }<file_sep>#pragma once #ifndef _TSERVICE_H #define _TSERVICE_H #include <string> typedef void вишнёвый_пирожок; using namespace std; struct TService// list of service { string country; string travel_conditions; string excursion_services; string host_service; string ticket_price; TService(void); TService(const TService& obj); }; #endif<file_sep>#ifndef _UTILITY_H #define _UTILITY_H #include <iostream> #include <string> using namespace std; string intToString(int num, int minLeng, char fill = '0'); #endif // !_UTILITY_H<file_sep>#define _CRT_SECURE_NO_WARNINGS #include "banki.h" int main() { //char* path = "C:\\Users\\abobi\\OneDrive\\Рабочий стол\\banki2.txt"; char* path = getfile();//C:\Users\abobi\banki2.txt int stringcount= strcount(path); bankstruct** banki = allocbanki(stringcount); workfile(banki, path, stringcount); int sumvkl = 0; int your_month = 0; char your_type[15]; data_input(&sumvkl, &your_month, &your_type); choosebest(sumvkl, your_month, banki,stringcount, &your_type); freebanki(banki, stringcount); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <time.h> #include <math.h> #define N 5 void main() { int number[N] = { 0 }; int arr[N] = { 0 }; int n, i, flag, j, r, p_num, cow, bull, check,p,flag1; printf("Enter the number of digits in the number from 2 to 5 "); srand(time(NULL)); do { scanf("%d", &n); if ((n > 5) || (n < 2)) { printf("Invalid number entered. Try again\n"); } } while ((n > 5) || (n < 2)); number[0] = 1 + rand() % (9); r = 0; flag = 1; for (i = 1; i < n; i++) { flag = 1; while (flag == 1) { r = rand() % 10; flag = 1; for (j = 0; j < i; j++) { if (number[j] == r) { flag = 0; break; } } if (flag == 1) { number[i] = r; break; } } } bull = 0; while (bull != n) { printf("Try to guess the number: "); do { scanf(" %d", &p_num); check = 0; p = p_num; flag1 = 1; while (p > 0) { if ((p % 10) == (p / 10 % 10)) { flag1 = 0; printf("Incorrect number entered. Try again: "); break; } p = p / 10; check++; } if ((flag1 == 1)&&(check != n)) { printf("Invalid number entered. Try again: "); } } while (check != n); i = n - 1; while (p_num > 0) { arr[i] = p_num % 10; p_num = p_num / 10; i--; } bull = 0; cow = 0; for (i = 0; i < n; i++) { if (number[i] == arr[i]) { bull++; } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (number[i] == arr[j]) { if (i != j) cow++; } } } printf("Number of bulls: %d. Number of cows: %d\n", bull, cow); } printf("Congratulations! You guessed the number!"); }<file_sep>#include <windows.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <time.h> #include <string.h> #include <vcruntime_string.h> #include <corecrt_wstring.h> #define N 100 #define mx_path 100 typedef unsigned long long ull; typedef long long ll; void insert_sort(ull a[],int *hlp, int n); void bubble_sort(ull a[], int *hlp, int n); void merge(ull a[], int *hlp, int l, int r, int m); void merge_sort(ull a[],int *hlp, int n); void dir(wchar_t** wnames, ull* sze, time_t* tme1,int *hlp, int n); void sorting(wchar_t** wnames, ull* sze, time_t* tme, time_t* tme1, int* hlp, int i); int indir(wchar_t** wnames, ull* sze, time_t* tme, time_t* tme1, int* hlp); time_t filetime_to_timet(const FILETIME ft); wchar_t* newpath(wchar_t* copypath, wchar_t* name); int main() { setlocale(LC_ALL, "rus"); int i = 0; time_t* tme1 = (time_t*)malloc(N * sizeof(time_t*)); int* hlp = (int*)malloc(N * sizeof(int*)); char* nme = (char*)malloc(N * sizeof(char*)); ull* sze = (ull*)malloc(N * sizeof(ull*)); ull* tme = (ull*)malloc(N * sizeof(ull*)); wchar_t** wnames = (wchar_t**)malloc(N * sizeof(wchar_t**)); for (int i = 0; i < N; i++) { hlp[i] = i; sze[i] = 0; tme[i] = 0; wnames[i] = (wchar_t*)malloc(N * sizeof(wchar_t)); wnames[i] = L"Empty"; } i = indir(wnames, sze, tme, tme1, hlp); if (i <= 2) { printf("I guess your directory is empty or u did input a wrong path. Try again :) "); return 1; } dir(wnames, sze, tme1, hlp,i); sorting(wnames, sze, tme, tme1, hlp, i); printf("\nIm sure i have max mark for the work. \n I did it for a long time and helped everyone \n Have a good day."); return 0; } void insert_sort(ull* arr, int* hlp, int n) { ull num = 0; int ti = -1; int j = 0; for (int i = 2; i < n; i++) { num = arr[i]; ti = hlp[i]; j = i - 1; while (j >= 0 && arr[j] > num) { arr[j + 1] = arr[j]; hlp[j + 1] = hlp[j]; j--; } arr[j + 1] = num; hlp[j + 1] = ti; } } void bubble_sort(ull arr[],int *hlp, int n) { ull temp = 0; int Htmp = 0; for (int write = 0; write < n; write++) { for (int sort = 0; sort < n - 1; sort++) { if (arr[sort] > arr[sort + 1]) { temp = arr[sort + 1]; arr[sort + 1] = arr[sort]; arr[sort] = temp; Htmp = hlp[sort + 1]; hlp[sort + 1] = hlp[sort]; hlp[sort] = Htmp; } } } } void merge(ull arr[], int* hlp, int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; ull* L = (ull*)malloc(n1 * sizeof(ull*)); ull* R = (ull*)malloc(n2 * sizeof(ull*)); int* HL = (int*)malloc(n1 * sizeof(int*)); int* HR = (int*)malloc(n2 * sizeof(int*)); for (i = 0; i < n1; i++) { L[i] = arr[l + i]; HL[i] = hlp[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1 + j]; HR[j] = hlp[m + 1 + j]; } i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; hlp[k] = HL[i]; i++; } else { arr[k] = R[j]; hlp[k] = HR[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; hlp[k] = HL[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; hlp[k] = HR[j]; j++; k++; } } void merge_sort(ull arr[], int* hlp, int l, int r) { if (l < r) { int m = l + (r - l) / 2; merge_sort(arr, hlp, l, m); merge_sort(arr, hlp, m + 1, r); merge(arr, hlp, l, m, r); } } void dir(wchar_t** wnames, ull* sze, time_t* tme1, int* hlp, int n) { for (int i = 2; i < n; i++) { //File name printf("%d. ", i - 1); printf("Name: "); int j = hlp[i]; wprintf(wnames[j]); //File size printf(" %10c Size (bites): %u ", ' ', sze[j]); //File creation time printf("%10c Created time: %s \n", ' ', ctime(&(tme1[j]))); } } int indir(wchar_t** wnames, ull* sze,time_t* tme, time_t* tme1, int* hlp) { int i = 0; char* a = (char*)malloc(MAX_PATH - 3); char* a1 = (char*)malloc(MAX_PATH); WIN32_FIND_DATA names[N]; WIN32_FIND_DATA fdata; HANDLE hfile; wchar_t* path = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); wchar_t* cpypath = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); //check input path do { printf("Input a path: \n"); printf("Be careful. If did not input a path like this: 'C:\\...\\...', you can have a problems \n"); //Preparing path â wchar_t //In C we dont have "gets" idk why also we need to input a string with spaces, we cant do this with scanf() gets_s(a, 260); strcat(a, "\\"); mbstowcs(cpypath, a, strlen(a) + 1); strcat(a, "*.*"); mbstowcs(path, a, strlen(a) + 1); hfile = FindFirstFile(path, &fdata); } while (hfile == INVALID_HANDLE_VALUE); printf("Your path : %s \n", a); printf("Data in your directory: \n"); do { if (i == 0 || i == 1) { i++; continue; } names[i] = fdata; if (names[i].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { wnames[i] = names[i].cFileName; sze[i] = 0; time_t* time1 = filetime_to_timet(names[i].ftCreationTime); ull a = names[i].ftCreationTime.dwHighDateTime; ull b = names[i].ftCreationTime.dwLowDateTime; ull tm = a << 32 | b; tm /= 10000000; tme[i] = tm; tme1[i] = time1; i++; continue; } wnames[i] = names[i].cFileName; sze[i] = names[i].nFileSizeLow; //File creation time time_t* time1 = filetime_to_timet(names[i].ftCreationTime); ull a = names[i].ftCreationTime.dwHighDateTime; ull b = names[i].ftCreationTime.dwLowDateTime; ull tm = a << 32 | b; tm /= 10000000; tme[i] = tm; tme1[i] = time1; i++; } while (FindNextFile(hfile, &fdata) != NULL); return i; } wchar_t *newpath(wchar_t* copypath, wchar_t* name) { wchar_t* newpath1 = (wchar_t*)malloc(mx_path * sizeof(wchar_t*)); wcscpy(newpath1, copypath); wcscat(newpath1, name); wcscat(newpath1, L"\\*.*"); return newpath1; } time_t filetime_to_timet(const FILETIME ft) { ULARGE_INTEGER ll; ll.LowPart = ft.dwLowDateTime; ll.HighPart = ft.dwHighDateTime; return ll.QuadPart / 10000000ULL - 11644473600ULL; } void sorting(wchar_t** wnames, ull* sze, time_t* tme, time_t* tme1, int* hlp, int i) { while (1) { ull* arr = (ull*)malloc(N * sizeof(ull)); ull* arrt = (ull*)malloc(N * sizeof(ull)); for (int j = 0; j < i + 10; j++) { arr[j] = sze[j]; arrt[j] = tme[j]; } for (int i = 0; i < N; i++) { hlp[i] = i; } printf("Input '0' if u wanna kill it\n"); int sr; printf("Input a sorted method: \n Input 1 for insert sort \n Input 2 for bubble sort \n Input 3 for merge sort \n "); do { printf("Input 1 or 2\n"); scanf("%d", &sr); } while ((sr != 1) && (sr != 2) && (sr != 3) && (sr != 0)); if (sr == 0) { break; } int wsr; printf("What i need to sort? \n Input 1 for sort size of files \n Input 2 for sort creation time \n "); do { printf("Input 1 or 2\n"); scanf("%d", &wsr); } while ((wsr != 1) && (wsr != 2)); if (sr == 1) { if (wsr == 1) { clock_t begin = clock(); insert_sort(arr, hlp, i); clock_t end = clock(); printf("Sorted data(size): "); dir(wnames, sze, tme1, hlp, i); long double q = end; q /= 1000000; printf("Time of insert sort: %lf.\n", q); } if (wsr == 2) { clock_t begin = clock(); insert_sort(arrt, hlp, i); clock_t end = clock(); printf("Sorted data(time): \n"); dir(wnames, sze, tme1, hlp, i); long double q = end; q /= 1000000; printf("Time of insert sort: %lf.\n", q); } } if (sr == 2) { if (wsr == 1) { clock_t begin = clock(); bubble_sort(arr, hlp, i); clock_t end = clock(); printf("Sorted data(size): "); dir(wnames, sze, tme1, hlp, i); long double q = end; q /= 1000000; printf("Time of Bubble_sort: %lf.\n", q); } if (wsr == 2) { clock_t begin = clock(); bubble_sort(arrt, hlp, i); clock_t end = clock(); printf("Sorted data(time): "); dir(wnames, sze, tme1, hlp, i); long double q = end; q /= 1000000; printf("Time of Bubble_sort: %lf.\n", q); } } if (sr == 3) { if (wsr == 1) { clock_t begin = clock(); merge_sort(arr, hlp, 0, i - 1); clock_t end = clock(); printf("Sorted data(size): "); dir(wnames, sze, tme1, hlp, i); long double q = end; q /= 1000000; printf("Time of Merge_sort: %lf.\n", q); } if (wsr == 2) { clock_t begin = clock(); merge_sort(arrt, hlp, 0, i - 1); clock_t end = clock(); printf("Sorted data(time): "); dir(wnames, sze, tme1, hlp, i); long double q = end; q /= 1000000; printf("Time of Merge_sort: %lf.\n", q); } } } }<file_sep>#include <stdio.h> #include "cars.h" #include <stdlib.h> #include <string.h> int main() { // get path to file with cars char* path = getPath(); puts(path); // read file and save info about cars to array int count_of_cars; Car* cars = ReadCarFile(path, &count_of_cars); // find oldest car Car oldest_car = FindOldestCar(cars, count_of_cars); // print answer PrintCar(oldest_car); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main() { float x1, y1, r1, x2, y2, r2, d; printf("Enter the center coordinates and radius of the first circle: "); scanf(" %f %f %f", &x1, &y1, &r1); printf("Enter the center coordinates and radius of the second circle: "); scanf(" %f %f %f", &x2, &y2, &r2); d = sqrt(x2 * x2 - 2 * x2 * x1 + x1 * x1 + y2 * y2 - 2 * y1 * y2 + y1 * y1); if (d > r1 + r2) { printf("The circles do not intersect."); } else if ((r1 == r2) && (d == 0)) { printf("The circles match."); } else if (d < abs(r1 - r2)) { printf("A circle with a small radius lies in a larger circle."); } else if (d == abs(r1 - r2)) { printf("Internal tangency of circles."); } else if (d == r1 + r2) { printf("External tangency of circles."); } else if ((abs(r1 - r2) < d) && (d < r1 + r2)) { printf("The circles intersect."); } return 0; }<file_sep> #include <stdio.h> #include <malloc.h> #include <string.h> #include "prototypes.h" #define NUM_EUROPE_COUNTRIES 20 char euro_zone[NUM_EUROPE_COUNTRIES][15] = {//list of eurozone countries "Austria\n", "Belgium\n", "Cyprus\n", "Estonia\n", "Finland\n", "France\n", "Germany\n", "Greece\n", "Ireland\n", "Italy\n", "Latvia\n", "Lithuania\n", "Luxembourg\n", "Malta\n", "Netherlands\n", "Portugal\n", "Slovakia\n", "Slovenia\n", "Croatia\n" }; int CountAgencies(FILE* fptr) { int num_agencies =0; char str[LEN]; char* str_p; char buffer[LEN] = "List agencies:"; int i = 0; int q = 1; int c = 0; while (!feof(fptr)) { fgets(str, LEN, fptr); fseek(fptr, -1, SEEK_CUR); if (strncmp(str, buffer, strlen(buffer)) == 0) { str_p = str; for (i = 0; i < strlen(str) - 1; i++) { c = str[i]; if (c >= 49 && c < 58) { num_agencies = atoi(str_p); break; } else str_p++; } } if (num_agencies == 0) { fseek(fptr, 1, SEEK_CUR); } if (num_agencies !=0) { break; } } fseek(fptr, 0, SEEK_SET); return num_agencies; } int* CountTServices(FILE* fptr) { int num_agencies; int* num_services; char str[LEN]; char* str_p; char buffer[LEN] = "Directions:"; char* buffer_p; int i, j; int len; int c = 0; i = j = 0; buffer_p = buffer; num_agencies = CountAgencies(fptr); num_services = (int*)malloc(sizeof(int) * num_agencies); for (i = 0; i < num_agencies; i++) { num_services[i] = 0; } while (j < num_agencies) { fgets(str, LEN, fptr); fseek(fptr, -1, SEEK_CUR); len = strlen(buffer_p); if (strncmp(str, buffer, len) == 0) { str_p = str; for (i = 0; i < strlen(str) - 1; i++) { c = str[i]; if (c >= 49 && c < 58) { num_services[j] = atoi(str_p); j++; break; } else str_p++; } } if (num_services[j] == 0) { fseek(fptr, 1, SEEK_CUR); } } fseek(fptr, 0, SEEK_SET); return num_services; } void allocate_TAgency(TAgency** pointer) { (*pointer) = (TAgency*)malloc(sizeof(TAgency));//creating a list of travel agencies (*pointer)->name = (char*)malloc(sizeof(char) * LEN); } void allocate_TServices(TAgency* ptr, int count_services) { ptr->num_services = count_services; ptr->services = (TService*)malloc(sizeof(TService) * count_services);//creating a service structure for each facility for (int i = 0; i < ptr->num_services; i++) { ptr->services[i].country = (char*)malloc(sizeof(char) * LEN); ptr->services[i].travel_conditions = (char*)malloc(sizeof(char) * LEN); ptr->services[i].excursion_services = (char*)malloc(sizeof(char) * LEN); ptr->services[i].host_service = (char*)malloc(sizeof(char) * LEN); ptr->services[i].ticket_price = (char*)malloc(sizeof(char) * LEN); } } void search_string(FILE* fptr) {//look for the first occurrence of the string int i = 0; char c[LEN]; int len; fgets(c, LEN, fptr); if (c[0] == 10) { do { fgets(c, LEN, fptr); } while (c[0] == 10); len = strlen(c); fseek(fptr, -len-1, SEEK_CUR); } else { len = strlen(c); fseek(fptr, -len - 1, SEEK_CUR); } } int file_reader(FILE * fptr, TAgency *** list) { int num_agencies = CountAgencies(fptr); int* num_services = CountTServices(fptr); *(list) = (TAgency**)malloc(sizeof(TAgency*)*num_agencies); //create a dynamic array of objects int i = 0; int c = 0; int j = 0; const char buffer1[LEN] = "List agencies:"; const char buffer2[LEN] = "Directions:"; int num; for (i = 0; i < num_agencies; i++) { allocate_TAgency(&(*list)[i]);//Give the same pointer to create the structure } for (i = 0; i < num_agencies; i++) { allocate_TServices((*list)[i], num_services[i]);//Give the same pointer to create the structure } for (i = 0; i < num_agencies; i++) { search_string(fptr); fgets((*list)[i]->name, LEN, fptr); if ((strncmp((*list)[i]->name, buffer1, strlen(buffer1)) == 0) || (strncmp((*list)[i]->name, buffer2, strlen(buffer2))) == 0) { do { c = fgetc(fptr); } while (c == 10); fseek(fptr, -1, SEEK_CUR); fgets((*list)[i]->name, LEN, fptr); } for (j = 0; j < (*list)[i]->num_services; j++) { search_string(fptr); if (j==0) { do { c = fgetc(fptr); } while (c != 10); } fgets((*list)[i]->services[j].country, LEN, fptr); fgets((*list)[i]->services[j].travel_conditions, LEN, fptr); fgets((*list)[i]->services[j].excursion_services, LEN, fptr); fgets((*list)[i]->services[j].host_service, LEN, fptr); fgets((*list)[i]->services[j].ticket_price, LEN, fptr); } } fseek(fptr, 0, SEEK_SET); free(num_services); return num_agencies; } void output_all_data(FILE* fptr, TAgency** list, int num_agencies) { int i = 0; int j = 0; for (i = 0; i < num_agencies; i++) { printf("%s", list[i]->name); for (j = 0; j < list[i]->num_services; j++) { search_string(fptr); printf("%s",list[i]->services[j].country); printf("%s", list[i]->services[j].travel_conditions); printf("%s", list[i]->services[j].excursion_services); printf("%s", list[i]->services[j].host_service); printf("%s", list[i]->services[j].ticket_price); printf("\n"); } } } void output_data_EZONES(FILE* fptr, TAgency** list, int num_agencies) { int i = 0; int j = 0; int k = 0; for (i = 0; i < num_agencies; i++) {//going over the TAgency printf("%s", list[i]->name); for (j = 0; j < list[i]->num_services;j++) {//going over the TServices for (k = 0; k < NUM_EUROPE_COUNTRIES; k++) {//scanning base of data if (strcmp(list[i]->services[j].country, euro_zone[k]) == 0) { printf("%s", list[i]->services[j].country); printf("%s", list[i]->services[j].travel_conditions); printf("%s", list[i]->services[j].excursion_services); printf("%s", list[i]->services[j].host_service); printf("%s", list[i]->services[j].ticket_price); printf("\n"); } if (k == NUM_EUROPE_COUNTRIES && list[i]->num_services == 1) { printf("(No suitable destination found!)"); } } } } } void free_memory(TAgency** pointer, int num_agencies){ int i, j; for ( i = 0; i < num_agencies; i++) {//Freeing up memory from dynamic fields for (j = 0; j < pointer[i]->num_services; j++) { free(pointer[i]->services[j].country); free(pointer[i]->services[j].travel_conditions); free(pointer[i]->services[j].excursion_services); free(pointer[i]->services[j].host_service); free(pointer[i]->services[j].ticket_price); } } for (i = 0; i < num_agencies; i++) { free(pointer[i]->name); free(pointer[i]->services);//massive TService free(pointer[i]);//object } free(pointer);//freeing up memory massive pointers } <file_sep>#pragma once #include <stdio.h> #include <stdlib.h> typedef struct { float* x; int d; } TMatrix; void allocate_matrix(TMatrix** matrix, int d); void build_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix, int dimension); TMatrix* addition(TMatrix* matrix1, TMatrix* matrix2, int dimension); TMatrix* multiplication(TMatrix* matrix1, TMatrix* matrix2, int dimension); TMatrix* multiplication_const(TMatrix* matrix1, int consta, int dimension); void free_m(TMatrix** matrix);<file_sep>#include "Book.h" #include <iostream> #include <string> #include <fstream> #include <locale.h> #include <sstream> int main() { setlocale(LC_ALL, "Rus"); string path = get_path(); TLib full_library(path); cout << full_library; int choose_section_number; TLib sectionLibrary; do { full_library.print_unique_sections(); cin >> choose_section_number; if (choose_section_number != 0) { sectionLibrary = full_library.search_by_section(full_library.unic_section[choose_section_number - 1]); cout << sectionLibrary; } } while (choose_section_number != 0); return 0; } <file_sep>#include <stdio.h> #include "matrix.h" int main() { TMatrix* m1, *m2, *res; // Creating matrices alloc_matrix(&m1, 2); alloc_matrix(&m2, 2); // Filling in the matrices fill_matrix(m1); fill_matrix(m2); // Output of matrices print_matrix(m1); print_matrix(m2); // 1. Adding a scalar to the matrix res = add_scalar(m1, 2); print_matrix(res); free_matrix(&res); // 2. Multiplication a matrix by a scalar res = multi_scalar(m1, 2); print_matrix(res); free_matrix(&res); // 3. Adding a matrix to another matrix res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); // 4. Multiplication a matrix to another matrix res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>// ConsoleApplication2.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <stdlib.h> #include <stdio.h> #include "matrix.h" int main() { TMatrix* matrix_d, *m1, *m2, *res, *size; size_matrix(& size); alloc_matrix(&matrix_d,size);//vyvod scan_matrix(matrix_d); print_matrix(matrix_d); free_matrix(&matrix_d); alloc_matrix(&m1, size);//scan m1,m2 alloc_matrix(&m2, size); scan_matrix(m1); scan_matrix(m2); res = matrix_add_const(m1, 2);//add print_matrix(res); free_matrix(&res); res = matrix_multiply_const(m1, 2);//multiply c. print_matrix(res); free_matrix(&res); res = matrixes_multiply(m1, m2);//multiply m. print_matrix(res); free_matrix(&res); free(&m1); free(&m2); return 0; } <file_sep>cmake_minimum_required(VERSION 3.23) project(SHISHKAREV_AM C) set(CMAKE_C_STANDARD 23) add_executable(SHISHKAREV_AM main.c) <file_sep>#include "Header.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include <stdbool.h> int count_books(char* str) { int count = 0; char line[LINE]; printf("Введите название файла\n"); gets(str); FILE* file = fopen(str, "r"); if (file == NULL) { printf("Нет такого файла"); return -1; } while (fgets(line, LONGLINE, file) != NULL) { count++; } fclose(file); return count; } void setAuthors(char* strTmp,TBook* book) { char* pos1; char find[] = ","; int i,count = 0; char strTmp1[LINE]; strcpy(strTmp1, strTmp); pos1 = strtok(strTmp, find); while (pos1 != NULL) { count++; pos1 = strtok(NULL, find); } book->Couaut = count; (book->Author) = malloc(sizeof(*(book->Author)) * count); for (i = 0; i < count; i++) { book->Author[i] = malloc(LONTAUTHORNAME); } pos1 = strtok(strTmp1, find); i = 0; while (pos1 != NULL) { strcpy(book->Author[i], pos1); i++; pos1 = strtok(NULL, find); } } void read(char* str, TBook* book) { int n,j=0,count=0; char line[LONGLINE]; char* pos1; char find[] = ";"; char strTmp[LINE]; FILE* file = fopen(str, "r"); while (fgets(line, LONGLINE, file) != NULL) { pos1 = strtok(line, find); if (*pos1 == '\n') { break; } n = 0; strcpy(strTmp, pos1); while (pos1 != NULL) { pos1 = strtok(NULL, find); switch (n) { case (0): { strcpy(book->Name, pos1); n++; break; } case (1): { strcpy(book->Publishing, pos1); n++; break; } case (2): { strcpy(book->Section, pos1); n++; break; } case (3): { if (strcmp(pos1, "Есть") == 0) { book->Availability = true; } else { book->Availability = false; } n++; break; } case (4): { book->Score= strtol(pos1,NULL,10); n++; break; } } } setAuthors(strTmp, book); book++; } fclose(file); } int count_unic(TBook* book, int count) { int unic = 0; int i, j; int flag; for (i = 0; i < count; i++) { flag = 0; for (j=i+1;j<count;j++) { if (strcmp(book[i].Section, book[j].Section) == 0) { flag++; break; } } if (flag == 0) unic++; } return unic; } char** create_section(TBook* book, int unic, int count) { int i,flag,k,j; char** unic_section; unic_section = (char**)malloc(sizeof(char*) * unic); k = 0; for (i = 0; i < unic; i++) { unic_section[i] = (char*)malloc(sizeof(char)*LINE); } for (i = 0; i < count; i++) { flag = 0; for (j = i + 1; j < count; j++) { if (strcmp(book[i].Section, book[j].Section) == 0) { flag++; break; } } if (flag == 0) { strcpy(unic_section[k], book[i].Section); k++; } } return unic_section; } void print_book(TBook* book,int count) { int i,j; printf("Имеются следующие книги в нашей библиотеке:\n\n"); for (i = 0; i < count; i++) { printf("%d.", (i+1)); printf("Автор -"); for (j = 0; j < book[i].Couaut; j++) { printf(" %s, ", book[i].Author[j]); } printf("| Название книги - %s|", book[i].Name); printf(" Издательство - %s|", book[i].Publishing); printf(" Жанр - %s|", book[i].Section); if(book->Availability) { printf("Наличие - Есть"); } else { printf("Наличие - Нет"); } printf("|Оценка - %d\n", book[i].Score); } } void print_section(TBook* book, int count, char* word) { int i,j; j = 1; for (i = 0; i < count; i++) { if (strcmp(book[i].Section, word) == 0) { printf("%d.", j++); printf("Автор -"); for (j = 0; j < book[i].Couaut; j++) { printf(" %s, ", book[i].Author[j]); } printf(" | Название книги - %s|", book[i].Name); printf(" Издательство - %s|", book[i].Publishing); printf(" Жанр - %s|", book[i].Section); if (book->Availability) { printf("Наличие - Есть"); } else { printf("Наличие - Нет"); } printf("|Оценка - %d\n", book[i].Score); } } } void print_choose_book(TBook* lib, int count,int unic,char** unic_section) { int a,i; char word[20]; do { printf("\nКакой жанр вы хотите увидеть?\n"); for (i = 0; i < unic; i++) { printf("%d - %s\n",i+1, unic_section[i]); } printf("Если хотите выйти, введите 0\n"); scanf("%d", &a); if ((a > 0) && (a <= unic)) { print_section(lib, count, unic_section[a-1]); } } while (a != 0); } void free_mas(TBook* book,int count) { int i,j; int pos; for (i = 0; i < count; i++) { pos = book[i].Couaut; for (j = 0; j < pos; j++) { free(book[i].Author[j]); } free(book[i].Author); } free(book); } void free_unic(char** unic_section, int unic) { int i; for (i = 0; i < unic; i++) { free(unic_section[i]); } free(unic_section); } <file_sep>#include "lib.h" int main() { string path = menu(); Library lib(path); set <string> sections = lib.booksBySection(); vector <CardIndex> books = lib.findBooks(sections); lib.getBook(books); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" void allocate_matrix(Matrix** matrix, int n) { (*matrix) = (Matrix*)malloc(sizeof(Matrix) * 1); (*matrix)->n = n; (*matrix)->x = (float*)malloc(sizeof(float) * n * n); } void fill_matrix(Matrix* matrix) { int i,j; for (i = 0; i < matrix->n; i++) for (j = 0; j < matrix->n; j++) scanf("%f", &(matrix->x[i * matrix->n + j])); } void print_matrix(Matrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) printf("%.1f ", matrix->x[i * matrix->n + j]); printf("\n"); } } void free_matrix(Matrix** matrix) { free((*matrix)->x); free(*matrix); } Matrix* addition_matrix(Matrix* matrix1, Matrix* matrix2) { Matrix* res; int i,j; if (matrix1->n != matrix2->n) { printf("ERROR: Matrices should have the same size.\n"); return NULL; } allocate_matrix(&res, matrix1->n); for (i=0; i < res->n; i++) for (j=0;j<res->n;j++) res->x[i * res->n + j] = matrix1->x[i * res->n + j] + matrix2->x[i * res->n + j]; return res; } Matrix* addition_const(Matrix* matrix, float c) { Matrix* res; int i, j; allocate_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) for (j = 0; j < res->n; j++) res->x[i * res->n + j] = matrix->x[i * res->n + j] + c; return res; } Matrix* multi_const(Matrix* matrix, float c) { Matrix* res; int i, j; allocate_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) for (j = 0; j < res->n; j++) res->x[i * res->n + j] = matrix->x[i * res->n + j] * c; return res; } Matrix* multi_matrix(Matrix* matrix1, Matrix* matrix2) { Matrix* res; int i, j, k; if (matrix1->n != matrix2->n) { printf("ERROR: Matrices should have the same size.\n"); return NULL; } allocate_matrix(&res, matrix1->n); for (i = 0; i < res->n; i++) for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = 0.0; for (k = 0; k < res->n; k++) res->x[i * res->n + j] += matrix1->x[i * res->n + k] * matrix2->x[k * res->n + j]; } return res; }<file_sep>#include <iostream> #include <fstream> #include "stars.h" using namespace std; Constellation_library:: Constellation_library(int n) { count = n; cns = new Constellation*[n]; } Constellation_library:: ~Constellation_library() { delete (*cns); delete[] cns; } Constellation:: Constellation(std::string Cname, int n) { count = n; name = Cname; stars = new Star[n]; } Constellation:: ~Constellation() { delete[] stars; } void read_data(Constellation_library*& lib, int& cnt) { ifstream in; string path, name; int st_cnt; cout << endl << "Enter the path: "; cin >> path; in.open(path); if (in.is_open()) { in >> cnt; lib = new Constellation_library(cnt); for (int i = 0; i < cnt; i++) { in >> name >> st_cnt; lib->cns[i] = new Constellation(name, st_cnt); in >> lib->cns[i]; } in.close(); } } void cnst_table(Constellation_library* lib, int count) { for (int i = 0; i < count / 2; i++) { cout << i + 1 << "." << lib->cns[i]->name << " \t\t " << i + 6 << "." << lib->cns[i + 5]->name << endl; } cout << "\nOutput format:\n\n name distance magnitude coordinates(deg, min, sec)\n\n"; } std::ostream& operator<< (std::ostream& out, const Constellation* cns) { cout << endl << cns->name << endl; for (int i = 0; i < cns->count; i++) { cout << " " << cns->stars[i].name << " " << cns->stars[i].dist << " " << cns->stars[i].magnitude << " "; cout << cns->stars[i].deg << "° " << cns->stars[i].min << "' " << cns->stars[i].sec << "\"" << endl; } return out; } std::istream& operator>> (std::istream& in, const Constellation* cns) { for (int j = 0; j < cns->count; j++) { in >> cns->stars[j].name; in >> cns->stars[j].dist >> cns->stars[j].magnitude >> cns->stars[j].deg >> cns->stars[j].min >> cns->stars[j].sec; } return in; } void choice(Constellation_library* lib, int count) { string con; cout << "Choice a constellation" << endl; do { int flag = 0; cout << endl << ">> "; cin >> con; if (con == "stop") flag = 1; for (int i = 0; i < count && flag == 0; i++) { if (lib->cns[i]->name == con) { cout << lib->cns[i]; flag = 1; } } if (!flag) cout << "Not found. Please, choose constellation from table" << endl; } while (con != "stop"); delete lib; } <file_sep>#ifndef _HEADER_H #define _HEADER_H typedef struct { char* name; char* unit; double price; int number; } product; typedef struct { int day; int month; int year; } date; int cntLines(const char* filename); void allocate_stock(product** shipment, date** data, int number); void fill_shipment(product* shipment, date* data, int number); void find_null(product* shipment, date* data, int number); void free_stock(product** shipment, date** data, int number); #endif<file_sep>#include "matrix.h" #include <stdio.h> int main() { TMatrix* matrix_d, * m1, * m2, * res; alloc_matrix(&matrix_d, 2); fill_matrix(matrix_d); print_matrix(matrix_d); free_matrix(&matrix_d); alloc_matrix(&m1, 3); alloc_matrix(&m2, 3); fill_matrix(m1); fill_matrix(m2); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); res = add_constant(m1, 2); print_matrix(res); free_matrix(&res); res = multi_constant(m1, 2); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); return 0; } <file_sep>// Спортивная команда.Спортивная команда характеризуется названием, городом, // за который играет, количеством сыгранных игр, количеством очков, // количеством игроков.Среди множества спортивных команд определить команду, // которая имеет максимальное количество очков. #include "comand.h" int main() { output(); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <memory.h> #define N 10 #define _CRT_SECURE_NO_WARNINGS char names[N][16] = { "Water", "Chocolate", "Milk", "Bread", "Fries", "Soup", "Tea", "Coffee", "Cookies", "Sugar" }; char barcodes[N][6] = { "0001","0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", }; int sales[N] = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 }; int coasts[N] = { 20, 50, 50, 35, 40, 90, 90, 300, 150, 50 }; int cart[N] = { 0 }; int index(char user_code[5]) { for (int i = 0; i < 10; i++) { if (strcmp(&(barcodes[i]), user_code) == 0) { return i; } } } void product_information(char user_code[5]) { int i = index(user_code); printf("You choose %s\n ", names[i]); printf("The price per unit with a discount is: %d \n", coasts[i] - (coasts[i] * sales[i] / 100)); } int amount_summ() { int s = 0; for (int i = 0; i < N; i++) { s += cart[i] * (coasts[i] - (coasts[i] * sales[i] / 100)); } return s; } void list() { char p = ' '; printf("Hi, goods in stock:\n\n"); printf("product %11c price(rub) %5c discount(%%) %5c barcode\n", p, p, p); printf("--------------------------------------------------------------\n"); printf("Water %14c 20 %13c 5 %15c 0001\n", p, p, p); printf("Chocolate %10c 50 %13c 10 %14c 0002\n", p, p, p); printf("Milk %15c 50 %13c 15 %14c 0003\n", p, p, p); printf("Bread %14c 35 %13c 20 %14c 0004\n", p, p, p); printf("Fries %14c 40 %13c 25 %14c 0005\n", p, p, p); printf("Soup %15c 90 %13c 30 %14c 0006\n", p, p, p); printf("Tea %16c 90 %13c 35 %14c 0007\n", p, p, p); printf("Coffee %13c 300 %12c 40 %14c 0008\n", p, p, p); printf("Cookies %12c 150 %12c 45 %14c 0009\n", p, p, p); printf("Sugar %14c 50 %13c 50 %14c 0010\n", p, p, p); printf("--------------------------------------------------------------\n\n"); } void removed() { printf("Choose a barcode of this product: \n"); for (int i = 0; i < N; i++) { if (cart[i] != 0) { printf("Name: %s Barcode: %s Count: %d \n", names[i], barcodes[i], cart[i]); } } char tmp[5]; scanf("%s", &tmp); int i = index(tmp); if (cart[i] == 0) { printf("You cant remove this product. Try again \n "); } else { int cnt; printf("Input a number 0 <= number <= %d \n", cart[i]); scanf("%d", &cnt); if (cnt > cart || cnt < 0) { printf("Try again. You inputed a wrong count \n"); } else { cart[i] -= cnt; printf("Done!"); } } } void basket() { int c1 = 0, sl = 0, f = 0;; for (int i = 0; i < N; i++) { if (cart[i] != 0) { f++; printf("Name: %s Barcode: %s, Unit_price: %d Discount %d Count: %d Total_cost: %d \n", names[i], barcodes[i],coasts[i], (coasts[i] * sales[i] / 100), cart[i], cart[i] * (coasts[i] - (coasts[i] * sales[i] / 100))); sl += coasts[i] - coasts[i] * sales[i]/100; } } if (f == 0) printf("Cart is empty \n"); else printf("Total cost of goods: %d Total discount of goods: %d\n ", amount_summ(), sl); } void pay() { int as = amount_summ(); int tmp = 0; while (10 > 9) { printf("Write %d for to pay for the goods \n", as); scanf("%d", &tmp); if (tmp == as) { printf("Thank you \n"); break; } else if (tmp < as) { as = as - tmp; printf("You have to pay another \n"); } else if (tmp > as) { printf(" This is your change %d \n", tmp - as); break; } } } void gen_of_receipt() { printf("Cashier: Mircosoft Visual Studio\n "); basket(); printf("To be paid: %d \n ", amount_summ()); pay(); } int scanning_funtion() { int flag = 1, count; while (flag != 0) { printf("You always can input 'stop' if u wanna kill it "); //Scanning barcode char user_code[10]; printf("Scan your barcode: \n"); scanf("%s", user_code); //exit if (strcmp(user_code, "stop") == 0) { flag = 0; return 0; } //check input barcode int product_index = check_user_code(user_code); while (product_index == -1) { printf("Pls, scan a right barcode: "); scanf("%s", &user_code); product_index = check_user_code(user_code); } product_information(user_code); printf("Input a count you wanna to buy. Input 0 if u dont want to buy it. \n "); scanf("%d", &count); if (count != 0) { cart[product_index] += count; printf("Done! %d products '%s' have been added to the cart \n", count, names[product_index]); continue; } } int s = amount_summ(); if (s == 0) { int id = random_digit(); printf("You did not choose any product :( Maybe u wanna %s with %d percent a discount \n", names[id], sales[id]); } else printf("You added to the cart products for %d \n", s); return 0; } int main() { int c = 0, user; list(); while (c == 0) { printf("\n Also u can: \n Input 1 for add a products to cart \n Input 2 for know more about product. \n Input 3 for total cost \n Input 4 for generate a receipt \n Input 5 for remove last product from a cart \n Input 6 for print shopping cart \n "); scanf("%d", &user); //Box office if (user == 1) scanning_funtion(); else if (user == 2) list(); else if (user == 3) { printf("In your basket of products for %d rubles \n", amount_summ()); } else if (user == 4) { gen_of_receipt(); c = 1; break; } else if (user == 5) removed(); else if (user == 6) basket(); else printf("Choose a operation and write a digit from 1 to 6 pls. \n"); } printf("Have a nice day!"); return 0; } int check_user_code(char* user_code) { int product_index = -1, f=0; for (int i = 0; i < N; i++) { if (strcmp(barcodes[i], user_code) == 0) { product_index = i; break; } } return product_index; } int random_digit() { int n; srand((unsigned int)time(NULL)); n = rand() % (10); return n; }<file_sep>#include <iostream> #include "Header.h" #include <string> #include <fstream> void main() { int n = 12; string filename; cin >> filename; lib empls(filename); cout << "all employees:" << endl << empls << endl << endl << "elderly ones:" << endl << empls.output(); } <file_sep>#include <iostream> #include "fileProcessing.h" #include "userSide.h" int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); std::string fname; Univ_database_t unsdata(fname); working_with_user(unsdata); return 0; }<file_sep>#include <stdio.h> #include <string.h> #define N 10 char* barcodes[N] = { "0101", "0202", "0303", "1212", "1414", "2323", "4545", "5236", "5632", "7845" }; char* products[N] = { "Milk", "Bread", "Butter", "Cheese", "Sugar", "Juice", "Chicken", "Jam", "Beer", "Pie" }; float price[N] = { 79.90, 49.00, 120.50, 210.90, 75.00, 99.00, 230.00, 125.50, 69.99, 189.90 }; float discount[N] = { 5.9, 4, 12.5, 15, 5, 8, 19, 11.50, 9.99, 4.90 }; void scan(int* ct) { char bc[5] = ""; int count[10] = { 0 }; printf("Enter barcodes...\n"); while (strcmp(bc, "q")) { gets(bc); if (strcmp(bc, "q")) { for (int i = 0; i < N; i++) { if (strcmp(barcodes[i], bc) == 0) { printf("%s, price: %.2f, diccount: %.2f\n", products[i], price[i], discount[i]); ct[i] += 1; } } } } } void printReceipt(int* ct) { float totalCost = 0; printf("Your receipt :)\n"); for (int i = 0; i < N; i++) { if (ct[i] == 0) continue; printf("%s, price including discount - %.2f, %d units.\n", products[i], price[i]-discount[i], ct[i]); totalCost += (price[i] - discount[i])*ct[i]; } printf("Total cost - %.2f", totalCost); } int main() { int counts[N] = { 0 }; scan(counts); printReceipt(counts); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #define N 10 char* barcodes[N] = { "1212", "0101" , "2323" , "2424" , "5454" , "5858" , "8989" , "9090" , "9898" , "2727" }; char* names[N] = { "Tea", "Milk", "Bread", "Eggs", "Apples", "Chocolate", "Cookies", "Beer", "Sugar", "Salt" }; int price[N] = { 150, 100, 105, 100, 120, 240, 179, 149, 350, 120 }; float discout[N] = { 0.15, 0.20, 0.0, 0.25, 0.10, 0.35, 0.39, 0.0, 0.0, 0.0 }; void scan(int* arr) { int i,f; float cost; char a[5]; printf("Good day!\n Enter the barcodes of your products\n If you have entered all your products, then write 0\n"); do { printf("Enter the barcode\n"); gets(a); f = 0; for (i = 0; i < N; i++) { if (strcmp(barcodes[i], a) == 0) { arr[i]++; cost = price[i] - discout[i] * price[i]; printf("| %s | Price is %d rubles | Discout is %.0f%% | Total cost is %.2f rubles\n\n", names[i], price[i], discout[i]*100,cost);//Вывод информации о товаре f = 1; } } if ((f == 0) && (strcmp(a, "0")!=0)) { printf("There is no such barcode, check the correctness of the input\n\n"); } } while (strcmp(a,"0")); } void receipt_print (int *arr) { int i, sum = 0; float r_price,sum_discout=0,total_sum=0; for (i = 0; i < N; i++) { if (arr[i] > 0) { sum = price[i]*arr[i] + sum; r_price = (price[i] - price[i] * discout[i])*arr[i]; total_sum = total_sum + r_price; sum_discout=sum_discout+ (price[i] * discout[i])*arr[i]; printf("|%10s\t|\tCOST=%d\t|\tCOUNT=%d\t|\tTOTAL COST=%.2f\t|\n", names[i], price[i], arr[i], r_price); } } printf("\n\tThe cost of all goods=%d rubles\n", sum); printf("\tTotal discount=%.2f rubles\n", sum_discout); printf("\tTotal cost of all goods=%.2f rubles\n", total_sum); } int main() { int i; int count[N] = { 0 }; scan(count); printf("YOUR RECEIPT\n\n"); receipt_print(count); return 0; }<file_sep>#ifndef FILM_H #define FILM_H #include <string> #include <fstream> #include <vector> struct Producer { std::string Name; std::string Surname; friend std::istream& operator>>(std::istream& input_stream, Producer& p); friend std::ostream& operator<<(std::ostream& output_stream, const Producer& p); bool operator==(const Producer& p) const; }; struct Film { std::string film_name; Producer creator; std::string country; int year; int budget; int fees; friend std::istream& operator>>(std::istream& input_stream, Film& p); friend std::ostream& operator<<(std::ostream& output_stream, const Film& p); }; std::string getInput(const std::string& message); Producer getProducerFromFile(std::ifstream& file); Producer getProducerFromString(std::string& producer_str); Film ReadFilmEntity(std::ifstream& file); std::vector<Film> ReadFileWithFilms(const std::string& file_path); std::vector<Film> getFilmsByProducer(const std::vector<Film>& all_films, const Producer& creator); #endif <file_sep>#include <iostream> #include "Header.h" #include <string> #include <fstream> using namespace std; string get_string(ifstream& file) { string tmp; getline(file, tmp); return tmp; } lib::lib(int n) { emp_amount = n; empls = new employee[emp_amount]; } lib::lib(const lib& l) { emp_amount = l.emp_amount; empls = new employee[emp_amount]; for (int i = 0; i < emp_amount; i++) { this->empls[i] = l.empls[i]; } } lib::lib(const string& filename) { string* strtmp = new string[50]; ifstream file(filename); int n = 0; while ((strtmp[n] = get_string(file)) != "") n++; emp_amount = n; empls = new employee[emp_amount]; for (int i = 0; i < emp_amount; i++) empls[i].create_data(strtmp[i]); file.close(); delete[] strtmp; } lib::~lib() { delete[] this->empls; } employee& lib::operator[](int ind) { return empls[ind]; } lib lib::output() { int n = 0; for (int i = 0; i < this->emp_amount; i++) if (this->empls[i].pspt.isElderly()) n++; lib new_lib(n); int k = 0; for (int i = 0; i < this->emp_amount; i++) if (this->empls[i].pspt.isElderly()) { new_lib[k] = this->empls[i]; k++; } return new_lib; } void employee::create_data(string str) { string Stmp[14]; string delim = ";"; size_t last = 0; size_t next; int i = 0; while ((next = str.find(delim, last)) != string::npos) { Stmp[i] = str.substr(last, next - last); i++; last = next + delim.length(); } Stmp[12] = str.substr(last); this->pspt.create_data(Stmp); this->name = Stmp[0]; this->edu = Stmp[7]; this->spec = Stmp[8]; this->unit = Stmp[9]; this->appnt = Stmp[10]; this->dateofappnt.create_data(Stmp[11]); this->lastdate.create_data(Stmp[12]); } const employee& employee::operator=(const employee& e) { pspt = e.pspt; name = e.name; edu = e.edu; spec = e.spec; unit = e.unit; appnt = e.appnt; dateofappnt = e.dateofappnt; lastdate = e.lastdate; return *this; } const pasport& pasport::operator=(const pasport& p) { series = p.series; number = p.number; auth = p.auth; reg = p.reg; issue = p.issue; birth = p.birth; return *this; } void pasport::create_data(string* str) { this->series = atoi(str[1].c_str()); this->number = atoi(str[2].c_str()); this->auth = str[3]; this->reg = str[6]; this->issue.create_data(str[4]); this->birth.create_data(str[5]); } bool pasport::isElderly() { if ((birth.year < 58) || ((birth.year == 58) && ((birth.month < 4) || ((birth.month == 4) && (birth.day < 27))))) return true; else return false; } void date::create_data(string str) { string tmp; tmp = str.substr(0, 2); this->day = atoi(tmp.c_str()); tmp = str.substr(3, 2); this->month = atoi(tmp.c_str()); tmp = str.substr(8, 2); this->year = atoi(tmp.c_str()); } const date& date::operator=(const date& d) { day = d.day; month = d.month; year = d.year; return *this; } <file_sep>#ifndef _DATABASE_H #define _DATABASE_H #include <iostream> #include <fstream> #include <string> #include "products.h" #include "container.h" using namespace std; class TDataLine { private: TProduct product; int count; public: TDataLine(const string _code = "", const string _name = "", const double _cost = 0, const int _count = 0); void Set(const string _code, const string _name, const double _cost, const int _count); void ChangeCount(int dcount) { count += dcount; } TProduct* GetProduct(){ return &product; } void Print(); string GetCode() { return product.GetCode(); } string GetName() const { return product.GetName(); } double GetCost() const { return product.GetCost(); } int& GetProductCount() { return count; } bool operator==(const TDataLine& dl) const; bool operator!=(const TDataLine& dl) const; const TDataLine& operator=(const TDataLine& dl); friend ostream& operator<<(ostream& out, const TDataLine& d) { out << d.product << " " << setfill(' ') << setw(3) << d.count; return out; } }; class TDataBase { private: TContainer<TDataLine> products; public: TDataBase(const string& filename = "data.txt"); void ScanFile(const string& filename = "data.txt"); void ArchiveData(const string& filename = "data.txt"); void UpdateData(const string& filename = "data.txt"); // Кол-во продуктов в базе данных int Size() { return products.Count(); } // -1 - Продукт не найден int Check(const string& _code); TProduct* GetProduct(int index); int& GetProductCount(int ind) { return products[ind].GetProductCount(); } int& GetProductCount(const string& _code); void PrintAll() { for (int i = 0; i < products.Count(); i++) { cout << "#" << i << ": "; products[i].Print(); } } friend ostream& operator<<(ostream& out, const TDataBase& d) { for (int i = 0; i < d.products.Count(); i++) out << "№" << i << ": " << d.products[i] << endl; return out; } }; #endif // !_DATABASE_H <file_sep>#include <stdio.h> void main() { float p_Tree = 900.0, p_DVP = 800.0, p_DSP = 800.0; float th_Tree = 0.01, th_DVP = 0.005, th_DSP = 0.015; float h, w, d, m_z, m_b, m_k, m_d, m_p, weight_carcas; int n; printf("Enter the height of the wardrobe "); scanf_s("%f", &h); printf("Enter the width of the wardrobe "); scanf_s("%f", &w); printf("Enter the lenght of the wardrobe "); scanf_s("%f", &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) { printf("Size input error"); return 1; } else { h = h / 100; w = w / 100; d = d / 100; n = h / 0.4; m_z = h * (w - 2 * th_DSP) * th_DVP * p_DVP; m_b = h * d * th_DSP * p_DSP * 2; m_k = (w - 2 * th_DSP) * (d - th_DVP) * th_DSP * p_DSP * 2; m_d = h * w * th_Tree * p_Tree; m_p = (w - 2 * th_DSP) * (d - th_DVP) * th_DSP * p_DSP * n; weight_carcas = m_z + m_b + m_k + m_d + m_p; printf("Weight of wardrobe %f", weight_carcas); } }<file_sep>#include "sort.h" void swap(unsigned long* x, unsigned long* y) { unsigned long temp; temp = *x; *x = *y; *y = temp; } void quicksort(unsigned long* list, int m, int n, int* index) { unsigned long key, i, j, k; if (m < n) { k = (m + n) / 2; swap(&list[m], &list[k]); swap(&index[m], &index[k]); key = list[m]; i = m + 1; j = n; while (i <= j) { while ((i <= n) && (list[i] <= key)) i++; while ((j >= m) && (list[j] > key)) j--; if (i < j) { swap(&list[i], &list[j]); swap(&index[i], &index[j]); } } swap(&list[m], &list[j]); swap(&index[m], &index[j]); quicksort(list, m, j - 1, index); quicksort(list, j + 1, n, index); } } void merge(unsigned long* a, unsigned long* tmp, int left, int mid, int right, unsigned long* index, unsigned long* itmp) { unsigned long i, left_end, count, tmp_pos; left_end = mid - 1; tmp_pos = left; count = right - left + 1; while ((left <= left_end) && (mid <= right)) { if (a[left] <= a[mid]) { tmp[tmp_pos] = a[left]; itmp[tmp_pos] = index[left]; tmp_pos = tmp_pos + 1; left = left + 1; } else { tmp[tmp_pos] = a[mid]; itmp[tmp_pos] = index[mid]; tmp_pos = tmp_pos + 1; mid = mid + 1; } } while (left <= left_end) { tmp[tmp_pos] = a[left]; itmp[tmp_pos] = index[left]; left = left + 1; tmp_pos = tmp_pos + 1; } while (mid <= right) { tmp[tmp_pos] = a[mid]; itmp[tmp_pos] = index[mid]; mid = mid + 1; tmp_pos = tmp_pos + 1; } for (i = 0; i <= count; i++) { a[right] = tmp[right]; index[right] = itmp[right]; right = right - 1; } } void msort(unsigned long* a, unsigned long* tmp, int left, int right, unsigned long* index, unsigned long* itmp) { unsigned long mid; if (right > left) { mid = (right + left) / 2; msort(a, tmp, left, mid, index, itmp); msort(a, tmp, mid + 1, right, index, itmp); merge(a, tmp, left, mid + 1, right, index, itmp); } } void bubbleSort(unsigned long* a, int size, int* index, char** fname) { int i, j; unsigned long tmp; int indtmp; for (i = 1; i < size; i++) { for (j = 1; j < size; j++) { if (a[j] > a[j - 1]) { tmp = a[j]; indtmp = index[j]; a[j] = a[j - 1]; index[j] = index[j - 1]; a[j - 1] = tmp; index[j - 1] = indtmp; } } } }<file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { int* x; int n; //number of elements in a column } TMatrix; void allocate_matrix(TMatrix** matrix, int n); void free_matrix(TMatrix** matrix); void fill_matrix(TMatrix* matrix, int n); void print_matrix(TMatrix* matrix, int n); TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2, int n); TMatrix* add_const(TMatrix* matrix, int n); TMatrix* multi_const(TMatrix* matrix, int n); TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2, int n); #endif <file_sep>#include "stdafx.h" int main() { system("chcp 1251"); try { string path = enter_path(); vacancyLib vacancyData(path); vacancyLib searchedVacancyData; searchedVacancyData = vacancyData.search_vacancy(); cout << searchedVacancyData; } catch (const int ex) { return 1; } return 0; }<file_sep>#include <iostream> #include "Container.h" #include "Client.h" using namespace std; int main() { string file_name; TProductsDatabase database(file_name); cout << database; work_with_client(database); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include "header.h" int main() { int number; product* shipment; date* data; number = cntLines("sklad.txt"); // printf("%d\n",number); // _getch(); allocate_stock(&shipment, &data, number); fill_shipment(shipment, data, number); find_null(shipment, data, number); free_stock(&shipment, &data, number); return 0; }<file_sep>#ifndef _OUTLET_H #define _OUTLET_H #include <string> #include <vector> using namespace std; enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; struct Time { int hour; int minute; bool operator==(const Time& other) const; }; struct address { string street; int house_number; }; // структура для хранения рабочих дней магазина struct workingDays { vector<Day> days; vector<Time> opens; vector<Time> closes; }; // структура для хранения сведений о торговой точке struct outlet { string name; address address; int phone_number; string specialization; workingDays working_days; friend ostream& operator<<(ostream& os, const outlet& outlet); }; struct buyerGuide {//хранит все торговые точки buyerGuide(const vector<outlet>& o); buyerGuide(const string& filename); ~buyerGuide(); vector<outlet> outlets; buyerGuide show_24_outlets(); friend ostream& operator<<(ostream& os, const buyerGuide& bg); }; string start(); #endif // !_OUTLET_H <file_sep>#ifndef _SORT_H #define _SORT_H void bubbleSort(unsigned long* a, int size, int* index, char** fname); void swap(unsigned long* x, unsigned long* y); void quicksort(unsigned long* list, int m, int n, int* index); void merge(unsigned long* a, unsigned long* tmp, int left, int mid, int right, unsigned long* index, unsigned long* itmp); void msort(unsigned long* a, unsigned long* tmp, int left, int right, unsigned long* index, unsigned long* itmp); #endif // !_SORT_H <file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" int main() { int i,j,n; Matrix *matrix_dynamic, *m1,*m2,*res; allocate_matrix(&matrix_dynamic, 2); fill_matrix(matrix_dynamic); print_matrix(matrix_dynamic); free_matrix(&matrix_dynamic); allocate_matrix(&m1, 2); allocate_matrix(&m2, 2); fill_matrix(m1); fill_matrix(m2); printf("\n"); res = addition_matrix(m1, m2); print_matrix(res); free_matrix(&res); printf("\n"); res = addition_const(m1, 5.2f); print_matrix(res); free_matrix(&res); printf("\n"); res = multi_const(m1, 3.4f); print_matrix(res); free_matrix(&res); printf("\n"); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#include <stdlib.h> #include <stdio.h> #include "matrix.h" void alloc_matrix(matrix** m, int n) { *m = (matrix*)malloc(1 * sizeof(matrix)); (*m)->x = (double*)malloc(sizeof(double) * n * n); (*m)->n = n; } void free_matrix(matrix** m) { free((*m)->x); free(*m); } void fill_matrix(matrix* m) { int i = 0; for (; i < m->n * m->n; i++) { scanf("%lf", &(m->x[i])); } } void print_matrix(matrix* m) { int i, j; for (i = 0; i < m->n; i++) { for (j = 0; j < m->n; j++) printf("%3.lf ", m->x[i * m->n + j]); printf("\n"); } } matrix* add_matrix(matrix* m1, matrix* m2) { if (m1->n != m2->n) { printf("ERROR: Incorrect vector sizes.\n"); return NULL; } matrix* res; alloc_matrix(&res, m1->n); for (int i = 0; i < m1->n * m1->n; i++) res->x[i] = (m1->x)[i] + (m2->x)[i]; return res; } matrix* add_scalar(matrix* m1, double c) { matrix* res; alloc_matrix(&res, m1->n); for (int i = 0; i < m1->n * m1->n; i++) res->x[i] = m1->x[i] + c; return res; } matrix* multi_matrix(matrix* m1, matrix* m2) { if (m1->n != m2->n) { printf("ERROR: Incorrect vector sizes.\n"); return NULL; } matrix* res; alloc_matrix(&res, m1->n); int j, l, n = m1->n; for (int i = 0; i < n; i++) { for (j = 0; j < n; j++) { res->x[i * n + j] = 0.0; for (l = 0; l < n; l++) { res->x[i * n + j] += (m1->x[i * n + l]) * (m2->x[l * n + j]); } } } return res; } matrix* multi_scalar(matrix* m1, double c) { matrix* res; alloc_matrix(&res, m1->n); for (int i = 0; i < (m1->n) * (m1->n); i++) res->x[i] = m1->x[i] * c; return res; }<file_sep>#include <iostream> #include <fstream> #include <sstream> #include "outlet.h" ostream& operator<<(ostream& os, const outlet& outlet) {//перегрузка вывода для объекта struct outlet const char* dayNames[] = { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" }; os << "Name: " << outlet.name << endl; os << "Address: " << outlet.address.street << ", " << outlet.address.house_number << endl; os << "Phone Number: " << outlet.phone_number << endl; os << "Specialization: " << outlet.specialization << endl; os << "Working Days: " << endl; for (int i = 0; i < outlet.working_days.days.size(); i++) { os << dayNames[outlet.working_days.days[i]] << ": " << outlet.working_days.opens[i].hour << ":" << outlet.working_days.opens[i].minute << " - " << outlet.working_days.closes[i].hour << ":" << outlet.working_days.closes[i].minute << endl; } os << endl; return os; } bool Time::operator==(const Time& other) const {//перегрузка оператора сравнения return hour == other.hour && minute == other.minute; } string start() {//запрашивает у пользователя путь к файлу до тех пор, пока не будет введён путь к существующему файлу string path; while (true) { cout << "Enter the file path..." << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } cout << "ERROR: Could not open file!\n" << endl; } } buyerGuide::buyerGuide(const vector<outlet>& o) {//конструктор с параметром outlets = o; } ostream& operator<<(ostream& os, const buyerGuide& bg) {//перегрузка вывода для buyerGuide for (auto& o : bg.outlets) { cout << o; } return os; } buyerGuide::buyerGuide(const string& path) { ifstream infile(path); string line; while (getline(infile, line)) { istringstream iss(line); string name, street, specialization, phone_number, house_number; getline(iss, name, ',');//-----------------------------------| getline(iss, street, ',');// getline(iss, house_number, ',');// просто считываем данные getline(iss, phone_number, ',');// getline(iss, specialization, ',');//-------------------------| outlet o = { name, {street, stoi(house_number)}, stoi(phone_number), specialization, {} };//создаём объект "магазин" string day_time; while (getline(iss, day_time, ',')) {//работаем с днями istringstream dt(day_time); string day, opens, closes; getline(dt, day, ':'); Day currentDay; if (day == "Monday") currentDay = Monday; else if (day == "Tuesday") currentDay = Tuesday; else if (day == "Wednesday") currentDay = Wednesday; else if (day == "Thursday") currentDay = Thursday; else if (day == "Friday") currentDay = Friday; else if (day == "Saturday") currentDay = Saturday; else if (day == "Sunday") currentDay = Sunday; getline(dt, opens, '-'); getline(dt, closes, '-'); o.working_days.days.push_back(currentDay); o.working_days.opens.push_back({ stoi(opens.substr(0, 2)), stoi(opens.substr(3, 2)) }); o.working_days.closes.push_back({ stoi(closes.substr(0, 2)), stoi(closes.substr(3, 2)) }); } outlets.push_back(o);//запихиваем заполненный объект в вектор } infile.close(); } buyerGuide::~buyerGuide() {//деструктор, просто удаляет содержимое векторов for (auto& outlet : outlets) { outlet.working_days.closes.clear(); outlet.working_days.opens.clear(); outlet.working_days.days.clear(); } outlets.clear(); } buyerGuide buyerGuide::show_24_outlets() {//показывает магазины работающие 24/7 vector<outlet> all_time_shops; cout << "24-Hour Retail Outlets:\n" << endl; for (const auto& outlet : outlets) {//проходимся по всем торговым точкам for (int i = 0; i < outlet.working_days.days.size(); i++) { if (outlet.working_days.opens[i] == outlet.working_days.closes[i]) { all_time_shops.push_back(outlet); break; } } } buyerGuide bg(all_time_shops); return bg; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include "fileProcessing.h" #include "userSide.h" int main() { setlocale(LC_ALL, "Russian"); SetConsoleCP(1251); char fname[] = "VUZ.csv"; int c_univ; University_t* uns; // counting the number of univercity c_univ = find_num_univ(fname); // allocating all array of university structs uns = fill_univ(fname, c_univ); working_with_user(uns, c_univ); free_memory(uns, c_univ); return 0; }<file_sep>#include <iostream> #include <fstream> #include <cstring> #include <string> #include <iomanip> #include "header.h" using namespace std; Product::Product() { name = ""; unit = ""; price = 0.0f; number = 0; data.day = 0; data.month = 0; data.year = 0; } Product::Product(string name, string unit, double price, int number, int day, int month, int year) { this->name = name; this->unit = unit; this->price = price; this->number = number; this->data.day = day; this->data.month = month; this->data.year = year; } int cntLines(const string filename) { string line; int f = 0; ifstream file(filename); // окрываем файл для чтения if (!file.is_open()) throw "File open error"; if (file.is_open()) { while (getline(file, line)) { // cout << line << endl; f++; } } return f; } void allocate_stock(Product*& p, int size) { p = new Product[size]; } void Product::SetRes(string _name, string _unit, double _price, int _number, int _day, int _month, int _year) { name = _name; unit = _unit; price = _price; number = _number; data.day = _day; data.month = _month; data.year = _year; } void fill_sklad(Product*& p, int size, const string filename) { string line; char str[200]; char* istr; ifstream file(filename); // окрываем файл для чтения int j = 0, flag = 0; if (!file.is_open()) throw "File open error"; if (file.is_open()) { while (j != size) { while (getline(file, line)) { string _name = " "; string _unit=" "; double _price=0; int _number=0; int _day=0; int _month=0; int _year=0; strcpy(str, line.c_str()); istr = strtok(str, ";/"); flag++; if (flag == 1) { _name = string(istr); // cout << _name << endl; } while (istr != NULL) { istr = strtok(NULL, ";/"); flag++; if (flag == 2) { _unit = string(istr); // cout << _unit << endl; } if (flag == 3) { _price = atoi(istr); // cout << _price << endl; } if (flag == 4) { _number = atoi(istr); // cout << _number << endl; } if (flag == 5) { _day = atoi(istr); // cout << _day << endl; } if (flag == 6) { _month = atoi(istr); // cout << _month << endl; } if (flag == 7) { _year = atoi(istr); // cout << _year << endl; p[j].SetRes(_name, _unit, _price, _number, _day, _month, _year); } } flag = 0; j++; } } } file.close(); // закрываем файл } ostream& operator <<(ostream& stream, const Product& p) { stream << p.name << " " << p.unit << " " << p.price<<" "<<p.number <<" "<<setw(2) << setfill('0') << p.data.day << "." << setw(2) << setfill('0') << p.data.month << "." << p.data.year << endl; return stream; } void find_NULL(Product*& p, int size) { for (int i = 0; i < size; i++) { if (p[i].number == 0) { cout << p[i].name << "\t" << p[i].unit << "\t" << p[i].price << "\t" << p[i].number<<"\t"; cout<<setw(2)<<setfill('0')<<p[i].data.day << "." << setw(2) << setfill('0')<< p[i].data.month << "." << p[i].data.year << endl; } } } void free_stock(Product*& p) { delete[]p; }<file_sep>#include <iostream> #include <string> #include "products.h" #include "receipt.h" #include "database.h" #include "display.h" #include "utility.h" using namespace std; TReceiptLine::TReceiptLine() { count = 0; sum = 0; product = NULL; } bool TReceiptLine::Scan(TDataBase& data, const string& code, const int _count) { int ind = data.Check(code); if (ind == -1) { cout << "Неправильный штрихкод. Побробуйте отсканировать другой." << endl; int tmp; cout << "\nНажмите любую клавишу, чтобы продолжить.\n" << endl; cin >> tmp; return false; } product = data.GetProduct(ind); count = _count; sum = (*product).GetCost() * count; return true; } bool TReceiptLine::operator==(const TReceiptLine& rl) { if (product == rl.product) return true; return false; } const TReceiptLine& TReceiptLine::operator=(const TReceiptLine& rl) { if (this == &rl) return (*this); product = rl.product; count = rl.count; sum = rl.sum; return (*this); } void TReceiptLine::AddCount(int _count) { if (_count > 0) { count += _count; sum += (*product).GetCost()* _count; } } // ===================================================================== // TReceipt TReceipt::TReceipt() { index = 0; sum = 0; money = 0; odd_money = 0; SetCLOCK(); } void TReceipt::Add(const TReceiptLine& product, int _count) { int i = products._find(product); if (i == -1) { products.Add(product); index = products.Count() - 1; sum += products[products.Count() - 1].GetSum(); } else { products[i].AddCount(_count); index = i; sum += product.GetCost() * _count; } } void TReceipt::Del(int _index) { sum -= products[_index].GetSum(); products.Del(_index); index--; if (index < 0) index = 0; if (index > products.Count()) index = products.Count(); } void TReceipt::Del(const TReceiptLine& product) { int ind = products._find(product); sum -= products[ind].GetSum(); products.Del(ind); index--; if (index < 0) index = 0; if (index > products.Count()) index = products.Count(); } void TReceipt::Change(int ind, int _count) { products[ind].AddCount(_count); } void TReceipt::Cart() { cout << "Ваша корзина:" << endl; for (int i = 0; i < products.Count(); i++) cout << i+1 << ". " << products[i] << endl; } int TReceipt::Count() const{ return products.Count(); } void TReceipt::SetCode(int _code) { code = date.StringDate() + intToString(_code, 3, '0'); } void TReceipt::Show() const { // Показывает данные чека на мониторе cout << products[index] << endl; } void TReceipt::Payment(TDataBase& data, const double _money) { // Печатает чек, т.е. заканчивается работа с данным покупателем money = _money; odd_money = money - sum; // Формирование чека // dsp::Line(); cout << "Чек #" << code << endl; cout << date << ' ' << time << endl; for (int i = 0; i < products.Count(); i++) cout << i + 1 << ". " << products[i] << endl; cout << "\nИтоговая сумма к оплате: " << sum << " руб." << endl; cout << "Вы оплатили: " << money << " руб." << endl; cout << "Ваша сдача: " << odd_money << " руб.\n" << endl; cout << "СПАСИБО ЗА ПОКУПКУ! ЖДЕМ ВАС СНОВА!!!" << endl; dsp::Line(); // Внесение изменений в базу данных // for (int i = 0; i < products.Count(); i++) { string pcode = products[i].GetCode(); int dind = data.Check(pcode); data.GetProductCount(dind) -= products[i].GetCount(); } } void TReceipt::Clear() { products.Clear(); index = 0; sum = 0; } void TReceipt::LastScan() { // Показывает продукт, который сейчас выбран if (Count()) cout << products[index] << endl; } int TReceipt::FindCount(const TReceiptLine& rl) { int ind = _find(rl); if (ind == -1) return 0; else return products[ind].GetCount(); } const TReceipt& TReceipt::operator=(const TReceipt& r) { if (this == &r) return (*this); index = r.index; products = r.products; date = r.date; time = r.time; sum = r.sum; money = r.money; odd_money = r.odd_money; return *this; } bool TReceipt::operator==(const TReceipt& r) const { if (this == &r) return true; return false; } TReceiptLine TReceipt::operator[](int ind) { return products[ind]; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include <windows.h> #include "fileProcessing.h" int find_num_univ(char fname[]) { char line[MAX_LINE_LEN]; int c = 0; FILE* fp; fp = fopen(fname, "r"); if (fp == NULL) { printf("No such file"); return 1; } while (fgets(line, MAX_LINE_LEN, fp) != NULL) { c++; } fclose(fp); return c; } University_t* fill_univ(char fname[], int c) { char line[1000]; int i = 0; University_t* uns = (University_t*)malloc(sizeof(University_t) * c); FILE* fp; fp = fopen(fname, "r"); if (fp == NULL) { printf("No such file"); return 1; } while (fgets(line, MAX_LINE_LEN, fp) != NULL) { int iter; strcpy(uns[i].name, strtok(line, ";")); uns[i].n_spec = atoi(strtok(NULL, ";")); uns[i].specs = (Spec_t*)malloc(sizeof(Spec_t) * uns[i].n_spec); for (iter = 0; iter < uns[i].n_spec; iter++) { int j; strcpy(uns[i].specs[iter].name, strtok(NULL, ";")); uns[i].specs[iter].n_form = atoi(strtok(NULL, ";")); uns[i].specs[iter].forms = (EducationalForm*)malloc(uns[i].specs[iter].n_form * sizeof(EducationalForm)); uns[i].specs[iter].costs = (int*)malloc(uns[i].specs[iter].n_form * sizeof(int)); uns[i].specs[iter].examScores = (int*)malloc(uns[i].specs[iter].n_form * sizeof(int)); for (j = 0; j < uns[i].specs[iter].n_form; j++) { char type_form[MAX_NAME]; strcpy(type_form, strtok(NULL, ";")); if (!strcmp(type_form, "дневная")) { uns[i].specs[iter].forms[j] = DNEV; uns[i].specs[iter].examScores[j] = atoi(strtok(NULL, ";")); uns[i].specs[iter].costs[j] = atoi(strtok(NULL, ";")); } if (!strcmp(type_form, "вечерняя")) { uns[i].specs[iter].forms[j] = VECHER; uns[i].specs[iter].examScores[j] = atoi(strtok(NULL, ";")); uns[i].specs[iter].costs[j] = atoi(strtok(NULL, ";")); } if (!strcmp(type_form, "заочная")) { uns[i].specs[iter].forms[j] = ZAOCH; uns[i].specs[iter].examScores[j] = atoi(strtok(NULL, ";")); uns[i].specs[iter].costs[j] = atoi(strtok(NULL, ";")); } } } i++; } return uns; fclose(fp); } void free_memory(University_t* uns, int c) { int i, j; for (i = 0; i < c; i++) { for (j = 0; j < uns[i].n_spec; j++) { free(uns[i].specs[j].forms); free(uns[i].specs[j].examScores); free(uns[i].specs[j].costs); } free(uns[i].specs); } free(uns); }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #define N_ARR 10 #define N_CODE 5 #define N_NAME 6 /* Bread, Milk, Water, Tomato, Pickle, Salt, Pepper, Shugar, Beer, Jagermeister */ int i, j, total_cost = 0; char codes[N_ARR][N_CODE] = { "0001", "1213", "2424", "3776", "4637", "5180", "6878", "7352", "8545", "9999" }; char name[N_ARR][N_NAME] = { "Bread ", "Milk ", "Water ", "Tomato", "Pickle", "Salt ", "Pepper", "Spices", "Beer ", "Jagerm" }; int cost[N_ARR] = { 40, 55, 70, 80, 100, 120, 130, 150, 200, 3000 }; int discount[N_ARR] = { 5, 10, 15, 20, 22, 25, 30, 35, 40, 45 }; int cost_d[N_ARR] = { 33, 38, 60, 63, 85, 94, 98, 104, 140, 1650 }; int counters[N_ARR] = { 0 }; int chr_int(char x) { int a; a = (int)x - 48; if (0 <= a && a <= 9) return a; else return -1; } int check(char* c) { // 1 - in array; 0 - NOT in array int i; for (i = 0; i < N_ARR; i++) if (!(strncmp(c, codes[i], N_CODE))) return 1; return 0; } void print_item(int item[]) { printf("| "); for (i = 0; i < N_NAME; i++) printf("%c", name[item[0]][i]); printf(" | "); printf("%4d | %4d%% | %10d |\n", cost[item[1]], discount[item[2]], cost_d[item[3]]); counters[item[0]]++; total_cost += cost_d[item[3]]; } int main() { int S, S_d, k, num = 0, flag = 1; int item[N_CODE]; char* inp; printf("Welcome to the cash register!\n\n"); printf("Please scan your items (enter his 4-digit code).\n"); printf("To finish scanning, enter 0.\n\n"); printf("| NAME | COST | DISC. | COST_DISC. |\n"); do { inp = (char*)malloc(10); gets(inp); flag = strcmp(inp, "0"); if (check(inp)) { for (i = 0; i < N_CODE; i++) item[i] = chr_int(*(inp + i)); // 0 - id_name, 1 - id_cost, 2 - id_disc, 3 - id_cost_d; print_item(item); } else if (flag) printf("There is no such code, try another one.\n"); free(inp); } while (flag); //The_check: printf("\n\n=====================================================================\n"); printf("| # | NAME | COST OF 1 | COST_D OF 1 | COUNT | DISCOUNT | COST |\n"); for (i = 0; i < N_ARR; i++) if (counters[i] != 0) { num++; k = counters[i]; S = cost[i] * k; S_d = S - cost_d[i] * k; printf("| %2d | ", num); for (j = 0; j < N_NAME; j++) printf("%c", name[i][j]); printf(" | "); printf("%9d | %11d | %5d | %8d | %6d |", cost[i], cost_d[i], k, S_d, cost_d[i] * k); printf("\n"); } printf("=====================================================================\n"); printf("Total cost: %d rub.\n", total_cost); printf("=====================================================================\n"); return 0; }<file_sep> #include <stdio.h> int main() { double h, w, d, back_wall, side_wall, upper_wall, shelves, doors, k; double density_wood = 550; double density_DSP = 650; double density_DVP = 800; int i = 0; printf("Enter wardrobe dimensions: height, width, depth: \n"); scanf_s("%lf %lf %lf", &h, &w, &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) { printf("something went wrong...\n"); return 1; } k = h-3; h *= 0.01; w *= 0.01; d *= 0.01; back_wall = h * w * 0.005 * density_DVP; side_wall = h * d * 0.015 * 2 * density_DSP; upper_wall = (w-0.03) * d * 0.015 * 2 * density_DSP; doors = h * w * 0.01 * density_wood; while (k >= 41.5) { k -= 41.5; i++; } shelves = d * (w-0.03) * 0.015 * i * density_DSP; printf("overall wardrobe weight is %lf", back_wall + side_wall + upper_wall + shelves + doors); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #include "Header.h" #define MAX_PATH 100 // Max path length #define MAX_NAME 20 // Max name of banks length void input_path(char* path) { printf("Input a path with file type: \n"); scanf("%s", path); printf("\n \nYour path: \n%s \n\n", path); } void print_data(BanksData* data, int n) { printf("Yours data: \n\n"); for (int i = 0; i < n; i++) { printf("%s %s %d \n", data[i].name, data[i].ownership, data[i].count); for (int j = 0; j < data[i].count; j++) { printf("%s %d %f\n", data[i].deposits[j].name, data[i].deposits[j].period, data[i].deposits[j].conditions); } printf("\n"); } } void freedata(BanksData** data, int n) { for (int i = 0; i < n; i++) { free((*data)[i].name); free((*data)[i].ownership); for (int j = 0; j < (*data)[i].count; j++) { free((*data)[i].deposits[j].name); } free((*data)[i].deposits); } } void input_user_data(int* user_year, float* user_money) { do { printf("For how long would you like to open a deposit? \n"); scanf("%d", &(*user_year)); if ((*user_year) <= 0 || (*user_year) >= 100) { printf("Wrong period, try again\n"); } } while ((*user_year) <= 0 || (*user_year) >= 100); do { printf("How much would you like to open a deposit for (rubles)? \n"); scanf("%f", &(*user_money)); if ((*user_money) <= 0) { printf("Wrong period, try again\n"); } } while ((*user_money) <= 0); } int read(BanksData** data) { char* path = (char*)malloc(sizeof(char) * MAX_PATH); input_path(path); FILE* file; file = fopen(path, "r"); if (file == NULL) { printf("\n Uncorrect path\n"); return 0; } int n; fscanf(file, "%d", &n); (*data) = (BanksData*)malloc(sizeof(BanksData) * n); for (int i = 0; i < n; i++) { (*data)[i].name = (char*)malloc(sizeof(char) * MAX_NAME); (*data)[i].ownership = (char*)malloc(sizeof(char) * MAX_NAME); fscanf(file, "%s %s %d", (*data)[i].name, (*data)[i].ownership, &(*data)[i].count); (*data)[i].deposits = (Deposit*)malloc(sizeof(Deposit) * ((*data)[i].count + 5)); for (int j = 0; j < (*data)[i].count; j++) { (*data)[i].deposits[j].name = (char*)malloc(sizeof(char) * MAX_NAME); if ((*data)[i].deposits[j].name == NULL) { printf("bee"); } fscanf(file, "%s %d %f", (*data)[i].deposits[j].name, &((*data)[i].deposits[j].period), &((*data)[i].deposits[j].conditions)); } } free(path); fclose(file); return n; } pair comparing(BanksData* data, int n, int user_year, int user_money) { float profit = 0; int id1 = -1; int id2 = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < data[i].count; j++) if (user_year % data[i].deposits[j].period == 0) { float tmp_profit = user_money * (pow(1 + (data[i].deposits[j].conditions * 0.01), user_year));// formule if (profit < tmp_profit) { profit = tmp_profit; id1 = i; id2 = j; } } } pair q; q.id1 = id1; q.id2 = id2; q.profit = profit; return q; }<file_sep>#ifndef _HUser_Matrixh_ #define _HUser_Matrixh_ typedef struct { float** matrix; int size; } CMatrix; void allocate_matrix(CMatrix** data, int n); void free_matrix(CMatrix** data); void fill_matrix(CMatrix* data); void mprint(CMatrix* data); CMatrix* multi_matrix(CMatrix* vector1, CMatrix* vector2); CMatrix* add_matrix(CMatrix* vector1, CMatrix* vector2); CMatrix* add_const(CMatrix* data, float c); CMatrix* multi_const(CMatrix* data, float c); #endif<file_sep>#include "outlet.h" #include <iostream> using namespace std; int main() { string path = start(); buyerGuide guide(path); buyerGuide all_time_shops = guide.show_24_outlets(); cout << all_time_shops; return 0; }<file_sep>#ifndef _SORT_H #define _SORT_H void ChooseSort(int*, int len, int*); void merge(int*, int, int, int, int*); void mergeSort(int*, int, int, int*); void QuickSort(int*, int, int, int*); #endif <file_sep>#include <stdio.h> #include <stdlib.h> #define S 5 void main() { int i, j, n, x = 0, y, a[S], b[S], k, z, r, m, bulls, cows; do { printf("Enter the length of the guessed number n="); scanf_s("%d", &n); } while ((n < 2) || (n > 5)); srand((unsigned int)time(NULL)); for (i = 0; i < n; i++) { a[i] = rand() % 10; } i = 0; while (i < n) { r = rand() % 10; for (j = 0; j < i; j++) { if (a[j] == r) break; } if (j == i) a[i++] = r; } for (i = 0; i < n; i++) { k = a[i]; for (j = n - 1; j > i; j--) k *= 10; x = x + k; } printf("x=%d\n", x); printf("I guessed the number. Try to guess it\n"); scanf_s("%d", &y); while (x != y) { i = 1; bulls = 0; cows = 0; while (y > 0) { m = y % 10; for (j = 0; j < n; j++) { if (a[j] == m) { if (j == n - i) bulls++; else cows++; } } y /= 10; i++; } printf("%d bull(s), %d cow(s)\n", bulls, cows); scanf_s("%d", &y); } printf("Guessed"); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <conio.h> int main() { float xc1, yc1, xc2, yc2,r1,r2,sc,d; printf("Enter the coordinates of the center of the first circle: "); scanf("%f %f", &xc1, &yc1); printf("Enter the coordinates of the center of the second circle: "); scanf("%f %f", &xc2, &yc2); printf("Enter the radius of the first circle: "); scanf("%f", &r1); printf("Enter the radius of the second circle: "); scanf("%f", &r2); sc = sqrt(((xc2 - xc1)*(xc2-xc1)) + ((yc2 - yc1)*(yc2 - yc1))); d = sc - (r1 + r2); if (sc == 0 && r1 == r2) { printf("the circles are congruent\n"); } else if (d== 0) { printf("the circles are touching\n"); } else if (d > 0) { printf("The circles are distant from each other\n"); } else if (sc < abs(r1 - r2)) { printf("One circle inside another\n"); } else if (sc == abs(r1-r2)) { printf("The circles have one common point\n"); } else { printf("The circles intersect at two points\n"); } getchar(); return 0; }<file_sep>/* Определить структуру для представления полинома произвольной степени (полином представляется набором коэффициентов). Реализовать операции сложения, умножения, вычитания полиномов, а также вычисления значения полинома для заданного значения аргумента, дифференцирования полинома. */ #ifndef _POLYNOM_H #define _POLYNOM_H typedef struct { float* coeff; int degree; } TPolynom; void allocate_polynom(TPolynom** polynom, int degree); TPolynom* allocate_polynom_copy(TPolynom** p, TPolynom** tmp); void free_polynom(TPolynom** polynom); void read_file(TPolynom*** p, int* n); void fill_polynom(TPolynom* p, FILE* file); void print_polynom(TPolynom* p); TPolynom* plus_polynom(TPolynom* p1, TPolynom* p2); TPolynom* multi_polynom(TPolynom* p1, TPolynom* p2); TPolynom* minus_polynom(TPolynom* p1, TPolynom* p2); TPolynom* diff_polynom(TPolynom* p); float value_polynome(TPolynom* p, float _x); #endif // !_POLYNOM_H<file_sep>#ifndef _HEADER #define _HEADER using namespace std; class Data { private: int day; int month; int year; public: int getMonth()const { return month; } void setMonth(int month1) { month = month1; } int getDay()const { return day; } void setDay(int day1) { day = day1; } int getYear()const { return year; } void setYear(int year1) { year = year1; } Data() { day = 0; month = 0; year = 0; } Data(int d, int m, int y) { day = d; month = m; year = y; } }; class Owner { private: string name; string surname; string patronymic; string carnum; unsigned long gibdd; string phnum; unsigned long tehpas; Data date; public: void setData(int a, int b, int c) { date.setDay(a); date.setMonth(b); date.setYear(c); } friend istream& operator>>(istream& in, Owner& o); friend ostream& operator<<(ostream& out, const Owner& o); unsigned long getGibdd()const { return gibdd; } }; Owner* read_inf(int& n); void print_inf(Owner* o, int n); Owner* search_owner(Owner* o, int& n, int& k); #endif<file_sep>#ifndef _HEADER_H_ #define _HEADER_H_ #include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include "Container.h" #include "GlobalFunctions.h" #include "Product.h" #include "Base.h" using namespace std; class Cart { private: Product *product; int count; double cost; public: Cart() { count = 0; cost = 0; product = nullptr; } Cart(const Product& pr, const int& ncount,const double& ncost = 0) { product = new Product; *product = pr; count = ncount; cost = ncost; } friend ifstream& operator>>(ifstream& buf, Cart& Date) { if (Date.product == nullptr) Date.product = new Product; buf >> *(Date.product) >> Date.count >> Date.cost; return buf; } friend istream& operator>>(istream& buf, Cart& Date) { if (Date.product == nullptr) Date.product = new Product; buf >> *(Date.product) >> Date.count >> Date.cost; return buf; } friend ostream& operator<<(ostream& buf, const Cart& Date) { buf << *(Date.product) << Date.count << endl; return buf; } //bool operator != (Product tmp) { return (product != tmp.product); } bool operator == (const Cart& tmp) const; bool operator == (const Base& tmp) const; bool operator != (const Cart& tmp) const; bool operator == (const string& tmp) const; bool operator <= (const int& ncount) const; Cart& operator = (const Cart& tmp); Cart& operator += (const int& ncount); Cart& operator -= (const int& ncount); Product* get_product() const; int get_count() const; double get_cost() const; }; //Date struct Date { //int year, month, day, hour, min, sec; tm* timeinfo; void now(); }; //Receipt class Receipt { private: int num; int size; Date Date; NewContainer<Cart> cart; public: //constructors Receipt() { num = 0; size = 0; Date.timeinfo = NULL; } Receipt(const Receipt& receipt) { num = receipt.num; size = receipt.size; Date = receipt.Date; cart = NewContainer<Cart>(receipt.cart); } //overloaded operations /* friend istream& operator>>(istream& buf, Receipt& Date) { buf >> Date.num >> Date.size >> Date.cart; return buf; } */ friend ostream& operator<<(ostream& buf, Receipt& Date) { buf << "\nNumber of a receipt: " << Date.num << endl; buf << "Date: " << endl; Date.Date.now(); buf << "Products: \n"; for (int i = 0; i < Date.size; i++) { buf << Date.cart[i]; } buf << endl; return buf; } bool operator == (const Receipt& r) { return (size == r.size && cart == r.cart); } const Receipt& operator=(const Receipt& receipt); //functions void add(const Cart& product, const int& count = 1); void add(const Product& product, const int& count = 1); void remove(const Cart& product, const int& count); double sum() const; void print_cart() const; void pdata(); void set_num(const int& q); Cart* find(const Base& product) const; Cart* find(const string& product) const; int len() const; bool empty() const; }; #endif <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main() { float h, w, d; int count; double shelves, mass_backdoor, mass_sidewalk, mass_roof, mass_door, mass_shelves, mass; float density_wood = 640; float density_DSP = 800; float density_DVP = 750; printf("Enter cabinet height h"); scanf(" %f", &h); if ((h < 180) || (h > 220)) { printf("Incorrect data, valid values 180 cm < h < 220 cm"); return 0; } printf("Enter cabinet width w"); scanf(" %f", &w); if ((w < 80) || (w > 120)) { printf("Incorrect data, valid values 80 cm < w < 120 cm"); return 0; } printf("Enter cabinet depth d"); scanf(" %f", &d); if ((d < 50) || (d > 90)) { printf("Incorrect data, valid values 50 cm < d < 90 cm"); return 0; } h = h / 100; w = w / 100; d = d / 100; shelves = (h / 0.415) - 1.015; count = (int)shelves; mass_backdoor = h * w * 0.005 * density_DVP; mass_sidewalk = 2 * h * d * 0.015 * density_DSP; mass_roof = 2 * (w - 0.03) * d * 0.015 * density_DSP; mass_door = w * h * 0.01 * density_wood; mass_shelves = count * d * (w - 0.03) * density_DSP * 0.015; mass = mass_backdoor + mass_sidewalk + mass_roof + mass_door + mass_shelves; printf("Cabinet weight = %f kg\n", mass); return 0; }<file_sep>#include <stdio.h> #include "HUser_Matrix.h" #include <stdlib.h> void allocate_matrix(CMatrix** data, int new_size) { (*data) = (CMatrix*)malloc(sizeof(CMatrix)); (*data)->size = new_size; (*data)->matrix = (float**)malloc(sizeof(float*) * new_size); for (int i = 0; i < new_size; i++) { (*data)->matrix[i] = (float*)malloc(sizeof(float) * new_size); } } void fill_matrix(CMatrix* data) { int n = data->size; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("Input a number from %d column and %d row ", i+1, j+1); scanf("%f", &data->matrix[i][j]); } } } void mprint(CMatrix* data) { printf("\n"); int n = data->size; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%f ", data->matrix[i][j]); } printf("\n"); } } void free_matrix(CMatrix** data) { int size = (*data)->size; for (int i = 0; i < size; i++) { free((*data)->matrix[i]); } free((*data)->matrix); } CMatrix* add_const(CMatrix* data, float c) { CMatrix* res; int i = 0; int k = data->size; allocate_matrix(&res, k); for (; i < k; i++) { for (int j = 0; j < k; j++) { res->matrix[i][j] = data->matrix[i][j] + c; } } return res; } CMatrix* multi_const(CMatrix* data, float c) { CMatrix* res; int i = 0; int k = data->size; allocate_matrix(&res, k); for (; i < k; i++) { for (int j = 0; j < k; j++) { res->matrix[i][j] = data->matrix[i][j] * c; } } return res; } CMatrix *add_matrix(CMatrix *matrix1, CMatrix *matrix2) { CMatrix* res; int i = 0; int k1 = matrix1->size, k2 = matrix2->size; if (k1 != k2) { printf("ERROR: Matrix should have the same lenght.\n"); return NULL; } allocate_matrix(&res, k1); for (; i < k1; i++) { for (int j = 0; j < k2; j++) { res->matrix[i][j] = matrix1->matrix[i][j] + matrix2->matrix[i][j]; } } return res; } CMatrix* multi_matrix(CMatrix* matrix1, CMatrix* matrix2) { CMatrix* res; int i = 0; int k1 = matrix1->size, k2 = matrix2->size; if (k1 != k2) { printf("ERROR: Matrix should have the same lenght.\n"); return NULL; } allocate_matrix(&res, k1); for (; i < k1; i++) for (int j = 0; j < k1; j++) { res->matrix[i][j] = 0; for (int k = 0; k < k1; k++) res->matrix[i][j] += matrix1->matrix[i][k] * matrix2->matrix[k][j]; } return res; } <file_sep>#include <iostream> #include <fstream> #include <string> #include "Header.h" using namespace std; int main() { int n, k; Owner* owners = read_inf(n); cout <<"number of owners =" << n << endl << endl; print_inf(owners, n); Owner* owner1 = search_owner(owners, n, k); print_inf(owner1, k); delete[] owners; delete[] owner1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include "functions.h" #include <memory.h> #include <string.h> void scanstring(char** tmpstr,FILE* file) { fgets(*tmpstr, 350, file); } void set_data(char** data, const char* value) { *data = (char*)malloc(strlen(value) + 1); strcpy(*data, value); } void struct_free(struct EmployeesInfo_t* g_empls, struct Pasports_t* g_pspts) { free(g_empls->name); free(g_empls->appnt); free(g_empls->edu); free(g_empls->spec); free(g_empls->unit); free(g_pspts->auth); free(g_pspts->issue); free(g_pspts); free(g_empls); } void* get_target(void* base, int size, int index) { return (void*)((char*)base + (size * index)); } void set_data_char(void* base, int size, int index, char* value) { char** target = (char**)get_target(base, size, index); *target = (char*)malloc(strlen(value)+1); strcpy(*target, value); } void set_data_int(void* base, int size, int index, int value) { int* target = (int*)get_target(base, size, index); *target = value; } void read_str(FILE* file, int n, void* target, size_t struct_size) { char str[350]; fgets(str, 350, file); char tmp[30]; for (int i = 0, g = 0; i < n; i++) { for (int j = g; j < g + 30; j++) { if (str[j] == ';') { tmp[j - g] = '\0'; g = j + 1; break; } tmp[j - g] = str[j]; } set_data_char(target, struct_size, i, tmp); } } void read_int(FILE* file, int n, void* target, size_t struct_size) { char str[350]; fgets(str, 350, file); for (int i = 0, g = 0; i < n; i++) { int tmp = 0; for (int j = g; j < g + 30; j++) { if (str[j] == ';') { g = j + 1; break; } tmp = tmp * 10 + (int)str[j] - 48; } set_data_int(target, struct_size, i, tmp); } } void allocstructmem(int n, char* filename, struct EmployeesInfo_t** g_empls, struct Pasports_t** g_pspts) { FILE* file = fopen(filename, "r"); if (file == NULL) { printf("error"); exit(ENFILE); } const size_t empl_size = sizeof(struct EmployeesInfo_t); const size_t pspts_size = sizeof(struct Pasports_t); *g_empls = malloc(empl_size * n); *g_pspts = malloc(pspts_size * n); char str[350]; int tmp[3]; struct EmployeesInfo_t* empls = *g_empls; struct Pasports_t* pspts = *g_pspts; read_str(file, n, &(empls->name), empl_size); read_int(file, n, &(pspts->series), pspts_size); read_int(file, n, &(pspts->number), pspts_size); read_str(file, n, &(pspts->auth), pspts_size); read_str(file, n, &(pspts->issue), pspts_size); fgets(str, 350, file); for (int i = 0, g = 0; i < n; i++) { (*g_pspts)[i].birth.day = ((int)str[g] - 48) * 10 + (int)str[g + 1] - 48; (*g_pspts)[i].birth.month = ((int)str[g + 3] - 48) * 10 + (int)str[g + 4] - 48; (*g_pspts)[i].birth.year = ((int)str[g + 8] - 48) * 10 + (int)str[g + 9] - 48; g += 11; } fgets(str, 350, file); for (int i = 0, g = 0; i < n; i++) { (*g_pspts)[i].reg.day = ((int)str[g] - 48) * 10 + (int)str[g + 1] - 48; (*g_pspts)[i].reg.month = ((int)str[g + 3] - 48) * 10 + (int)str[g + 4] - 48; (*g_pspts)[i].reg.year = ((int)str[g + 8] - 48) * 10 + (int)str[g + 9] - 48; g += 11; } read_str(file, n, &(empls->edu), empl_size); read_str(file, n, &(empls->spec), empl_size); read_str(file, n, &(empls->unit), empl_size); read_str(file, n, &(empls->appnt), empl_size); fgets(str, 350, file); for (int i = 0, g = 0; i < n; i++) { (*g_empls)[i].dateofappnt.day = ((int)str[g] - 48) * 10 + (int)str[g + 1] - 48; (*g_empls)[i].dateofappnt.month = ((int)str[g + 3] - 48) * 10 + (int)str[g + 4] - 48; (*g_empls)[i].dateofappnt.year = ((int)str[g + 8] - 48) * 10 + (int)str[g + 9] - 48; g += 11; } fgets(str, 350, file); for (int i = 0, g = 0; i < n; i++) { (*g_empls)[i].lastdate.day = ((int)str[g] - 48) * 10 + (int)str[g + 1] - 48; (*g_empls)[i].lastdate.month = ((int)str[g + 3] - 48) * 10 + (int)str[g + 4] - 48; (*g_empls)[i].lastdate.year = ((int)str[g + 8] - 48) * 10 + (int)str[g + 9] - 48; g += 11; } fclose(file); } void age_scan(int n, struct EmployeesInfo_t* g_empls, struct Pasports_t* g_pspts) { for (int i = 0; i < n; i++) { if ((g_pspts[i].birth.year<58) || ((g_pspts[i].birth.year == 58) && ((g_pspts[i].birth.month < 4) || ((g_pspts[i].birth.month == 4) && (g_pspts[i].birth.day <= 6))))) if (g_pspts[i].birth.day < 10) { printf("%s - 0%d.", g_empls[i].name, g_pspts[i].birth.day); if (g_pspts[i].birth.month < 10) printf("0%d.19%d\n", g_pspts[i].birth.month, g_pspts[i].birth.year); } else if (g_pspts[i].birth.month < 10) printf("%s - %d.0%d.19%d\n", g_empls[i].name, g_pspts[i].birth.day, g_pspts[i].birth.month, g_pspts[i].birth.year); else printf("%s - %d.%d.19%d\n", g_empls[i].name, g_pspts[i].birth.day, g_pspts[i].birth.month, g_pspts[i].birth.year); } } <file_sep>#ifndef _PERSON_H #define _PERSON_H #include <string> using namespace std; struct Address { string country; string region; string city; string district; string street; string house; string apartament; }; struct Date { int day; int month; int year; }; class Person { private: string surname; string name; string patronymic; string gender; string nation; Date date; string height; string weight; string num_phone; string postal_code; Address ad; public: Person(); Person(string surname, string name, string patronymic, string gender, string nation, int day, int month, int year, string height, string weight, string num_phone, string postal_code, string country, string region, string city, string district, string street, string house, string apartament); void set_info(const string& p_surname, const string& p_name, const string& p_patronymic, const string& p_gender, const string& p_nation, const int& p_day, const int& p_month, const int& p_year, const string& p_height, const string& p_weight, const string& p_num_phone, const string& p_postal_code, const string& p_country, const string& p_region, const string& p_city, const string& p_district, const string& p_street, const string& p_house, const string& p_apartament); string get_surname() { return surname; } string get_name() { return name; } friend ostream& operator<<(ostream& out, const Person& p); }; void read(Person** p, int n, string& f); void Sort(Person** p, int n); int cntStruct(string& f); void removeFirstN(string& str, int n); #endif // !_PERSON_H <file_sep>#include <stdlib.h> #include <stdio.h> #include "matrix.h" int main() { int n; double c1=5, c2=5; matrix* m; printf("Vvedite razmer kvadratnoy matrizi\n"); scanf("%d", &n); alloc_matrix(&m, n); fill_matrix(m); print_matrix(m); matrix* m1 = multi_scalar(m, c1); printf("Ymhojenie matrizi na %.3lf\n", c1); print_matrix(m1); matrix* m2 = add_scalar(m, c2); printf("Slojinie matrizi i %.3lf\n", c2); print_matrix(m2); matrix* m3 = multi_matrix(m1, m2); printf("Proizvedenie m1 i m2:\n"); print_matrix(m3); matrix* m4 = add_matrix(m1, m2); if (m4) { printf("Summa m1 i m2\n"); print_matrix(m4); } /*free_matrix(&m1);*/ //free_matrix(&m2); //free_matrix(&m3); //free_matrix(&m4); //free_matrix(&m); return 0; }<file_sep>#include <stdio.h> #define Chipboard 0.0008f #define Fiberboard 0.0008f #define Wood 0.0009f #define _CRT_SECURE_NO_WARNINGS int main() { float h, w, d, weight, weight_back, weight_side, weight_cover, weight_door, weight_shelf; //Input data printf("Input a height of the wardrope (180 <= h <= 220) : "); scanf("%f", &h); if (h > 220 || h < 180) { printf("You inputed uncorrect height "); return 0; } printf("Input a width of the wardrope(80 <= w <= 120) : "); scanf("%f", &w); if (w < 80 || w > 120) { printf("You inputed uncorrect height"); return 0; } printf("Input a deep of the wardrope (50 <= d <= 90) : "); scanf("%f", &d); if (d > 90 || d < 50) { printf("You inputed uncorrect deep"); return 0; } //Weight of the back wall weight_back = 0.5 * w * h * Fiberboard; //Weigh of the side walls weight_side = 2 * h * d * 1.5 * Chipboard; //Weight of the overhead cover weight_cover = 2 * (w-3) * d * 1.5 * Chipboard; //Weight of the doors weight_door = h * w * Wood; //Weight of the shelfs int n; n = h / 40; weight_shelf = (n - 1) * 1.5 * (w - 3) * d * Chipboard; weight = weight_back + weight_cover + weight_door + weight_shelf + weight_side; printf("The weight of the wardrobe is (kg) : "); printf("%.2f", weight); return 0; }<file_sep>#include "fileProcessing.h" Univ_database_t::Univ_database_t(const std::string& fname) { int i = 0; std::string line; count = try_to_open_file(fname); std::ifstream file(fname); univs = new University_t[count]; while (i < count) { getline(file, univs[i].name, ';'); getline(file, line, ';'); univs[i].n_spec = atoi(line.c_str()); univs[i].specs = new Spec_t[univs[i].n_spec]; for (int j = 0; j < univs[i].n_spec; j++) { getline(file, univs[i].specs[j].name, ';'); getline(file, line, ';'); univs[i].specs[j].n_form = atoi(line.c_str()); univs[i].specs[j].forms = new EducationalForm[univs[i].specs[j].n_form]; univs[i].specs[j].costs = new int[univs[i].specs[j].n_form]; univs[i].specs[j].examScores = new int[univs[i].specs[j].n_form]; for (int z = 0; z < univs[i].specs[j].n_form; z++) { std::string type_form; getline(file, line, ';'); type_form = line; if (type_form == "дневная") { univs[i].specs[j].forms[z] = DNEV; getline(file, line, ';'); univs[i].specs[j].examScores[z] = atoi(line.c_str()); getline(file, line, ';'); univs[i].specs[j].costs[z] = atoi(line.c_str()); } if (type_form == "вечерняя") { univs[i].specs[j].forms[z] = VECHER; getline(file, line, ';'); univs[i].specs[j].examScores[z] = atoi(line.c_str()); getline(file, line, ';'); univs[i].specs[j].costs[z] = atoi(line.c_str()); } if (type_form == "заочная") { univs[i].specs[j].forms[z] = ZAOCH; getline(file, line, ';'); univs[i].specs[j].examScores[z] = atoi(line.c_str()); getline(file, line, ';'); univs[i].specs[j].costs[z] = atoi(line.c_str()); } } } i++; file.get(); } file.close(); } Univ_database_t::Univ_database_t(int c) { count = c; univs = new University_t[count]; } Univ_database_t::Univ_database_t() { count = -1; univs = nullptr; } Univ_database_t::~Univ_database_t() { delete[]univs; } University_t::~University_t() { delete[]specs; } Spec_t::~Spec_t() { delete[]forms; delete[]examScores; delete[]costs; } University_t& Univ_database_t::operator[] (const int ind) { return univs[ind]; } std::ostream& operator<<(std::ostream& out, const University_t& un) { std::cout << "Информация о ВУЗе " << un.name << ":\n"; std::cout << "ВУЗ " << un.name << " имеет " << un.n_spec << " специальностей:\n"; for (int i = 0; i < un.n_spec; i++) { std::cout << " " << un.specs[i].name << std::endl; } return out; } std::ostream& operator<<(std::ostream& out, const Spec_t& s) { std::cout << "Название специальности: " << s.name << ":\n"; std::cout << "Колличество форм обучения: " << s.n_form << "\n"; for (int i = 0; i < s.n_form; i++) { std::string name_form; switch (s.forms[i]) { case 0: name_form = "Дневная"; case 1: name_form = "Вечерняя"; case 2: name_form = "Заочная"; } std::cout << " Форма обучения: " << name_form << std::endl; std::cout << " Стоимость: " << s.costs[i] << std::endl; std::cout << " Проходные баллы: " << s.examScores[i] << std::endl; } return out; } int Univ_database_t::find_num_univ(const std::string& fname) const { std::string line; int c = 0; std::ifstream file(fname); if (file.fail()) throw - 1; while (getline(file, line)) { c++; } file.close(); return c; } int Univ_database_t::try_to_open_file(const std::string& fname) { int c = -1; while (c == -1) { try { getline(std::cin, const_cast<std::string&>(fname)); c = find_num_univ(fname); } catch (int err) { std::cout << "Такого файла нет" << std::endl; } } return c; } Spec_t::Spec_t() { name = ""; n_form = 0; forms = nullptr; examScores = nullptr; costs = nullptr; } University_t::University_t() { name = ""; n_spec = 0; specs = nullptr; } Spec_t::Spec_t(const Spec_t& s) { name = s.name; n_form = s.n_form; forms = new EducationalForm[n_form]; costs = new int[n_form]; examScores = new int[n_form]; for (int i = 0; i < n_form; i++) { forms[i] = s.forms[i]; costs[i] = s.costs[i]; examScores[i] = s.examScores[i]; } } University_t::University_t(const University_t& u) { name = u.name; n_spec = u.n_spec; specs = new Spec_t[n_spec]; for (int i = 0; i < n_spec; i++) { specs[i] = u.specs[i]; } } Univ_database_t::Univ_database_t(const Univ_database_t& ud) { count = ud.count; univs = new University_t[count]; for (int i = 0; i < count; i++) { univs[i] = ud.univs[i]; } } int Univ_database_t::SearchVUZ(const std::string& name, University_t& u) const { for (int i = 0; i < count; i++) { if (univs[i].name == name) { u = univs[i]; return 1; } } return -1; } float University_t::ComputeAverageScore() const { float sum_examRes = 0, count = 0; for (int i = 0; i < n_spec; i++) { for (int j = 0; j < specs[i].n_form; j++) { sum_examRes += specs[i].examScores[j]; count++; } } return sum_examRes / count; } float University_t::ComputeAverageCost() const { float sum_costs = 0, count = 0; for (int i = 0; i < n_spec; i++) { for (int j = 0; j < specs[i].n_form; j++) { sum_costs += specs[i].costs[j]; count++; } } return sum_costs / count; } University_t& University_t::operator=(const University_t& u) { if (this != &u) { name = u.name; n_spec = u.n_spec; specs = new Spec_t[n_spec]; for (int i = 0; i < n_spec; i++) { specs[i] = u.specs[i]; } } return *this; } Spec_t& Spec_t::operator=(const Spec_t& s) { if (this != &s) { name = s.name; n_form = s.n_form; forms = new EducationalForm[n_form]; costs = new int[n_form]; examScores = new int[n_form]; for (int i = 0; i < n_form; i++) { forms[i] = s.forms[i]; costs[i] = s.costs[i]; examScores[i] = s.examScores[i]; } } return *this; } void University_t::SearchMinScoreSpeciality(std::string& spec_name, int& score, std::string& form) const { int min = 1000; EducationalForm edForm; std::string name_form, name_spec; for (int i = 0; i < n_spec; i++) { for (int j = 0; j < specs[i].n_form; j++) { if (specs[i].examScores[j] < min) { min = specs[i].examScores[j]; edForm = specs[i].forms[j]; name_spec = specs[i].name; } } } switch (edForm) { case 0: name_form = "Дневная"; case 1: name_form = "Вечерняя"; case 2: name_form = "Заочная"; } score = min; form = name_form; spec_name = name_spec; } int Univ_database_t::SearchSpecialties(const std::string& name, Spec_t*& specs, std::string*& names_univ) const { int c_spec = 0; for (int i = 0; i < count; i++) { for (int j = 0; j < univs[i].n_spec; j++) { if (univs[i].specs[j].name == name) c_spec++; } } specs = new Spec_t[c_spec]; names_univ = new std::string[c_spec]; int k = 0; for (int i = 0; i < count; i++) { for (int j = 0; j < univs[i].n_spec; j++) { if (univs[i].specs[j].name == name) { specs[k] = univs[i].specs[j]; names_univ[k] = univs[i].name; k++; } } } return c_spec; }<file_sep>#include <stdio.h> #include <math.h> int main() { float x1, x2, y1, y2, r1, r2, s, big_r, small_r; printf("Vvedite znachenie koordinate x1:"); scanf("%f", &x1); printf("Vvedite znachenie koordinate y1:"); scanf("%f", &y1); printf("Vvedite znachenie koordinate x2:"); scanf("%f", &x2); printf("Vvedite znachenie koordinate y2:"); scanf("%f", &y2); printf("Vvedite znachenie radiys1:"); scanf("%f", &r1); printf("Vvedite znachenie radiys2:"); scanf("%f", &r2); s = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); big_r = r1; if (r2 > big_r) { big_r = r2; small_r = r1; } else small_r = r2; if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("okrygnosti sovpadaut"); return 0; } if ((s<r1 + r2) && (s>big_r-small_r)) { printf("peresechenie v dvyx tochkax"); } if (s == r1 + r2) { printf("vneshnee kasanie"); } if (s == big_r - small_r) { printf("vnytrennee kasanie"); } if (s > r1 + r2) { printf("odna legit vne drygoi"); } if (s < big_r - small_r) { printf("odna legit vnytri drygoi"); } return 0; } <file_sep>#include "Header.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include <stdbool.h> int main() { int z=0,count=0,unic,i; char line[LINE],word[LINE],str[LINE]; char** unic_section=NULL; setlocale(LC_ALL, "Rus"); TBook* lib; count = count_books(str); if (count == -1) return 1; lib = (TBook*)malloc(sizeof(TBook) * count); read(str,lib); unic = count_unic(lib, count); unic_section= create_section(lib,unic,count); print_book(lib, count); print_choose_book(lib, count,unic, unic_section); free_unic(unic_section,unic); free_mas(lib, count); return 0; }<file_sep>#ifndef _Container_H_ #define _Container_H_ #include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> using namespace std; static int IndexError() { cout << "Wrong Index" << endl; return -1; } //Container template <typename Type> class NewContainer { private: int size; Type* elements; int max_size; int step; int position; void realloc() { max_size += step; if (elements == nullptr) { elements = new Type[max_size]; position = 0; size = 0; return; } if (max_size == 0) return; Type* tmp = new Type[max_size]; for (int i = 0; i < size; i++) { tmp[i] = elements[i]; } delete[] elements; elements = new Type[max_size]; for (int i = 0; i < size; i++) { elements[i] = tmp[i]; } position = size; delete[] tmp; } public: //constructors NewContainer() { size = 0; max_size = 0; step = 10; position = -1; elements = nullptr; } // Lengh of the nelements must be equal new_size NewContainer(const int& new_size, const Type*& nelements, int nstep = 10) { if (max_size < new_size + 1) { realloc(); } size = new_size; for (int i = 0; i < size; i++) { elements[i] = nelements[i]; } step = nstep; position = size; } NewContainer(const NewContainer<Type>& container) { size = container.size; if (container.max_size != 0) { if (max_size < container.size) { realloc(); } elements = new Type[container.max_size]; } for (int i = 0; i < container.size; i++) { elements[i] = container.elements[i]; } max_size = container.max_size; position = container.position; step = container.step; } //destructor virtual ~NewContainer() { if (elements != nullptr) delete[] elements; } //overloaded operations friend ifstream& operator>>(ifstream& buf, NewContainer<Type>& Date) { { buf >> Date.size; for (int i = 0; i < Date.size; i++) { if (Date.size+1 >= Date.max_size) Date.realloc(); buf >> Date.elements[i]; Date.next(); } return buf; } } friend istream& operator>>(istream& buf, NewContainer<Type>& Date) { { buf >> Date.size; for (int i = 0; i < Date.size; i++) { if (Date.size == Date.max_size) Date.realloc(); buf >> Date.elements[i]; Date.next(); } return buf; } } friend ostream& operator<<(ostream& buf, const NewContainer<Type>& Date) { for (int i = 0; i < Date.size; i++) { buf << Date.elements[i] << " "; } buf << endl; return buf; } Type& operator[](const int& index) const { if (index < 0 && index >= size) { throw IndexError(); } return elements[index]; } bool operator==(const NewContainer<Type>& container) const { if (size != container.size || max_size != container.max_size || step != container.step) return false; for (int i = 0; i < size; i++) { if (elements[i] != container.elements[i]) return false; } return true; } bool operator!=(const NewContainer<Type>& container) const { return !(*this == container); } const NewContainer<Type>& operator=(const NewContainer<Type>& container) { if (*this == container) return *this; if (max_size < container.size) { int tmp = step; step = max(container.max_size - max_size + 1, step); realloc(); step = tmp; } size = container.size; max_size = container.max_size; for (int i = 0; i < size; i++) { elements[i] = container.elements[i]; } position = container.position; step = container.step; return *this; } //getters Type* get_elements() const { return elements; } //setters void set_step(const int& nstep) { step = nstep; } void push(const Type& value, const int& index) { if (index < 0 && index >= size) { throw IndexError; } if (size + 1 >= max_size) realloc(); for (int i = size - 2; i >= index; i--) { elements[i + 1] = elements[i]; } elements[index] = value; position = size+1; size++; } void push_back(const Type& value) { if (size + 1 >= max_size) realloc(); elements[position] = value; position = size + 1; size++; } /* void push_front(const Type& value) { if (index < 0 && index >= size) { cout << "Wrong index" << endl; return; } if (size + 1 >= max_size) realloc(); for (int i = size, i >= 0; i--) { elements[i + 1] = elemnts[i]; } elements[0] = value; position = size + 1; size++; } */ void pop_id(const int& index) { if (index < 0 && index >= size) { throw IndexError; } if (size == 1) { elements = nullptr; return; } for (int i = index; i - 2 < size; i++) { elements[i] = elements[i+1]; } position = size - 1; size--; } void pop_value(const Type& value) { int k = find_id(value); if (k != -1) pop_id(k); throw IndexError; } /* void pop_back() { pop_id(size - 1); } void pop_front() { pop_id(0); } */ int len() const { return size; } template<typename Type1> // temlate for string. Why template? cuz NewContainer "must not know about different types" Type* find(const Type1& element) const { for (int i = 0; i < size; i++) { if (elements[i] == element) return &elements[i]; } return nullptr; } template<typename Type1> int find_id(const Type1& element) const { for (int i = 0; i < size; i++) { if (elements[i] == element) return i; } return -1; } static void read(const string& path,NewContainer<Type>& Date) { ifstream file(path); int count; file >> count; if (Date.size + count + 1 >= Date.max_size) Date.realloc(); for (int i = 0; i < count; i++) { file >> Date[i]; } Date.size = count; file.close(); } //Movements void next() { if (position + 1 < max_size && position != -1) position++; } void back() { if (position > 0) position--; } void reset() { position = 0; } bool is_end() const { return (position + 1 == max_size) ? true : false; } }; #endif<file_sep>#include <stdio.h> #include "matrix.h" int main() { TMatrix* matrix_d, * m1, * m2, * res; allocate_matrix(&matrix_d, 2); fill_matrix(matrix_d); print_matrix(matrix_d); free_matrix(&matrix_d); allocate_matrix(&m1, 2); allocate_matrix(&m2, 2); fill_matrix(m1); fill_matrix(m2); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); res = add_const(m1, 2); print_matrix(res); free_matrix(&res); res = multi_const(m1, 2); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); return 0; } <file_sep>#include <stdio.h>; #include "matrix.h"; #include <stdlib.h>; int main() { TMatrix* m1, *m2, *res; alloc_matrix(&m1, 2); alloc_matrix(&m2, 2); fill_matrix(m1); fill_matrix(m2); res = sum_matrix(m1,m2); print_matrix(res); free_matrix(&res); res = add_const(m1, 2.33); print_matrix(res); free_matrix(&res); res = multi_const(m1, 2.33); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#ifndef _LIB_H #define _LIB_H #include <string> #include <set> #include <vector> using namespace std; enum availability { available, not_available }; class CardIndex { private: vector <string> authors; string title; string publisher; string section; availability avb; float evaluation; public: CardIndex(const vector <string>& authors, const string& title, const string& publisher, const string& section, const availability avb, const float evaluation); ~CardIndex(); bool operator==(const string& otherTitle) const; bool operator!=(const string& otherTitle) const; friend ostream& operator<<(ostream& os, const CardIndex& card); string getTitle() const; string getSection() const; }; class Library { public: Library(const string& path); ~Library(); set <string> booksBySection(); vector <CardIndex> findBooks(const set <string>& sections); void getBook(const vector <CardIndex>& books); vector <CardIndex> getCards() const; private: vector <CardIndex> cards; }; string menu(); #endif // !_LIB_H <file_sep>#ifndef _CARS_H #define _CARS_H #include <string> #include <vector> using namespace std; struct Car { string brand; string color; string serial_number; string registration_number; string count_door; string year; string price; friend ostream& operator<<(ostream& output_stream, const Car& car); }; string GetFilePath(); Car ReadCarEntity(ifstream& file); Car FindOldestCar(const vector <Car>& cars); vector <Car> ReadCarFile(const string& filepath); #endif _CARS_H<file_sep>#ifndef _FILEPROCESSING_H #define _FILEPROCESSING_H #include <iostream> #include <string> #include <fstream> #include <Windows.h> enum EducationalForm { DNEV, VECHER, ZAOCH }; class Spec_t { private: std::string name; int n_form; EducationalForm* forms; int* examScores; int* costs; public: Spec_t(); Spec_t(const Spec_t&); ~Spec_t(); std::string GetName() const; int GetNum_form() const; EducationalForm Get_Form(int ind) const; int Get_ExamScore(int ind) const; int Get_Cost(int ind) const; void SetName(const std::string name_s); void SetNumForms(const int n); void Set_Form(const int ind, EducationalForm form); void Set_Cost(const int ind, int cost); void Set_ExamScore(const int ind, int score); void Set_Forms(const int num); void Set_Costs(const int num); void Set_ExamScores(const int num); Spec_t& operator=(const Spec_t&); }; class University_t { private: std::string name; int n_spec; Spec_t* specs; public: University_t(); University_t(const University_t&); ~University_t(); University_t& operator=(const University_t&); std::string GetName() const; int GetNum_spec() const; Spec_t& GetSpec(int ind) const; void SetName(const std::string name_u); void SetNumSpecs(const int n); void SetSpecs(const int num); void SearchMinScoreSpeciality(std::string& spec_name, int& score, std::string& form); float ComputeAverageScore() const; float ComputeAverageCost() const; }; class Univ_database_t { private: int count; University_t* univs; int find_num_univ(const std::string& fname) const; int try_to_open_file(const std::string& fname); public: Univ_database_t(); Univ_database_t(int count); Univ_database_t(const std::string& fname); Univ_database_t(const Univ_database_t&); ~Univ_database_t(); University_t& operator[] (const int ind); int SearchVUZ(const std::string& name, University_t& u) const; int SearchSpecialties(const std::string& name, Spec_t*& specs, std::string*& names_univ) const; }; std::ostream& operator<<(std::ostream& out, const University_t& un); std::ostream& operator<<(std::ostream& out, const Spec_t& sp); #endif<file_sep>#include "interface.h" #include "container.h" #include "receipt.h" #include <iostream> #include <fstream> string start() { string path; while (true) { cout << "Enter the file path..." << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } cout << "ERROR: Could not open file!\n" << endl; } } string getDebugPath() { string path; while (true) { cout << "Enter path to debug file..." << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } } } void menu(dataBase& data, Container<Receipt>& receipts) { int i = 0; while (true) { Receipt currentReceipt(i); bool exit = false; while (!exit) { cout << "Menu:\n"; cout << "1. Add item\n"; cout << "2. Remove item\n"; cout << "3. Counting summ\n"; cout << "4. New receipt\n"; cout << "5. Exit\n"; int choice; cout << "Enter menu's point: "; cin >> choice; switch (choice) { case 1: { Product* product = data.searchProductByCode(); currentReceipt.addItem(product, data); cout << currentReceipt << endl; break; } case 2: { Product* product = data.searchProductByCode(); currentReceipt.removeItem(product); cout << currentReceipt << endl; break; } case 3: { cout << currentReceipt; cout << "Total cost: " << currentReceipt.getTotal() << endl; break; } case 4: { receipts.add(currentReceipt); exit = true; cout << "New receipt...\n"; i++; currentReceipt.dataUpdate(data); break; } case 5: { receipts.add(currentReceipt); currentReceipt.dataUpdate(data); cout << "Exit.\n"; string debugPath = getDebugPath(); data.writeData(debugPath); return; } } } } }<file_sep>#ifndef _RECEIPT_H #define _RECEIPT_H #include <string> #include "Container.h" struct TProduct { int code; string name; float price; bool operator==(const TProduct&) const; friend ostream& operator<<(ostream&, const TProduct&); }; struct TInfoProduct { TProduct product; int count; bool operator==(const TInfoProduct&) const; friend ostream& operator<<(ostream&, const TInfoProduct&); }; class TProductsDatabase { private: TContainer<TInfoProduct> products; void get_correct_file_name(const string& fname) const; bool check_file_name(const string& fname) const; public: TProductsDatabase(const string& filename); TInfoProduct& operator[](int ind); int barcode_search(const int barcode); int Get_num_prods() const; void Updating_remove(const TProduct& prod); void Updating_add(const TProduct& prod); friend ostream& operator<<(ostream&, const TProductsDatabase&); // operator << }; class TReceiptLine { private: TProduct product; int count; double summ; public: TReceiptLine(); TReceiptLine(TProduct& product, int count, double sum_price); TReceiptLine(const TReceiptLine&); const TReceiptLine& operator= (const TReceiptLine&); bool operator==(const TReceiptLine&) const; friend ostream& operator<<(ostream& out, const TReceiptLine& rec_line); const TProduct& Get_product() const; int Get_count() const; double Get_sum_cost() const; void Set_count(int); void Set_sum_cost(double); }; struct TDate { int day; int month; int year; TDate(); }; struct TTime { int hour; int minute; int second; TTime(); }; class TReceipt { private: static long code; TDate date; TTime time; TContainer<TReceiptLine> products; static void Code_increase(); public: TReceipt(); TReceipt(const TReceipt&); int Find_product(const long) const; int Get_num_products() const; void Add_new_prod(const TReceiptLine&); double Get_total_sum() const; void SetTime(); void Delete_prod(const int ind); void Delete(TProductsDatabase& db); void Add(TProductsDatabase& db, int search); TReceiptLine& operator[](int); friend ostream& operator<<(ostream& out, TReceipt& rec); const TReceipt& operator= (const TReceipt&); }; #endif <file_sep>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include "Header.h" using namespace std; void token_size(string const& str, const char delim, vector<string>& out) { stringstream ss(str); string s; while (getline(ss, s, delim)) { out.push_back(s); } } Owner* read_inf(int& n) { string path; cout << "enter path" << endl; cin >> path; ifstream infile(path); if (!infile) { throw "file not finde"; } infile >> n; Owner* o = new Owner[n]; string data; string* razdel = new string[3]; for (int i = 0; i < n; i++) { infile >> o[i]; const char delim = '.'; vector<string> out; data = o[i].date.day; token_size(data, delim, out); int j = 0; for (auto& data : out) { razdel[j++] = data; } int k = 0; o[i].date.day = razdel[k++]; o[i].date.month = razdel[k++]; o[i].date.year = razdel[k++]; } infile.close(); delete[] razdel; return o; } void print_inf(Owner* o, int n) { for (int i = 0; i < n; i++) { cout << o[i]; } } Owner* search_owner(Owner* o, int& n, int& k) { Owner* o1 = new Owner[n]; int flag = 0, g; while (flag == 0) { cout <<"input number of gibdd = "; cin >> g; cout << endl; for (int i = 0; i < n; i++) { if (o[i].gibdd == g) { o1[flag] = o[i]; flag++; } } if (flag == 0) { cout <<"incorrect number of gibdd" << endl; } } k = flag; return o1; } istream&::operator>>(istream& in, Owner& o) { in >> o.surname >> o.name >> o.patronymic >> o.date.day >> o.carnum >> o.gibdd >> o.phnum >> o.tehpas; return in; } ostream& :: operator<<(ostream& out, const Owner& o) { out << o.surname << " " << o.name << " " << o.patronymic << endl << o.date.day << "." << o.date.month << "." << o.date.year << endl << o.carnum << endl << o.gibdd << endl << o.phnum << endl << o.tehpas << endl << endl; return out; }<file_sep>#include "utils.h" #include <stdio.h> #include <windef.h> void output(char** filesName, unsigned long* filesSize, int* filesIndex, int count, long long time) { for (int i = 0; i < count; i++) { printf("%s", filesName[filesIndex[i]]); printf(" %lu B\n", filesSize[i]); } printf("It took %lld milliseconds to sort\n\n", time); } void userInput(char** a, wchar_t** path, HANDLE hf, WIN32_FIND_DATA FindFileData) { do { printf("Enter the open path of the directory with the files: \n"); scanf("%s", a); strcat(a, "\\*.*"); mbstowcs(path, a, strlen(a) + 1); hf = FindFirstFileW(path, &FindFileData); } while (hf == INVALID_HANDLE_VALUE); printf("Your path: %s \n", a); } void add(unsigned long* copy, int* index, unsigned long* size, int count) { for (int i = 0; i < count; i++) { copy[i] = size[i]; index[i] = i; } } int filesAmount(wchar_t** path, HANDLE hf, WIN32_FIND_DATA FindFileData) { int count = 0; hf = FindFirstFile(path, &FindFileData); if (hf != INVALID_HANDLE_VALUE) { do { if (wcscmp(FindFileData.cFileName, L".") != 0 && wcscmp(FindFileData.cFileName, L"..") != 0) { count++; } } while (FindNextFile(hf, &FindFileData) != 0); } return count; } int choice() { int input; printf("|-----------------------------------------|\n"); printf("Selected action:\n"); printf("1) Merge Sort\n"); printf("2) Quick Sort\n"); printf("3) Bubble Sort\n"); printf("4) Change dir\n"); printf("5) Exit\n"); printf("|-----------------------------------------|\n"); if (scanf("%d", &input) != 1) { printf("Enter only numbers..."); return NULL; } return input; } void fill(HANDLE hf, WIN32_FIND_DATA FindFileData, char** fileNames, unsigned long* sizes) { int j = 0; if (hf != INVALID_HANDLE_VALUE) { do { if (wcscmp(FindFileData.cFileName, L".") != 0 && wcscmp(FindFileData.cFileName, L"..") != 0) { fileNames[j] = (char*)malloc(MAX_PATH * sizeof(char)); wcstombs(fileNames[j], FindFileData.cFileName, MAX_PATH); sizes[j] = FindFileData.nFileSizeLow; j++; } } while (FindNextFile(hf, &FindFileData) != 0); } } void info(int count, char** fileNames, unsigned long* sizes) { int i; printf("\nFiles amount in the directory: %d\n\n", count); for (i = 0; i < count; i++) { printf("%s size: %d B\n", fileNames[i], sizes[i]); } } void memFree(unsigned long* a, unsigned long* b) { free(a); free(b); } void memFreeMulti(char* userStr, char** fileNames, wchar_t* path, unsigned long* sizes, int count) { int i; free(userStr); for (i = 0; i < count; i++) free(fileNames[i]); free(fileNames); free(path); free(sizes); } <file_sep>#include <stdio.h> #include <stdlib.h> #include "person.h" int main(void) { Person** per; int n, i, a; char f[100]; printf("Enter filename: "); scanf("%s", f); read(&per, &n, f); for (i = 0; i < n; i++) print_persons(per[i]); Sort(per, n); do { printf("\nHow do you want to display the sorted list?\n1. In alphabetical ascending order\n2. In alphabetical descending order\nEnter a number: "); scanf("%d", &a); if (a == 1) { printf("\n"); for (i = 0; i < n; i++) print_persons(per[i]); } if (a == 2) { printf("\n"); for (i = n - 1; i >= 0; i--) print_persons(per[i]); } } while ((a <= 0) || (a > 2)); for (i = 0; i < n; i++) free_person(&(per[i])); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> void main() { srand(time(NULL)); int number, user_number, mode, try = 0; number = 1 + rand() % (1000); do { printf("Select game mode (1 or 2): "); scanf_s("%d", &mode); if ((mode != 1) && (mode != 2)) { printf("Invalid mode selection, try again!\n"); } } while ((mode < 1) || (mode > 2)); if (mode == 1) { printf("The program guessed a number from 1 to 1000. Try to guess it)) : "); do { scanf_s("%d", &user_number); if (user_number == number) printf("You guessed the number!\n"); else if (user_number < number) printf("The hidden number is more.Try again : "); else printf("The hidden number is less. Try again: "); try++; } while (user_number != number); printf("You guessed the number %d in %d tries", number, try); } else { printf("Choose a number from 1 to 1000 and enter it. The program will try to guess it: "); do { scanf_s("%d", &user_number); if (user_number > 1000 || user_number < 0) { printf("You entered an invalid number\n"); } } while (user_number > 1000 || user_number < 0); int a = 1, b = 1000, number, try = 0; char sign; printf("Print '<' if your number is less than guessed\n"); printf("Print '>' if your number is more than guessed\n"); printf("Print '=' if your number equals guessed\n"); while (a <= b) { try++; number = (b + a) / 2; printf("%d?\n", number); do { scanf_s("%c", &sign); } while (sign != '=' && sign != '<' && sign != '>'); if (sign == '=') break; if (sign == '<') b = number - 1; else a = number + 1; } printf("Program guessed the number %d in %d tries!", number, try); } } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <windows.h> #include <malloc.h> #include <time.h> typedef struct { long long int mas; char name[260]; }file; void copy_name(char name[], wchar_t nm[]) { int ind = 0; while (strcmp(&nm[ind], "\0") != 0) { name[ind] = nm[ind]; ind += 1; } strcpy(&name[ind], "\0"); } void copy_mas(file a[], file b[], int ind) { for (int j = 0; j < ind; j++) { a[j].mas = b[j].mas; strcpy(a[j].name, b[j].name); } } void collect_data(char *pPath, file *pMas) { char path_copy1[500]; HANDLE hFile; WIN32_FIND_DATA data; int ind = 0; hFile = FindFirstFileA(pPath, &data); while (FindNextFile(hFile, &data) != 0) { char name[500]; copy_name(name, data.cFileName); if (strcmp(&name, "..") != 0) { if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { pMas[ind].mas = data.nFileSizeLow; strcpy(pMas[ind].name, &name); ind += 1; } } } } void counting(char path[], int *cnt) { HANDLE hFile; WIN32_FIND_DATA data; strcat(path, "/*"); hFile = FindFirstFileA(path, &data); while (FindNextFile(hFile, &data) != 0) { if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { *cnt += 1; } } } void swap(int a, int b, file mas[]) { file tmp; tmp.mas = mas[a].mas; strcpy(&(tmp.name), &(mas[a].name)); mas[a].mas = mas[b].mas; strcpy(&(mas[a].name), &(mas[b].name)); mas[b].mas = tmp.mas; strcpy(&(mas[b].name), &(tmp.name)); } void merge(file mas[], int m1, file left[], int l1, file right[], int r1) { int l = 0, r = 0, m = 0; while (l < l1 && r < r1) { if (left[l].mas < right[r].mas) { mas[m].mas = left[l].mas; strcpy(mas[m].name, left[l].name); l += 1; } else { mas[m].mas = right[r].mas; strcpy(mas[m].name, right[r].name); r += 1; } m += 1; } while (l < l1) { mas[m].mas = left[l].mas; strcpy(mas[m].name, left[l].name); l += 1; m += 1; } while (r < r1) { mas[m].mas = right[r].mas; strcpy(mas[m].name, right[r].name); r += 1; m += 1; } } void choice_sort(file mas[], int n) { int k = 0; for (int i = 0; i < n; i++) { int min = i; for (int j = i; j < n; j++) { if (mas[j].mas < mas[min].mas) { min = j; } } swap(k, min, mas); k += 1; } } void insert_sort(file mas[], int n) { for (int i = 0; i < n; i++) { int k = i - 1; for (int j = i; j > 0; j--) { if (mas[j].mas < mas[k].mas) { swap(k, j, mas); } k -= 1; } } } void merge_sort(file mas[], int n) { int mid = n / 2; file* left = (file*)malloc(mid * sizeof(file)); file* right = (file*)malloc((n - mid) * sizeof(file)); if (n < 2) { return; } for (int i = 0; i < mid; i++) { left[i].mas = mas[i].mas; strcpy(left[i].name, mas[i].name); } for (int i = mid; i < n; i++) { right[i - mid].mas = mas[i].mas; strcpy(right[i - mid].name, mas[i].name); } merge_sort(left, mid); merge_sort(right, (n - mid)); merge(mas, n, left, mid, right, (n - mid)); free(left); free(right); } void output(file mas[], int ind) { for (int j = 0; j < ind; j++) { printf("\t%s %lld \n", mas[j].name, mas[j].mas); } } void sorting(void (*func)(file mas[], int n), file mas[], int n) { clock_t begin = clock(); func(mas, n); clock_t end = clock(); output(mas, n); long double total = (end - begin) / CLOCKS_PER_SEC; printf("\ttime spent: %llf\n", total); } void init() { system("chcp 1251"); file* pMas = { 0 }, *copy = {0}; int count = 0; char path[300], command[5]; WIN32_FIND_DATA t; HANDLE hFile; clock_t begin, end; void (*srt)(file mas[], int n); printf("\nList of available commands:\n"); printf("\tnew --- Set/change path\n"); printf("\tchs --- Choice sort\n"); printf("\tins --- Insert sort\n"); printf("\tmrs --- Merge sort\n"); printf("\texit\n"); do { printf(">> "); gets(command); if (strcmp(command, "new") == 0) { gets(path); count = 0; counting(path, &count); free(pMas); free(copy); pMas = (file*)malloc(count * (sizeof(file))); copy = (file*)malloc(count * (sizeof(file))); collect_data(path, pMas); copy_mas(copy, pMas, count); } else if (strcmp(command, "chs") == 0) { srt = choice_sort; sorting(srt, copy, count); } else if (strcmp(command, "ins") == 0) { srt = insert_sort; sorting(srt, copy, count); } else if (strcmp(command, "mrs") == 0) { srt = merge_sort; sorting(srt, copy, count); } else if (strcmp(command, "exit") != 0) printf("Incorrect command\n"); copy_mas(copy, pMas, count); } while (strcmp(command, "exit") != 0); free(pMas); free(copy); } int main(){ init(); return 0; }<file_sep>cmake_minimum_required(VERSION 3.23) project(Practice4 C) set(CMAKE_C_STANDARD 23) add_executable(Practice4 main.c) <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int a; printf("Game: guess the number. Which mode do you want to choose?(1 or 2) "); scanf("%d", &a); while ((a != 1) && (a != 2)) { printf("You can only choose mod number 1 or mod number 2"); scanf("%d", &a); } if (a == 1) { mode1(); return 0; } else { mode2(); return 0; } } int mode1() { time_t t; int numb, guess, i = 1; srand((unsigned int)time(&t)); numb = (int)(1000. / RAND_MAX * rand()); printf("Are you ready?\n"); system("pause"); printf("Let's start the game. Try to guess what number the computer guessed: "); scanf("%d", &guess); while ((guess > 1000) || (guess < 0)) { printf("Maybe you forgot that the computer could guessed of a number in the range from 0 to 1000(Don't be upset, this attempt doesn't count.). Try again: "); scanf("%d", &guess); } if (numb == guess) { printf("Wow! From the first try! Congratulations:)"); return 0; } else { while (numb != guess) { if (numb > guess) { printf("The hidden number is greater than the one you entered.Try again: "); scanf("%d", &guess); while ((guess > 1000) || (guess < 0)) { printf("Maybe you forgot that the computer could guessed of a number in the range from 0 to 1000(Don't be upset, this attempt doesn't count.). Try again: "); scanf("%d", &guess); } } else { printf("The hidden number is less than the one you entered.Try again: "); scanf("%d", &guess); while ((guess > 1000) || (guess < 0)) { printf("Maybe you forgot that the computer could guessed of a number in the range from 0 to 1000(Don't be upset, this attempt doesn't count.). Try again: "); scanf("%d", &guess); } } i++; } printf("Congratulations!You were able to guess from %d attempts", i); } return 0; } int mode2() { int point = 500; int correction = 500; int user_ans = -1; int i = 0; int choice = 0; printf("Are you ready?\n"); system("pause"); printf("Think of a number in the range from 0 to 1000, please.\n"); while (user_ans != 0) { if ((point > 1000) || (point < 0)) { printf("The number that you have in your mind doesn't belong to the specified range. Would you like to try again (if yes type 1)?\n"); scanf("%d", &choice); if (choice == 1) { system("cls"); mode2(); return 0; } else { return 0; } } printf("The number is %d, isn't it? (if my number is greater than yours, type 2, if my number is less than yours, type 1, otherwise type 0)\n", point); i++; if (i >= 15) { printf("You LIAR!!!\n"); system("pause"); return 0; } scanf("%d", &user_ans); switch (user_ans) { case 2: point += correction; correction = correction / 2 + correction % 2; break; case 1: point -= correction; correction = correction / 2 + correction % 2; break; case 0: printf("I'm smart! It takes me %d attempts to accomplish this mission!\n", i); break; } } system("pause"); return 0; }<file_sep>#include <stdio.h> int main() { float h, d, w; float dvp = 0.5, dsp = 1.5; printf("Enter the height, width and depth of the cabinet "); scanf_s("%f %f %f", &h, &w, &d); if (h < 180 || h > 220 || d < 50 || d > 90 || w < 80 || w > 120) { printf("Incorrect data entered\n"); printf("h in [180, 220], w in [80, 120], d in [50, 90]"); return 0; } int k = h / 40; float m1 = k * d * (w - 2 * dsp) * dsp * 0.55; float m2 = h * w * dvp * 0.8; float m3 = 2 * h * d * dsp * 0.55; float m4 = 2 * (w - 2 * dsp) * d * dsp * 0.55; float m5 = w * h * 1.5; float m = (m1 + m2 + m3 + m4 + m5) / 1000; printf("%f", m); printf(" kg "); return 0; } <file_sep>#include <stdio.h> #include "Functions_structures.c" /*Tourist Guide.The guide contains a list of travel agenciesand the services they offer (country, city or itinerary of the cruise, accommodation and travel conditions, excursions, host service, price of the trip). Provide a list of travel agencies offering tours to Eurozone countries. */ int main(int argc,char *argv[]) { FILE* fptr;//creating file var int num_agencies; TAgency** my_list_agencies;//create massive pointers fptr = fopen("C://TouristAgences.txt", "r");//open the file for reading if (fopen == NULL) { printf("Error!File not found\n");//check exit(-99999999999999);//normal program termination } num_agencies = file_reader(fptr, &my_list_agencies);//reading data on file output_data_EZONES(fptr, my_list_agencies, num_agencies); fclose(fptr); free_memory(my_list_agencies,num_agencies);//wash hands return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <time.h> int main() { int game, number, option_number, count, good, min, max; count = 0; char answer=' '; srand((unsigned int)time(NULL)); printf("Select the game mode (1-You guess the number given by the computer; 2-The computer guesses the number given by you): "); scanf("%d", &game); if (game == 1) { printf("The program made a number from 1 to 1000. Try to guess it. "); number = 1 + rand() % (1000); do { count++; scanf("%d", &option_number); if (option_number == number) printf("Congratulations, you guessed the number!"); else if (option_number < number) printf("The hidden number is bigger. Try again: "); else printf("The hidden number is smaller. Try again:"); } while (option_number != number); } else if (game == 2) { printf("Guess a number from 1 to 1000 and enter it. The program will try to guess it: \n"); do { scanf("%d", &number); if ((number > 1000) || (number < 1)) { printf("Incorrect number entered. Try again: "); } } while ((number > 1000) || (number < 1)); option_number = 1 + rand() % (1000); min = 1; max = 1000; while (answer!='=') { printf("Number %d\n", option_number); printf("What is the number?(=,<,>)\n "); scanf(" %c", &answer); count++; if (answer == '>') { min = option_number; option_number =option_number + (max-min)/2; } else if (answer == '<') { max = option_number; option_number = option_number - (max - min) / 2; } } } printf("Number: %d was guessed in %d attempts", number, count); }<file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" #define _CRT_SECURE_NO_WARNINGS void allocate_matrix(TMatrix** matrix, int n) { (*matrix) = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n; (*matrix)->x = (float*)malloc(sizeof(float) * n * n); } void fill_matrix(TMatrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { scanf_s("%f", &(matrix->x[i * matrix->n + j])); } } printf("\n"); } void print_matrix(TMatrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { printf("%.3f ", matrix->x[i * matrix->n + j]); } printf("\n"); } printf("\n"); } void free_matrix(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; int i, j; if (matrix1->n != matrix2->n) { printf("ERROR: Square matrixes should have the same lenght and height.\n"); return NULL; } allocate_matrix(&res, matrix1->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = matrix1->x[i * res->n + j] + matrix2->x[i * res->n + j]; } } return res; } TMatrix* add_const(TMatrix* matrix, float c) { TMatrix* res; int i, j; allocate_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = matrix->x[i * res->n + j] + c; } } return res; } TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; int i, j, k; if (matrix1->n != matrix2->n) { printf("ERROR: Square matrixes should have the same lenght and height.\n"); return NULL; } allocate_matrix(&res, matrix1->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = 0.0f; for (k = 0; k < res->n; k++) { res->x[i * res->n + j] += matrix1->x[i * res->n + k] * matrix2->x[k * res->n + j]; } } } return res; } TMatrix* multi_const(TMatrix* matrix, float c) { TMatrix* res; int i, j; allocate_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[i * res->n + j] = matrix->x[i * res->n + j] * c; } } return res; } void main_action() { TMatrix* matrix_dynamic, * m1, * m2, * res; int action = 0; int n; float add; float multi; printf("n = "); scanf_s("%d", &n); allocate_matrix(&m1, n); allocate_matrix(&m2, n); printf("Enter 1st matrix:\n"); fill_matrix(m1); printf("Enter 2nd matrix:\n"); fill_matrix(m2); print_matrix(m1); print_matrix(m2); printf("what i have to do?\n"); printf("choose an action: 1 - '+ add const', 2 - '+ add matrix', 3 - '* mylty const', 4 - '* multy matrix' \n"); printf("action = "); scanf_s("%d", &action); if (action == 1) { printf("add = "); scanf_s("%f", &add); printf("add_const:\n"); res = add_const(m1, add); print_matrix(res); free_matrix(&res); return 0; } else if (action == 2) { printf("add_matrix:\n"); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); } else if (action == 3) { printf("multi = "); scanf_s("%f", &multi); printf("multi_const:\n"); res = multi_const(m1, multi); print_matrix(res); free_matrix(&res); } else if (action == 4) { printf("multi_matrix:\n"); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); } else { printf("gg, start again"); return 0; free_matrix(&m1); free_matrix(&m2); } free_matrix(&m1); free_matrix(&m2); }<file_sep>#include <stdlib.h> #include <stdio.h> #include "matrix.h" void alloc_matrix(TMatrix** matrix, int n) { int i; *matrix = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n; (*matrix)->elems = (double**)malloc(sizeof(double*) * n); for (i = 0; i < n; i++) { (*matrix)->elems[i] = (double*)malloc(sizeof(double) * n); } } void free_matrix(TMatrix** matrix) { int i; for (i = 0; i < (*matrix)->n; i++) { free((*matrix)->elems[i]); } free((*matrix)->elems); free(*matrix); } void fill_matrix(TMatrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { scanf("%lf", &(matrix->elems[i][j])); } } } void print_matrix(TMatrix* matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { printf("%.3lf ", matrix->elems[i][j]); } printf("\n"); } printf("\n"); } TMatrix* add_scalar(TMatrix* matrix, double c) { TMatrix* res; int i, j; alloc_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->elems[i][j] = matrix->elems[i][j] + c; } } return res; } TMatrix* multi_scalar(TMatrix* matrix, double c) { TMatrix* res; int i, j; alloc_matrix(&res, matrix->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->elems[i][j] = matrix->elems[i][j] * c; } } return res; } TMatrix* add_matrix(TMatrix* m1, TMatrix* m2) { TMatrix* res; int i, j; if (m1->n != m2->n) { printf("ERROR: Incorrect vector sizes.\n"); return NULL; } alloc_matrix(&res, m1->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->elems[i][j] = m1->elems[i][j] + m2->elems[i][j]; } } return res; } TMatrix* multi_matrix(TMatrix* m1, TMatrix* m2) { TMatrix* res; int i, j, k; if (m1->n != m2->n) { printf("ERROR: Incorrect vector sizes.\n"); return NULL; } alloc_matrix(&res, m1->n); for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->elems[i][j] = 0; for (k = 0; k < res->n; k++) { res->elems[i][j] += m1->elems[i][k] * m2->elems[k][j]; } } } return res; }<file_sep>#include <stdio.h> #include <locale.h> #include <math.h> int main() { float x1, x2, y1, y2, r1, r2, dl; setlocale(LC_ALL, "rus"); printf("Enter x1: "); scanf_s("%f", &x1); printf("Enter x2: "); scanf_s("%f", &x2); printf("Enter y1: "); scanf_s("%f", &y1); printf("Enter y2: "); scanf_s("%f", &y2); printf("Enter r1: "); scanf_s("%f", &r1); printf("Enter r2: "); scanf_s("%f", &r2); dl = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if (dl == r1 + r2) { printf("The circles touch each other (external touch)"); return 0; } if (dl > r1 + r2) { printf("The circles do not touch each other "); return 0; } if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("The circles match"); return 0; } if ((dl + r1 == r2) || (dl + r2 == r1)) { printf("The circles touch each other (inner touch)"); return 0; } if (abs(x1 - x2) < r1 || abs(x1 - x2) < r2) { printf("One circle inside another"); return 0; } printf("Circles have two points in common"); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include "workers.h"; #include <iostream> using namespace std; int main() { string path = get_path(); labor labor_exchange(path); int percent=labor_exchange.higher_education(); cout << "Percentage of employees with higher education:" << percent << " % " << endl; return 0; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main() { //2 окружности задаются координатами центров и радиусов. Определите взаимное положение этих окружностей. float r1, r2, x1, x2, y1, y2, d; printf("Enter x1, y1\n"); scanf("%f %f", &x1, &y1); printf("Enter x2, y2\n"); scanf("%f %f", &x2, &y2); printf("Enter r1,r2\n"); scanf("%f %f", &r1, &r2); d = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("Circles coincide"); return 0; } if (d > r1 + r2) { printf("No common points"); return 0; } if (d == r1 + r2) { printf("External touch"); return 0; } if ((d > r1 - r2) && (d < r1 + r2)) { printf("Two common points(circles intersect)"); return 0; } if ((d >= 0) && (d < r1 - r2)) { printf("One circle is inscribed in another"); return 0; } if (d == r1 - r2) { printf("Inner touch"); return 0; } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" int main() { Matrix *res, *m1, *m2, *res_dt; allocate_matrix(&m1, 3); fill_matrix(m1, 3); allocate_matrix(&m2, 3); fill_matrix(m2, 3); res_dt = add_dot(m1, 5.0f); print_matrix(res_dt, 3); free_matrix(&res_dt); res_dt = multiple_dot(m1, 2.0f); print_matrix(res_dt, 3); free_matrix(&res_dt); res = add_matrix(m1, m2); print_matrix(res, 3); free_matrix(&res); res = multiple_matrix(m1, m2); print_matrix(res, 3); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#ifndef _Star #define _Star struct Star { std::string name; float dist; float magnitude; float deg; float min; float sec; }; struct Constellation { Constellation(std::string Cname, int n); ~Constellation(); int count; std::string name; Star* stars; }; struct Constellation_library { Constellation_library(int n); ~Constellation_library(); Constellation** cns; int count; }; std::ostream& operator<< (std::ostream& out, const Constellation* cns); std::istream& operator>> (std::istream& in, const Constellation* cns); void cnst_table(Constellation_library* cns, int count); void read_data(Constellation_library*& lib, int& cnt); void choice(Constellation_library* cns, int count); #endif <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define N 5 #define M 10 #include <stdlib.h> int main() { int a[N] = { 0 }; int u_a[N] = { 0 }; int k, i, j, user_n; int flag, flag1, flag2, tmp; int bulls, cows, attempts; printf("Input k "); scanf("%d", &k); while ((k < 2) || (k > 5)) { printf("Incorrect data. Try again. Input 2 < k < 5 "); scanf("%d", &k); } srand((unsigned int)time(NULL)); a[0] = 1 + rand() % 9; for (i = 1; i <= k - 1; i++) { flag = 1; while (flag == 1) { flag = 0; tmp = rand() % 10; for (j = 0; j < i; j++) if (tmp == a[j]) { flag = 1; break; } if (flag == 0) a[i] = tmp; } } flag = 1; attempts = 0; while (flag == 1) { flag2 = 0; printf("Guess the hidden number \n"); scanf("%d", &user_n); for (i = k - 1; i > -1; i--) { if (user_n == 0) { printf("Incorrect data. Number is too small. Try again. \n"); flag2 = 1; break; } u_a[i] = user_n % 10; user_n /= 10; } if (user_n > 0) { printf("Incorrect data. Number is too large. Try again.\n"); continue; } if (flag2 == 1) { continue; } flag1 = 0; for (i = 0; i <= k - 1; i++) { for (j = i + 1; j <= k - 1; j++) if (u_a[i] == u_a[j]) { printf("Incorrect data. Try again. The numbers should not be repeated \n"); flag1 = 1; break; } if (flag1 == 1) break; } if (flag1 == 1) continue; bulls = 0; cows = 0; for (i = 0; i <= k - 1; i++) for (j = 0; j <= k - 1; j++) if (u_a[i] == a[j]) if (i == j) bulls += 1; else cows += 1; if (bulls == k) { attempts += 1; printf("Congratulations! You guessed the number in %d attempts!", attempts); flag = 0; } else { attempts += 1; printf("bulls = %d, cows = %d \n", bulls, cows); } } return 0; }<file_sep>#include<stdio.h> #include<windows.h> #include<conio.h> #include<locale.h> #include<string.h> #include<malloc.h> #include<time.h> typedef struct { wchar_t name_file[260]; unsigned long long size_file; } file; int select_sort(file* ptr, unsigned int count, int type); int insert_sort(file* ptr, unsigned int count, int type); int merge_sort(file* ptr, unsigned int count, int type); int count_files(wchar_t* path); void menu(file* ptrf, unsigned int count, int type_sort); int find(wchar_t* path, unsigned int count, int type_sort); int main() { unsigned int num = 0; wchar_t path[100] = L" "; int type_sort; do { printf("enter path or exit : "); wscanf_s(L"%s", path, (unsigned)_countof(path));//scanf if (wcsncmp(path, L"exit", (unsigned)_countof(path))) { //сравнение строк printf("1. Select sort. Sort by ascending size.\n"); // сортировка выбором по возрастанию размера файла printf("2. Select sort. Sort by dicending size.\n"); // сортировка выбором по убыванию размера файла printf("3. Insert sort. Sort by ascending size.\n"); // сортировка вставками по возрастанию размера файла printf("4. Insert sort. Sort by dicending size.\n"); // сортировка вставками по убыванию размера файла printf("5. Merge sort. Sort by ascending size.\n"); // сортировка слиянием по возрастанию размера файла printf("6. Merge sort. Sort by dicending size.\n"); // сортировка слиянием по убыванию размера файла printf("Enter file sort type: "); scanf_s("%d", &type_sort); num = count_files(path);// считываем количесто файлов в директории if (num < 0) continue;// если возвращает -1 ошибку начинаем всё заново printf("\n"); find(path, num, type_sort); } } while (wcsncmp(path, L"exit", (unsigned)sizeof(path))); return 0; } int count_files(wchar_t* path) { WIN32_FIND_DATA FindFileData;//хранятся атрибуты файла HANDLE hf; int i = 0; hf = FindFirstFile(path, &FindFileData);//открывается поток на чтение данных из директории if (hf == INVALID_HANDLE_VALUE) { printf("Invalid File Handle. GetLastError reports %d\n", GetLastError()); return -1; } if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) i++; if (hf != INVALID_HANDLE_VALUE) while (FindNextFile(hf, &FindFileData)) if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) i++; FindClose(hf); // system("pause"); return i; } int find(wchar_t* path, unsigned int count, int type_sort) { WIN32_FIND_DATA FindFileData; HANDLE hf; unsigned long long nFileLen = 0;//8байт file* ptrf;//указатель на первый эл-т массива структур unsigned int i = 0; //выделяем память под размер структур //по адресу выделяем память =() if ((ptrf = (file*)malloc((count) * (unsigned int)sizeof(file))) == NULL) { printf("Unable to allocate %llu bytes of memory for character buffer\n", count * sizeof(file)); return 0; } hf = FindFirstFile(path, &FindFileData); if (hf == INVALID_HANDLE_VALUE) { printf("Invalid File Handle. GetLastError reports %d\n", GetLastError()); return -1; } if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { wcscpy_s(ptrf[i].name_file, sizeof(FindFileData.cFileName) / sizeof(wchar_t), FindFileData.cFileName); nFileLen = (FindFileData.nFileSizeHigh * ((unsigned long long)MAXDWORD + 1)) + FindFileData.nFileSizeLow; ptrf[i].size_file = nFileLen; i++; } if (hf != INVALID_HANDLE_VALUE) { while (FindNextFile(hf, &FindFileData)) { nFileLen = (FindFileData.nFileSizeHigh * ((unsigned long long)MAXDWORD + 1)) + FindFileData.nFileSizeLow; if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); // printf("%ls\t Каталог\n", FindFileData.cFileName); else { wcscpy_s(ptrf[i].name_file, sizeof(FindFileData.cFileName) / sizeof(wchar_t), FindFileData.cFileName); // printf("sizeof() = %llu\n", (unsigned long long)(sizeof(FindFileData.cFileName) / sizeof(wchar_t))); if (i < count) //-- ptrf[i].size_file = nFileLen; // printf("\n%d\t%ls\t %llu\n", i, ptrf[i].name_file, ptrf[i].size_file); i++; } } menu(ptrf, count, type_sort); free(ptrf); FindClose(hf); system("pause"); } else { printf("INVALID HANDLE VALUE!!!\n"); return 0; } return 1; } void menu(file* ptrf, unsigned int count, int type_sort) { switch (type_sort) { case 1: printf("Select sort. Sort by ascending size.\n"); select_sort(ptrf, count, 1); break; case 2: printf("Select sort. Sort by dicending size.\n"); select_sort(ptrf, count, 2); break; case 3: printf("Insert sort. Sort by ascending size.\n"); insert_sort(ptrf, count, 1); break; case 4: printf("Insert sort. Sort by dicending size.\n"); insert_sort(ptrf, count, 2); break; case 5: printf("Merge sort. Sort by ascending size.\n"); merge_sort(ptrf, count, 1); break; case 6: printf("Merge sort. Sort by dicending size.\n"); merge_sort(ptrf, count, 2); break; default:for (unsigned int j = 0; j < count; j++) printf("%d\t%ls\t %llu\n", j, ptrf[j].name_file, ptrf[j].size_file); printf("Sort type from 1 to 6\n"); } } int merge_sort(file* ptr, unsigned int count, int type) { unsigned int step = 1; // шаг разбиения последовательности unsigned long long* buff, * temp; // дополнительные массивы double time_spent = 0.0; if ((buff = malloc(sizeof(unsigned long long) * count)) == NULL) { printf("Unable to allocate %llu bytes of memory for character buffer\n", count * sizeof(unsigned long long)); return 0; } for (unsigned int i = 0; i < count; i++) buff[i] = ptr[i].size_file; if ((temp = malloc(sizeof(unsigned long long) * count)) == NULL) { printf("Unable to allocate %llu bytes of memory for character buffer\n", count * sizeof(unsigned long long)); return 0; } clock_t begin = clock(); while (step < count) { unsigned int index = 0; // индекс результирующего массива unsigned int l = 0; // левая граница участка unsigned int m = l + step; // середина участка unsigned int r = l + step * 2; // правая граница участка do { m = m < count ? m : count; // сортируемый участок не выходит за границы последовательности r = r < count ? r : count; unsigned int i1 = l, i2 = m; // индексы сравниваемых элементов while (i1 < m && i2 < r) { // пока i1 не дошёл до середины и i2 не дошёл до конца switch (type) { case 1: if (buff[i1] < buff[i2]) temp[index++] = buff[i1++]; // заполняем участок результирующей последовательности else temp[index++] = buff[i2++]; break; case 2: if (buff[i1] > buff[i2]) temp[index++] = buff[i1++]; // заполняем участок результирующей последовательности else temp[index++] = buff[i2++]; break; } } // Или i1 < m или i2 < r - только один из операторов while может выполниться while (i1 < m) temp[index++] = buff[i1++]; // заносим оставшиеся элементы сортируемых участков while (i2 < r) temp[index++] = buff[i2++]; // в результирующий массив l += step * 2; // перемещаемся на следующий сортируемый участок m += step * 2; r += step * 2; } while (l < count); // пока левая граница сортируемого участка - в пределах последоватльности for (unsigned int i = 0; i < count; i++) // переносим сформированный массив обратно в buff buff[i] = temp[i]; step *= 2; // увеличиваем в 2 раза шаг разбиения } clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf("The elapsed time is %f seconds", time_spent); printf("\n"); for (unsigned int i = 0; i < count; i++) for (unsigned int j = 0; j < count; j++) if (buff[i] == ptr[j].size_file) { printf("%d\t%ls\t %llu\n", i, ptr[j].name_file, ptr[j].size_file); break; } free(temp); free(buff); return 1; } int insert_sort(file* ptr, unsigned int count, int type) { unsigned int j = 0, key = 0; unsigned long long t = 0; unsigned long long* buff; double time_spent = 0.0; if ((buff = malloc(sizeof(unsigned long long) * count)) == NULL) { printf("Unable to allocate %llu bytes of memory for character buffer\n", count * sizeof(unsigned long long)); return 0; } for (unsigned int i = 0; i < count; i++) { buff[i] = ptr[i].size_file; } clock_t begin = clock(); for (unsigned int i = 0; i < count - 1; i++) { key = i + 1; t = buff[key]; for (j = i + 1; j > 0; j--) { switch (type) { case 1: if (t > buff[j - 1]) { buff[j] = buff[j - 1]; key = j - 1; } break; case 2: if (t < buff[j - 1]) { buff[j] = buff[j - 1]; key = j - 1; } break; } } buff[key] = t; } clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf("The elapsed time is %f seconds", time_spent); printf("\n"); for (unsigned int i = 0; i < count; i++) for (j = 0; j < count; j++) if (buff[i] == ptr[j].size_file) { printf("%d\t%ls\t %llu\n", i, ptr[j].name_file, ptr[j].size_file); break; } free(buff); return 1; } int select_sort(file* ptr, unsigned int count, int type) { unsigned int a, b, c; int exchange = 0; unsigned long long t = 0; unsigned long long* buff; double time_spent = 0.0; if ((buff = malloc(sizeof(unsigned long long) * count)) == NULL) { printf("Unable to allocate %llu bytes of memory for character buffer\n", count * sizeof(unsigned long long)); return 0; } for (unsigned int i = 0; i < count; i++) { if (buff[i]) buff[i] = ptr[i].size_file; } clock_t begin = clock(); for (a = 0; a < count - 1; ++a) { exchange = 0; c = a; t = buff[a]; switch (type) { case 1: for (b = a + 1; b < count; ++b) { if (buff[b] < t) { c = b; t = buff[b]; exchange = 1; } } break; case 2: for (b = a + 1; b < count; ++b) { if (buff[b] > t) { c = b; t = buff[b]; exchange = 1; } } break; } if (exchange) { buff[c] = buff[a]; buff[a] = t; } } clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf("The elapsed time is %f seconds", time_spent); printf("\n"); for (a = 0; a < count; a++) for (b = 0; b < count; b++) if (buff[a] == ptr[b].size_file) { printf("%d\t%ls\t %llu\n", a, ptr[b].name_file, ptr[b].size_file); break; } free(buff); return 1; }<file_sep>#ifndef _KTO_H #define _KTO_H typedef struct { int n; char* name; char* surname; char* patronymic; char* date; char* carnum; unsigned long gibdd; char* phnum; unsigned long tehpas; } Owners; Owners* read_inf(); void print_inf(Owners* owner, int n); void free_inf(Owners** owner, int n); int search_owner(Owners* owner, int n); #endif <file_sep>#define _CRT_SECURE_NO_WARNING #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int HiddenNumberMas[5] = {0}; int HiddenNumber = 0; int count_mas[2]; int check(int x, int y) { for (int i = 0; i < y; i++) { if (x == HiddenNumberMas[i]) return 1; } return 0; } int check_user_answer(int AnsMas[5], int n) { int mas[10] = { 0 }; for (int i = 0; i < n; i++) { int num = AnsMas[i]; if (mas[num] == 0) mas[num]++; else return 0; } return 1; } void random_num(int x) { srand((unsigned int)time(NULL)); HiddenNumberMas[0] = rand() % 9 + 1; HiddenNumber = HiddenNumber * 10 + HiddenNumberMas[0]; for (int i = 1; i < x; i++) { int num = rand() % 10; while (check(num, x) == 1) num = rand() % 10; HiddenNumberMas[i] = num; HiddenNumber = HiddenNumber * 10 + HiddenNumberMas[i]; } } void counter(int AnsMas[5], int n) { int count_cows = 0, count_bulls = 0; for (int i = 0; i < n; i++) { if (AnsMas[i] != HiddenNumberMas[i]) { if (check(AnsMas[i], n) == 1) count_cows += 1; } else count_bulls += 1; } count_mas[0] = count_bulls; count_mas[1] = count_cows; } int main() { int n, Answer; printf("Enter the number of digits of the guessed number (2 to 5)\n"); do { scanf_s("%d", &n); } while (n < 2 || n > 5); random_num(n); printf("%d\n", HiddenNumber); // for tasting do { int AnswerMas[5] = {0}; do { printf("Reminder! All digits of the hidden number are different\n"); scanf_s("%d", &Answer); int num = Answer; for (int i = n - 1; i >= 0; i--) { AnswerMas[i] = num % 10; num /= 10; } } while (check_user_answer(AnswerMas, n) == 0); counter(AnswerMas, n); if (count_mas[0] == n) { printf("Numbre guessed"); return 0; } printf("Count of bulls: %d\n", count_mas[0]); printf("Count of cows: %d\n\n", count_mas[1]); count_mas[0] = 0; count_mas[1] = 0; } while (Answer != HiddenNumber); return 0; }<file_sep>#ifndef _BOOK_H #define _BOOK_H #include <stdbool.h> #define LONGLINE 255 #define LONTAUTHORNAME 255 #define LINE 100 typedef struct { int Couaut; char** Author; char Name[100]; char Publishing[100]; char Section[100]; bool Availability; int Score; }TBook; int count_books(char* str); void setAuthors(char* strTmp, TBook* book); int count_unic(TBook* book, int count); void read(char* str, TBook* book); void print_book(TBook* book, int count); char** create_section(TBook* book, int unic, int count); void print_section(TBook* book, int count, char* word); void print_choose_book(TBook* lib, int count, int unic, char** unic_section); void free_unic(char** unic_section, int unic); void free_mas(TBook* book, int count); #endif _BOOK_H <file_sep>#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int game_variant; srand((unsigned int)time(NULL)); do { printf("game variant="); scanf_s("%d", &game_variant); } while ((game_variant < 1) || (game_variant > 2)); if (game_variant == 1) { int r_number=rand()%1001, p_number, i=0; do { printf("enter a number\n"); scanf_s("%d", &p_number); i++; if ((p_number > 1000) || (p_number < 0)) { printf("input error\n"); } else if (p_number > r_number) { printf("random number less\n"); } else if (p_number < r_number) { printf("random number is greater\n"); } else { printf("random number guessed\n"); } } while (r_number != p_number); printf("number of attempts=%d\n", i); } else { int r_numb, i = 0, k=0, upper_limit=1001, lower_limit=0, answer; while (k != 1) { r_numb = rand() % (upper_limit - lower_limit + 1) + lower_limit; printf("hidden number = %d?\n", r_numb); scanf_s("%d", &answer); //0 - hidden number lower 1 - higher 2 - guessed i++; if (answer == 0) { upper_limit = r_numb; } else if (answer == 1) { lower_limit = r_numb; } else if (answer == 2) { printf("number of attempts =%d", i); k++; } else { printf("input error"); } } } return 0; }<file_sep>#include "matrix.h" #include <stdio.h> #include <stdlib.h> #pragma warning(disable : 4996) void alloc_matrix(TMatrix** matrix, int n) { (*matrix) = (TMatrix*)malloc(sizeof(TMatrix)); (*matrix)->n = n;//обр. к полю n (*matrix)->x = (float*)malloc(sizeof(float) * n * n); } void size_matrix(int size) { printf("VVedite rasmer matrix"); scanf("%d", size); } void scan_matrix(TMatrix* matrix) { for (int i = 0; i < matrix->n; i++){ for (int j = 0; j < matrix->n; j++){ scanf("%f", &(matrix->x[matrix->n * i + j])); } } } void print_matrix(TMatrix* matrix) { for (int i=0; i < matrix->n; i++){ for (int j = 0; j < matrix->n; j++){ printf("%f ", (matrix->x[matrix->n * i + j])); } printf("\n"); } printf("\n"); } void free_matrix(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } TMatrix* matrix_add_const(TMatrix* matrix, float c) { //const TMatrix* res; alloc_matrix(&res, matrix->n); for (int i = 0; i < res->n * res->n; i++){ res->x[i] = matrix->x[i] + c; } return res; } TMatrix* matrix_multiply_const(TMatrix* matrix, float c) { //const TMatrix* res; alloc_matrix(&res, matrix->n); for (int i = 0; i < res->n * res->n; i++){ res->x[i] = matrix->x[i] * c; } return res; } TMatrix* matrixes_multiply(TMatrix* matrix1, TMatrix* matrix2) {//matrix TMatrix* res; alloc_matrix(&res, matrix1->n); /* for (int i = 0; i < res->n * res->n; i++){ for (int j = 0; j < res->n*res->n; j++) { } res->x[i] = matrix1->x[i] * matrix2->x[i]; } */ if (matrix1->n != matrix2->n){ printf("ERROR: Incorrect matrix sizes.\n"); res->n = 0; } else{ for (int i = 0; i < res->n; ++i){ for (int j = 0; j < res->n; ++j){ res->x[ res->n * i + j] = 0; for (int k = 0; k < res->n; ++k) res->x[res->n * i + j] += matrix1->x[i*res->n + k] * matrix2->x[k*res->n + j]; } } } return res; }<file_sep>#include <stdio.h> #include <math.h> int main() { float x1, y1, r1, x2, y2, r2, L; printf("Insert first circle's metrics (coordinates and radius)\n"); scanf("%f %f %f", &x1, &y1, &r1); printf("Insert second circle's metrics (coordinates and radius)\n"); scanf("%f %f %f", &x2, &y2, &r2); L = sqrt((x1 - x2)*(x1 - x2)+ (y1 - y2)* (y1 - y2)); if (x1 == x2 && y1 == y2) { if (r1 == r2) { printf("Circles are equal"); return 0; } else { printf("Circles are concentric"); return 0; } } else if (L > r1 + r2) { printf("Circles don't intersect and aren't situated inside each other"); return 0; } else if (L == r1 + r2) { printf("Circles have 1 point of intersection and aren't situated inside each other"); return 0; } else if (L < r1 + r2) { if (L < r1 || L < r2) { if (L == r1 - r2 || L == r2 - r1) { printf("Circles have 1 point of intersection while one of them is inside of another"); return 0; } else if (L < r1 - r2 || L < r2 - r1) { printf("Circles don't intersect while one of them is inside of another"); return 0; } else { printf("Circles have 2 points of intersection while one of them is inside of another"); return 0; } } else { printf("Circles have 2 points of intersection and aren't situated inside each other"); return 0; } } } <file_sep>#include <stdio.h> #include <malloc.h> #include "Matrix.h" void allocate_matrix(TDmatrix **struct_p, int size) { int i = 0; (*struct_p) = (TDmatrix*)malloc(sizeof(TDmatrix) * 1); (*struct_p)->size = size; //Determine the size of the square matrix (the size is entered from the keyboard) (*struct_p)->arr_2d = (float**)malloc(sizeof(float*) * (*struct_p)->size); for (i = 0; i < (*struct_p)->size; i++) {//Create a dynamic two-dimensional array with size size (*struct_p)->arr_2d[i] = (float*)malloc(sizeof(float) * (*struct_p)->size); } } void fill_matrix(TDmatrix *struct_p) { printf("Fill the matrix: \n"); int i = 0; int j = 0; for (i=0 ; i < struct_p->size; i++) { for (j = 0; j < struct_p->size; j++) { scanf("%f", &(struct_p->arr_2d[i][j]));//filling two-demension matrix } } } void print_matrix(TDmatrix*struct_p) { printf("Two-demension matrix: \n"); int i = 0; int j = 0; for (i=0; i < struct_p->size; i++) { printf("\n"); for (j = 0; j < struct_p->size; j++) { printf("%f ", struct_p->arr_2d[i][j]);//Outputting a square matrix } } printf("\n"); } void free_matrix(TDmatrix **struct_p) { int i = 0; for (i = 0; i < (*struct_p)->size;i++) { free((*struct_p)->arr_2d[i]); //Freeing up memory from underneath the columns } free((*struct_p)->arr_2d); //Freeing up memory from underneath the strings } TDmatrix* add_matrix(TDmatrix* matr1, TDmatrix* matr2) { TDmatrix* res1; int i = 0, j = 0; if (matr1->size != matr2->size) { printf("ERROR: Vectors should have the same lenght.\n"); exit(-100); } allocate_matrix(&res1, matr1->size); //Definition of the res matrix for (i=0; i < res1->size; i++) { for (int j = 0; j < res1->size; j++) { res1->arr_2d[i][j] = matr1->arr_2d[i][j] + matr2->arr_2d[i][j];//Add matr1 and matr2 element by element } } return res1; } TDmatrix* multi_const(TDmatrix* matr1, float c) { TDmatrix* res2; int i = 0,j=0; allocate_matrix(&res2, matr1->size); //Definition of the res matrix for (i = 0; i < matr1->size; i++) { for (int j = 0; j < matr1->size; j++) { res2->arr_2d[i][j] = matr1->arr_2d[i][j] * c;//Each element of the matrix res is multiplied by c } } return res2; } TDmatrix* add_const(TDmatrix* matr2, float c) { TDmatrix* res3; int i = 0, j =0; allocate_matrix(&res3, matr2->size); //Definition of the res matrix for (i = 0; i < matr2->size; i++) { for (int j = 0; j < matr2->size; j++) { res3->arr_2d[i][j] = matr2->arr_2d[i][j] + c;//Each element of the matrix res is added by c } } return res3; } TDmatrix* multi_matrix(TDmatrix* matr1, TDmatrix* matr2) { int k = 0; int i = 0; int j = 0; TDmatrix* res4; if (matr1->size != matr2->size) { printf("ERROR: Vectors should have the same lenght.\n"); exit(-100); } allocate_matrix(&res4, matr1->size); for (i = 0; i < res4->size; i++) { for (j = 0; j < res4->size; j++) { res4->arr_2d[i][j] = 0; } } for (i = 0; i < res4->size; i++) { while (k < res4->size) {//fix i-kth cell of matrix res for (int j = 0; j < res4->size; j++) { res4->arr_2d[i][k] += matr1->arr_2d[i][j] * matr2->arr_2d[j][k]; //matrix multiplication design } k++; } k = 0; } return res4; } <file_sep>#include <stdio.h> #include <locale.h> #include <math.h> int main() { setlocale(LC_ALL, "Rus"); float x1, y1, r1, x2, y2, r2; printf("Введите координаты и радиус первой окружности"); scanf("%f%f%f", &x1, &y1, &r1); printf("Введите координаты и радиус второй окружности"); scanf("%f%f%f", &x2, &y2, &r2); if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("Окружности равны"); return 1; } if (x1 == x2 && y1 == y2 && r1 > r2) { printf("Вторая окружность вписана впервую"); return 1; } if (x1 == x2 && y1 == y2 && r1 < r2) { printf("Первая окружность вписана в первую"); return 1; } if (sqrtf((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) == (r1 + r2)) { printf("Окружности имеют одну общую точку"); return 1; } if (sqrtf((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) >= (r1 + r2)) { printf("Окружности не имеют общих точек"); return 1; } else { printf("Окружности пресекаются в двух точках"); return 1; } return 0; } <file_sep>#include "TAgencyBook.h" #include <fstream> #include <iostream> #define NUM_EUROPE_COUNTRIES 19 string euro_zone[NUM_EUROPE_COUNTRIES] = {//list of eurozone countries "Austria", "Belgium", "Cyprus", "Estonia", "Finland", "France", "Germany", "Greece", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Portugal", "Slovakia", "Slovenia", "Croatia" }; void TAgencyBook::CountAgencies(ifstream& file) { string str; string buffer = "List agencies:"; int c = 0; int j = 0; int ch = 0; int num; int len_buffer = buffer.length(); while (!file.eof()) { getline(file, str); int len_str = str.length(); file.seekg(-1, ios_base::cur); if (str.compare(0, len_buffer, buffer, 0, len_buffer) == 0) { int i = 0; for (i = 0; i < len_str; i++) { c = str[i]; if (c >= 49 && c < 58) { int q = 1; while (str[i] != '\0') { ch = str[i]; num = static_cast<int>(ch) - 48; count_agencies *= q; count_agencies += num; if (q == 1) { q *= 10; } i++; } break; } } } if (count_agencies != 0) { file.seekg(1, ios_base::cur); break; } if (count_agencies == 0) { file.seekg(1, ios_base::cur); } } file.seekg(0, ios_base::beg); } int* TAgencyBook::CountTServices(ifstream& file) { int* num_services = nullptr; string str; string buffer = "Directions:"; int c = 0; int ch = 0; int num; int j = 0; int len_buffer = buffer.length(); num_services = new int[count_agencies]; for (int i = 0; i < count_agencies; i++) { num_services[i] = 0; } while (j < count_agencies) { getline(file, str); int len_str = str.length(); file.seekg(-1, ios_base::cur); if (str.compare(0, len_buffer, buffer, 0, len_buffer) == 0) { int i = 0; for (i = 0; i < len_str; i++) { c = str[i]; if (c >= 49 && c < 58) { int q = 1; while (str[i] != '\0') { ch = str[i]; num = static_cast<int>(ch) - 48; num_services[j] *= q; num_services[j] += num; if (q == 1) { q *= 10; } i++; } j++; break; } } } else file.seekg(1, ios_base::cur); } file.seekg(0, ios_base::beg); return num_services; } void TAgencyBook::search_string(ifstream& file) {//look for the first occurrence of the string string str; int c; int len; do { c = file.get(); } while (c == 10); file.seekg(-1, ios_base::cur); } void TAgencyBook::file_reader(ifstream& file) { string buffer; int* num_services = CountTServices(file); const string list_agencies = "List agencies:"; const string directions = "Directions:"; int len_list = list_agencies.length(); int len_directs = directions.length(); int i = 0; int j = 0; int c; agencies = new TAgency * [count_agencies]; for (i = 0; i < count_agencies; i++) { agencies[i] = new TAgency(num_services[i]); } for (i = 0; i < count_agencies; i++) { this->search_string(file); getline(file, buffer); if (buffer.compare(0, len_list, list_agencies, 0, len_list) == 0 || buffer.compare(0, len_directs, directions, 0, len_directs) == 0) { do { c = file.get(); } while (c == 10); file.seekg(-1, ios_base::cur); getline(file, agencies[i]->name); } else agencies[i]->name = buffer; for (j = 0; j < agencies[i]->num_services; j++) { search_string(file); if (j == 0) { do { c = file.get(); } while (c != 10); } getline(file, agencies[i]->services[j].country); getline(file, agencies[i]->services[j].travel_conditions); getline(file, agencies[i]->services[j].excursion_services); getline(file, agencies[i]->services[j].host_service); getline(file, agencies[i]->services[j].ticket_price); } } file.seekg(0, ios_base::beg); delete[] num_services; file.close(); } int TAgencyBook::counter_euro_agencies() { int i = 0; int j = 0; int k = 0; int flag = 0; int count_euro_agencies = 0; for (i = 0; i < count_agencies; i++) { while (j < agencies[i]->num_services) { while (k < NUM_EUROPE_COUNTRIES) { if (agencies[i]->services[j].country == euro_zone[k]) { count_euro_agencies++; flag = 1; break; } k++; } k = 0; if (flag == 1) { break; } j++; } flag = 0; j = 0; } return count_euro_agencies; } int* TAgencyBook::counter_euro_countries() { int i = 0; int j = 0; int k = 0; int* num_euro_countries = new int[count_agencies]; for (i = 0; i < count_agencies; i++) { num_euro_countries[i] = 0; } for (i = 0; i < count_agencies; i++) { while (j < agencies[i]->num_services) { while (k < NUM_EUROPE_COUNTRIES) { if (agencies[i]->services[j].country == euro_zone[k]) { num_euro_countries[i]++; break; } k++; } k = 0; j++; } j = 0; } return num_euro_countries; } TAgencyBook TAgencyBook::Get_Europe_Countries() {//find european countries and create european massive} int j = -1;//counter num_services int k = 0;//counter euro_zones int z = 0;//counter new_agencies_list TAgencyBook europeCountries; europeCountries.count_agencies = counter_euro_agencies(); int i = 0;//counter num_agencies int i_saved = -1; int* num_euro_countries = counter_euro_countries(); europeCountries.agencies = new TAgency * [europeCountries.count_agencies];//copy TAgency_array for (i = 0; i < count_agencies; i++) { if (num_euro_countries[i] == 0) { continue; } else { j++; europeCountries.agencies[j] = new TAgency(num_euro_countries[i]); } } j = i = 0; for (i = 0; i < count_agencies; i++) { i_saved++; if (num_euro_countries[i] == 0) { i_saved--; continue; } europeCountries.agencies[i_saved]->name = agencies[i]->name; while (k < NUM_EUROPE_COUNTRIES && z < num_euro_countries[i]) { if (agencies[i]->services[j].country == euro_zone[k]) {//find the European countries in the old array and insert them in the new one europeCountries.agencies[i_saved]->services[z].country = agencies[i]->services[j].country; europeCountries.agencies[i_saved]->services[z].travel_conditions = agencies[i]->services[j].travel_conditions; europeCountries.agencies[i_saved]->services[z].excursion_services = agencies[i]->services[j].excursion_services; europeCountries.agencies[i_saved]->services[z].host_service = agencies[i]->services[j].host_service; europeCountries.agencies[i_saved]->services[z].ticket_price = agencies[i]->services[j].ticket_price; z++; j++; k = 0; } else { k++; if (k == NUM_EUROPE_COUNTRIES) { j++; k = 0; } } } z = 0; j = 0; } delete[] num_euro_countries; return europeCountries; } TAgencyBook::TAgencyBook() { agencies = nullptr; count_agencies = 0; } TAgencyBook::TAgencyBook(const string& path) : TAgencyBook() { try { ifstream file; file.open(path); if (file.is_open() == 0) { FileExeption f_ex = FileExeption::NullPtrFile; throw f_ex;//generate object type of exeption } CountAgencies(file); file_reader(file); } catch (FileExeption f_ex) { cout << "File not found! The programm is over with code " << static_cast<int>(f_ex) << endl; } } const TAgencyBook& TAgencyBook::operator=(const TAgencyBook& obj) { count_agencies = obj.count_agencies; agencies = new TAgency * [count_agencies]; for (int i = 0; i < count_agencies; i++) { agencies[i]->num_services = obj.agencies[i]->num_services; agencies[i]->name = obj.agencies[i]->name; agencies[i]->num_services = obj.agencies[i]->num_services; agencies[i]->services = new TService[agencies[i]->num_services]; for (int i = 0; i < count_agencies; i++) { for (int j = 0; j < agencies[i]->num_services; j++) { agencies[i]->services[j].country = obj.agencies[i]->services[j].country; agencies[i]->services[j].travel_conditions = obj.agencies[i]->services[j].travel_conditions; agencies[i]->services[j].excursion_services = obj.agencies[i]->services[j].excursion_services; agencies[i]->services[j].host_service = obj.agencies[i]->services[j].country; agencies[i]->services[j].ticket_price = obj.agencies[i]->services[j].ticket_price; } } } return *this; } TAgencyBook::TAgencyBook(const TAgencyBook& object) { count_agencies = object.count_agencies; agencies = new TAgency * [count_agencies]; for (int i = 0; i < object.count_agencies; i++) { agencies[i] = new TAgency(*(object.agencies[i])); } } TAgencyBook::~TAgencyBook() { delete[] agencies; } TAgency::~TAgency() { delete[] services; } TAgency::TAgency() { num_services = 0; name = ""; services = nullptr; } TAgency::TAgency(int num_services) { this->num_services = num_services; services = new TService[num_services];//creating a service structure for each facility } TAgency::TAgency(const TAgency& object) { num_services = object.num_services; services = new TService[num_services]; name = object.name; for (int i = 0; i < num_services; i++) { services[i] = TService(object.services[i]); } } ostream& operator<<(ostream& stream, const TAgencyBook& obj) { for (int i = 0; i < obj.count_agencies; i++) { cout << obj.agencies[i]->name << endl; for (int j = 0; j < obj.agencies[i]->num_services; j++) { cout << obj.agencies[i]->services[j].country << endl; cout << obj.agencies[i]->services[j].travel_conditions << endl; cout << obj.agencies[i]->services[j].excursion_services << endl; cout << obj.agencies[i]->services[j].host_service << endl; cout << obj.agencies[i]->services[j].ticket_price << endl; cout << endl; } } return stream; } TService::TService() { country = ""; travel_conditions = ""; excursion_services = ""; host_service = ""; ticket_price = ""; } TService::TService(const TService& obj) { country = obj.country; travel_conditions = obj.travel_conditions; excursion_services = obj.excursion_services; host_service = obj.host_service; ticket_price = obj.ticket_price; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" void allocate_matrix(TMatrix** matrix, int n) { (*matrix) = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n*n; (*matrix)->x = (int*)malloc(sizeof(int) * n * n); } void fill_matrix(TMatrix* matrix, int n) { int i = 0; for (; i < n; i++) { int j = 0; for (; j < n; j++) { scanf("%d", &(matrix->x[i * n + j])); } } printf("\n"); } void print_matrix(TMatrix* matrix, int n) { int j = 0; for (; j < n; j++) { for (int i = 0; i < n; i++) { printf("%d ", matrix->x[j * n + i]); } printf("\n"); } printf("\n"); } void free_matrix(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2, int n) { TMatrix* res; int i = 0; allocate_matrix(&res, n); for (; i < res->n; i++) { res->x[i] = matrix1->x[i] + matrix2->x[i]; } return res; } TMatrix* add_const(TMatrix* matrix, int n) { TMatrix* res; int i = 0; allocate_matrix(&res, matrix->n); for (; i < res->n; i++) { res->x[i] = matrix->x[i] + n; } return res; } TMatrix* multi_const(TMatrix* matrix, int n) { TMatrix* res; int i = 0; allocate_matrix(&res, matrix->n); for (; i < res->n; i++) { res->x[i] = matrix->x[i] * n; } return res; } TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2, int n) { TMatrix* res; int k = 0; allocate_matrix(&res, matrix1->n); int i = 0, j = 0, flag = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { res->x[i*n+j] = 0; for (k = 0; k < n; k++) { res->x[i*n+j] += matrix1->x[i * n + k] * matrix2->x[k * n + j]; } } } return res; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 10 char* codes[N] = { "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009" }; int price[N] = { 62, 100, 50, 35, 80, 73, 27, 94, 15, 30 }; float discount[N] = { 0.1, 0.25, 0.15, 0.5, 0.0, 0.5, 0.1, 0.2, 0.0, 0.0 }; char* products[N] = { "Milk", "Lemon", "Tomato", "Potato", "Eggs", "Apples", "Onion", "Cheese", "Bread", "Oil" }; void scan(int* arr) { int i, j; float priceWD; char a[5]; printf("Welcome!\nScan your codes.\nEnter 0 to print check.\n"); do { printf("Enter codes\n"); gets(a); j = 0; for (i = 0; i < N; i++) { if (strcmp(codes[i], a) == 0) { arr[i]++; priceWD = price[i] - discount[i] * price[i]; printf("%s, price: %.2d rubles, discount: %.2f, total cost is %.2f rubles\n", products[i], price[i], discount[i] * 100, priceWD); j = 1; } } if ((j == 0) && (strcmp(a, "0") != 0)) { printf("There is no such code. Check it and try again.\n"); } } while (strcmp(a, "0")); } void print_check(int* arr) { int i, sum = 0; float sumD = 0, total_sum = 0, priceDD; for (i = 0; i < N; i++) { if (arr[i] > 0) { sum = price[i] * arr[i] + sum; priceDD = (price[i] - price[i] * discount[i]) * arr[i]; total_sum = total_sum + priceDD; sumD = sumD + (price[i] * discount[i]) * arr[i]; printf("%10s, price: %d, count: %d, price with discount: %.2f\n", products[i], price[i], arr[i], priceDD); } } printf("\t\nPrice: %d, Discount: %.2f, Total price: %.2f\n", sum, sumD, total_sum); } int main() { int count[N] = { 0 }; scan(count); print_check(count); return 0; } <file_sep>#include <stdio.h> #include <math.h> int main() { float r1, r2, x1, y1, x2, y2; float rasti; float summa_between_radius, difference_between_radius; printf("Enter x1 y1\n"); scanf("%f %f", &x1, &y1); printf("Enter x2 y2\n"); scanf("%f %f", &x2, &y2); printf("Enter r1 r2\n"); scanf("%f %f", &r1, &r2); rasti = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); difference_between_radius = abs(r2 - r1); summa_between_radius = (r1 + r2); if (rasti > summa_between_radius) { printf("No matul points"); return 0; } if (rasti == summa_between_radius) { printf("External Tangency of circles"); return 0; } if ((rasti > difference_between_radius) && (summa_between_radius > rasti)) { printf("circles intersect"); return 0; } if ((rasti >= 0) && (difference_between_radius > rasti)) { printf("No matual points.One cercle in incribed in another"); return 0; } if ((r1 == r2) && (x1 == x2) && (y1 == y2)) { printf("Circles Coincide"); return 0; } if (rasti == difference_between_radius) { printf("Internal Tangency of circles"); return 0; } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include <windows.h> #include "userSide.h" #include "fileProcessing.h" char* switch_form(EducationalForm form) { char name_form[MAX_NAME]; switch (form) { case DNEV: strcpy(name_form, "Дневная"); break; case VECHER: strcpy(name_form, "Вечерняя"); break; case ZAOCH: strcpy(name_form, "Заочная"); break; } return name_form; } int getting_univ(University_t* uns, int c, char in[]) { int ind; do { gets(in); ind = check_index_univ(uns, c, in); if (ind == -1) { printf("Такого ВУЗа нет, попробуйте ещё раз\n"); } } while (ind == -1); return ind; } void entering_mode(char in[]) { gets(in); while (strcmp(in, "1") != 0 && strcmp(in, "2") != 0) { printf("Не корректный ввод, попробуйте ещё раз, следуйте инструкциям!\n"); gets(in); } } void main_entering_mode(char in[]) { gets(in); while (strcmp(in, "1") != 0 && strcmp(in, "2") != 0 && strcmp(in, "0") != 0) { printf("Не корректный ввод, попробуйте ещё раз, следуйте инструкциям!\n"); gets(in); } } void print_minimal_spec(University_t* uns, int c, char name_univ[MAX_LEN_ANSWER], int ind) { int min = 1000, i, j; EducationalForm edForm; char name_form[MAX_NAME]; char name_spec[MAX_NAME]; for (i = 0; i < uns[ind].n_spec; i++) { for (j = 0; j < uns[ind].specs[i].n_form; j++) { if (uns[ind].specs[i].examScores[j] < min) { min = uns[ind].specs[i].examScores[j]; edForm = uns[ind].specs[i].forms[j]; strcpy(name_spec, uns[ind].specs[i].name); } } } switch (edForm) { case 0: strcpy(name_form, "Дневная"); case 1: strcpy(name_form, "Вечерняя"); case 2: strcpy(name_form, "Заочная"); } printf("Минимальный балл для поступления в ВУЗе %s: %d, это %s форма обучения по специальности: %s\n", name_univ, min, name_form, name_spec); } void print_all_about_univ(University_t* uns, int c, char name_univ[MAX_LEN_ANSWER], int ind) { int i, j, sum_costs = 0, sum_examRes = 0, count = 0; printf("Информация о ВУЗе %s:\n", name_univ); printf("ВУЗ %s имеет %d специальностей:\n", name_univ, uns[ind].n_spec); for (i = 0; i < uns[ind].n_spec; i++) { printf(" %s\n", uns[ind].specs[i].name); } for (i = 0; i < uns[ind].n_spec; i++) { for (j = 0; j < uns[ind].specs[i].n_form; j++) { sum_costs += uns[ind].specs[i].costs[j]; sum_examRes += uns[ind].specs[i].examScores[j]; count++; } } printf("Средний балл для поступления по ВУЗу: %.2lf; Средняя стоимость обучения по ВУЗу: %.2lf\n\n", (double)sum_examRes / count, (double)sum_costs / count); } int check_index_univ(University_t* uns, int c, char name_univ[MAX_LEN_ANSWER]) { int i; for (i = 0; i < c; i++) { if (!strcmp(name_univ, uns[i].name)) { return i; } } return -1; } void about_univercity(University_t* uns, int c) { char in[MAX_LEN_ANSWER]; int univ_ind; printf("Выберите интересующую вас информацию:\n"); printf("Всё о конкретном ВУЗе - введите 1;\nСпециальность с минимальным баллом в конкретном ВУЗе - введите 2;\n"); entering_mode(in); if (!strcmp(in, "1")) { printf("Вы выбрали 'Всё о конкретном ВУЗе'\nВведите название вуза:\n"); univ_ind = getting_univ(uns, c, in); print_all_about_univ(uns, c, in, univ_ind); } else if (!strcmp(in, "2")) { printf("Вы выбрали 'Специальность с минимальным баллом в конкретном ВУЗе'\nВведите название вуза:\n"); univ_ind = getting_univ(uns, c, in); print_minimal_spec(uns, c, in, univ_ind); } } void getting_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]) { gets(name_spec); while (!check_existing_spec(uns, c, name_spec)) { printf("Такой специальности не нашлось ни у одного ВУЗа из нашей базы, попробуйте ещё раз\n"); gets(name_spec); } } void about_spec(University_t* uns, int c) { char in[MAX_LEN_ANSWER]; printf("Выберите интересующую вас информацию:\n"); printf("Всё о специальности - введите 1;\nМинимальный балл по специальности среди вузов - введите 2;\n"); entering_mode(in); if (!strcmp(in, "1")) { printf("Вы выбрали 'Всё о специальности'\nВведите название специальности:\n"); getting_spec(uns, c, in); print_all_about_spec(uns, c, in); } else if (!strcmp(in, "2")) { printf("Вы выбрали 'Минимальный балл по специальности среди вузов'\nВведите название специальности:\n"); getting_spec(uns, c, in); print_min_score_for_spec(uns, c, in); } } int check_existing_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]) { int i, j; for (i = 0; i < c; i++) { for (j = 0; j < uns[i].n_spec; j++) { if (!strcmp(uns[i].specs[j].name, name_spec)) { return 1; } } } return 0; } void print_all_about_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]) { int i, j, z; char name_form[MAX_NAME]; EducationalForm edForm; printf("Специальность %s присутствует в следующем перечне ВУЗов:\n", name_spec); for (i = 0; i < c; i++) { for (j = 0; j < uns[i].n_spec; j++) { if (!strcmp(uns[i].specs[j].name, name_spec)) { printf("%s: \n", uns[i].name); printf(" В этом ВУЗе по этой специальности представлено %d форм:\n", uns[i].specs[j].n_form); for (z = 0; z < uns[i].specs[j].n_form; z++) { edForm = uns[i].specs[j].forms[z]; strcpy(name_form, switch_form(edForm)); printf(" %s:: проходные баллы: %d; стоимость обучения: %d \n", name_form, uns[i].specs[j].examScores[z], uns[i].specs[j].costs[z]); } } } } } void print_min_score_for_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]) { int i, j, z, min = 1000; char name_form[MAX_NAME], name_univ[MAX_NAME]; EducationalForm edForm; for (i = 0; i < c; i++) { for (j = 0; j < uns[i].n_spec; j++) { if (!strcmp(uns[i].specs[j].name, name_spec)) { for (z = 0; z < uns[i].specs[j].n_form; z++) { if (uns[i].specs[j].examScores[z] < min) { min = uns[i].specs[j].examScores[z]; edForm = uns[i].specs[j].forms[z]; strcpy(name_form, switch_form(edForm)); strcpy(name_univ, uns[i].name); } } } } } printf("По указанной специальности минимальный проходной балл по ВУЗам НН составляет: %d. ВУЗ: %s, форма обучения: %s", min, name_univ, name_form); } void working_with_user(University_t* uns, int c) { int end = 1; printf("Что бы вы хотели узнать?\n"); while (end) { char in[MAX_LEN_ANSWER]; printf("Если интересует информация о конкретном ВУЗе - нажмите 1, если о конкретной специальности - 2;\n"); printf("Если же узнали всю необходимую информацию и хотите завершить сессию - нажмите 0;\n\n"); main_entering_mode(in); if (!strcmp(in, "1")) { about_univercity(uns, c); } else if (!strcmp(in, "2")) { about_spec(uns, c); } else if (!strcmp(in, "0")) { printf("Спасибо, что выбрали нас, до скорых встреч!\n"); end = 0; } printf("\n\n"); } }<file_sep>#include <iostream> #include <clocale> #include "windows.h" #include "container.h" #include "products.h" #include "database.h" #include "receipt.h" #include "display.h" using namespace std; int main() { setlocale(LC_ALL, "rus"); try { TDataBase data; int data_update = 0; // 0 - файлы базы данных обновляться/архивироваться не будут int data_archive = 0; // 1 - Вносятся изменения в файл базы данных / создается архив базы данных TContainer<TReceipt> check; string code; int ans = -1; int startmenu_ans = 1; int scanmode = 0; if (data_archive) { data.ArchiveData(); } while (1) { TReceipt tmp_check; check.Add(tmp_check); int ind = check.Count() - 1; system("cls"); dsp::StartMenu(); cin >> startmenu_ans; // Если 0 - удаление пустого чека из контейнера и выход из цикла if (!startmenu_ans) { check.Del(ind); break; } while (1) { system("cls"); dsp:: MainMenu(); dsp::ScanAns(ans); // Отсканировать товары if (ans == 1) { while (1) { int scan_ans = 0; system("cls"); if (check[ind].Count()) { cout << "Последний отсканированный товар: " << endl; check[ind].Show(); cout << endl; } cout << "1. Начать сканирование." << endl; cout << "2. Режим: "; if (scanmode) { cout << "Вводить количество продукта" << endl; } else { cout << "Не вводить количество продукта" << endl; } cout << "Чтобы закончить сканирование, введите 0.\n" << endl; dsp::MenuScanAns(scan_ans); if (scan_ans == 1) { while (1) { system("cls"); if (check[ind].Count()) { cout << "Последний отсканированный товар: " << endl; check[ind].LastScan(); cout << endl; } cout << "Введите код товара:" << endl; cin >> code; if (code == "0") break; else { TReceiptLine prod; int count = 1; if (scanmode && (data.Check(code) != -1)) { cout << "Введите количество продукта:" << endl; do { cin >> count; } while (count <= 0); } if (prod.Scan(data, code, count)) { int tottal_pcount = check[ind].FindCount(prod) + count; int data_pcount = data.GetProductCount(code); if (tottal_pcount > data_pcount) { cout << "Недостаточно товара на складе." << endl; dsp::Press2Continue(); } else { check[ind].Add(prod, count); } } } } } else if (scan_ans == 2) { if (scanmode) scanmode = 0; else scanmode = 1; } else { break; } } } // Оплатить if (ans == 2) { system("cls"); if (!check[ind].Count()) { cout << "Ваша корзина пуста." << endl; dsp::Press2Continue(); } else { check[ind].Cart(); cout << "Сумма к оплате: " << check[ind].GetSum() << endl; cout << "\nОплата: "; double money; cin >> money; if (money < check[ind].GetSum()) { cout << "ОШИБКА. Недостаточно денег."; dsp::Press2Continue(); } else { system("cls"); check[ind].SetCLOCK(); check[ind].SetCode(check.Count()); check[ind].Payment(data, money); dsp::Press2Continue(); break; } } } // Посмотреть корзину else if (ans == 3) { system("cls"); if (!check[ind].Count()) { cout << "Ваша корзина пуста." << endl; dsp::Press2Continue(); } else { check[ind].Cart(); cout << "Сумма: " << check[ind].GetSum() << endl; dsp::Press2Continue(); } } // Удалить товар из корзины else if (ans == 4) { if (!check[ind].Count()) { system("cls"); cout << "Ваша корзина пуста." << endl; dsp::Press2Continue(); } else { int del_ans = 0; while (1) { system("cls"); check[ind].Cart(); cout << "Сумма: " << check[ind].GetSum() << endl; cout << "\nВведите номер товара, который хотите удалить." << endl; cout << "Для выхода введите 0.\n" << endl; cin >> del_ans; if (del_ans) check[ind].Del(del_ans - 1); else break; } } } else if (ans == 0) { check.Del(ind); break; } } } if (data_update) { data.UpdateData(); } } catch (const std::exception &exp) { cout << exp.what() << endl; } cout << "END!" << endl; return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> int random_function(int start, int end) { int n; srand(time(NULL)); n = start + rand() % (end - start); return n; } int main() { int guess, n, c_diff, choice,i=0; n = random_function(1, 1000); printf("Select game mode:\n"); printf("1. Guessing me\n"); printf("2. Guessing programm\n"); scanf("%d", &choice); if (choice != 1 && choice != 2) { printf("Error!"); return 1; } switch (choice) { case 1: { printf("1. Easy: two hundred twenty five attempts\n"); printf("2. Medium: one hundred fifteen attempts\n"); printf("3. Hard: five attempts\n"); printf("Select difficulty:\n"); scanf("%d", &c_diff); if (c_diff != 1 && c_diff != 2 && c_diff != 3) { printf("Please, input correct data"); return 1; } switch (c_diff) { case 1: { int n1 = 225; printf("Let`s start the game!Try to win!\n"); for (i; i < n1;) { i++; scanf("%d", &guess); if (guess > 1000 || guess < 1) { printf("Error!Incorrect data"); return 1; } if (guess == n) { printf("You guessed it!\n"); printf("Used attempts: %d\n", i); return 0; } else if (guess != n && guess > n) { printf("Assumption is bigger than the puzzle\n"); } else printf("Assumption is smaller than the puzzle\n"); } {printf("You didn`t riddled!\n"); printf("Used attempts: %d\n", i); } break; } case 2: { int n2 = 115; printf("Let`s start the game!Try to win!\n"); for (i; i < n2;) { i++; scanf_s("%d", &guess); if (guess > 1000 || guess < 1) { printf("Error!Incorrect data"); return 1; } if (guess == n) { printf("You guessed it!\n"); printf("Used attempts: %d\n", i); return 0; } else if (guess != n && guess > n) { printf("Assumption is bigger than the puzzle\n"); } else printf("Assumption is smaller than the puzzle\n"); } {printf("You didn`t riddled!\n"); printf("Used attempts: %d\n", i); } break; } case 3: { int n3 = 5; printf("Let`s start the game!Try to win!\n"); for (i; i < n3;) { i++; scanf("%d", &guess); if (guess > 1000 || guess < 1) { printf("Error!Incorrect data"); return 1; } if (guess == n) { printf("You guessed it!\n"); printf("Used attempts: %d\n", i); return 0; } else if (guess > n) { printf("Assumption is bigger than the puzzle\n"); } else printf("Assumption is smaller than the puzzle\n"); } {printf("You didn`t riddled!\n"); printf("Used attempts: %d\n", i);} break; } } } break; case 2: { int i = 0, n4 = 225, n5 = 115, n6 = 5,choice_n, new_n, up=1000, down= 1,user_number; char my_answer; new_n = random_function(1, 1000); choice_n = random_function(1, 3); printf("Riddle your number 1-1000: \n"); scanf("%d", &user_number); printf("\n"); if (user_number > 1000 || user_number < 1) { printf("Incorrect data!\n"); return 1; } printf("Select difficulty game mode:\n"); printf("1. Easy: two hundred twenty five attempts\n"); printf("2. Medium: one hundred fifteen attempts\n"); printf("3. Hard: five attempts\n"); printf("Programm: my choice %d\n", choice_n); switch (choice_n) { case 1: { printf("Let`s start the game!Try to win!\n"); while (i <= n4) { i++; printf("Maybe you riddled the number %d?\n", new_n); scanf("%c", &my_answer); my_answer = getchar(); if (my_answer != '>' && my_answer != '<' && my_answer != '=') { printf("Ooops, mistake!\n"); return 1; } if (my_answer == '>') { down = new_n+1; new_n = random_function(new_n, up); } else if (my_answer == '<') { up = new_n-1; new_n = random_function(down, new_n); } else if (my_answer == '=') { printf("My congrats!You guessed!\n"); printf("Used attempts: %d\n", i); break; } } break; } case 2: { printf("Let`s start the game!Try to win!\n"); while (i <= n5) { i++; printf("Maybe you riddled the number %d?\n", new_n); scanf("%c", &my_answer); my_answer = getchar(); if (my_answer != '>' && my_answer != '<' && my_answer != '=') { printf("Ooops, mistake!\n"); return 1; } if (my_answer == '>') { down = new_n+1; new_n = random_function(new_n, up); } else if(my_answer == '<'){ up = new_n-1; new_n = random_function(down, new_n); } else if (my_answer == '=') { printf("My congrats!You guessed!\n"); printf("Used attempts: %d\n", i); break; } } break; } case 3: { printf("Let`s start the game!Try to win!\n"); while (i <= n6) { i++; printf("Maybe you riddled the number %d?\n", new_n); scanf("%c", &my_answer); my_answer = getchar(); if (my_answer != '>' && my_answer != '<' && my_answer != '=') { printf("Ooops, mistake!\n"); return 1; } if (my_answer == '>') { down = new_n+1; new_n = random_function(new_n, up); } else if (my_answer == '<') { up = new_n-1; new_n = random_function(down, new_n); } else if (my_answer == '=') { printf("My congrats!You guessed!\n"); printf("Used attempts: %d\n", i); break; } } break; } } } } printf("Game over"); return 0; } <file_sep>#include <stdio.h> #include <math.h> int main() { double h, w, d, m_dsp, m_dvp, m_wood, res_M; int num_of_shelves, GAP = 40; //gap - промежуток между полками double D_WOOD = 0.55, D_DSP = 0.65, D_DVP = 0.8; // Константы плотности в г/см^3 printf("Enter every sizes in sm!!! in order: height, width, depth\n"); scanf_s("%lf%lf%lf", &h, &w, &d); if (w > 120 || w < 80 || d > 90 || d < 50 || h > 220 || h < 180) { printf("Data is incorrect"); return 1; } num_of_shelves = ceil(h / (double)GAP) - 1; // толщина полок не учитывается, считается = 0 // Если у верхней полки есть хоть какое-то расстояние до верхней крыжки - полку можно поставить // просчитаем массы частей в граммах! m_dsp = (2 * h * d * 1.5 + 2 * (w - 3) * d * 1.5 + num_of_shelves * 1.5 * d * (w - 3)) * D_DSP; // две боковины, верхняя и нижняя крышка, полки m_dvp = (h * w * 0.5) * D_DVP; // Задняя стенка m_wood = (h * w) * D_WOOD; // общая масса в КГ res_M = (m_dsp + m_dvp + m_wood) / 1000; printf("Your wardrobe weighs: %lf kg", res_M); return 0; }<file_sep>#include <iostream> #include <fstream> #include <sstream> #include "lib.h" bool cardIndex::operator==(const string& otherTitle) const { return (title == otherTitle); } bool cardIndex::operator!=(const string& otherTitle) const { return !(title == otherTitle); } ostream& operator<<(ostream& os, const cardIndex& card) { os << "Title: " << card.title << endl; os << "Authors: "; for (int i = 0; i < card.authorsCount; i++) { os << card.authors[i]; if (i < card.authorsCount - 1) { os << ", "; } } os << endl; os << "Publisher: " << card.publisher << endl; os << "Section: " << card.section << endl; os << "Availability: " << (card.avb == availability::available ? "Available" : "Not available") << endl; os << "Evaluation: " << card.evaluation << endl; os << "-----------------------" << endl; return os; } string menu() { string path; while (true) { cout << "Enter the file path..." << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } cout << "ERROR: Could not open file!\n" << endl; } } int lib::strCount(const string& path) { int count = 0; string line; ifstream file(path); while (getline(file, line)) { if (!line.empty()) { count++; } } file.close(); return count; } lib::lib(const string& path) { int j = 0; this->count = strCount(path); this->cards = new cardIndex[count]; ifstream file(path); string line; while (getline(file, line)) { if (line.empty()) { continue; } stringstream ss(line); string item; cardIndex card; getline(ss, item, ';'); stringstream authorsStream(item); string author; card.authorsCount = 0; while (getline(authorsStream, author, ',')) { card.authorsCount++; } card.authors = new string[card.authorsCount]; stringstream authorsStream2(item); int i = 0; while (getline(authorsStream2, author, ',')) { card.authors[i] = author; i++; } getline(ss, card.title, ';'); getline(ss, card.publisher, ';'); getline(ss, card.section, ';'); string availabilityStr; getline(ss, availabilityStr, ';'); if (availabilityStr == "Available") { card.avb = available; } else { card.avb = not_available; } string evaluationStr; getline(ss, evaluationStr, ';'); card.evaluation = stof(evaluationStr); this->cards[j] = card; j++; } file.close(); } lib::~lib() { for (int i = 0; i < this->count; i++) { delete[] this->cards[i].authors; } delete[] this->cards; } set <string> lib::booksBySection() { set <string> sections; for (int i = 0; i < this->count; i++) { sections.insert(this->cards[i].section); } for (string s : sections) { cout << "\nBooks from " << s << endl; for (int j = 0; j < this->count; j++) { if (this->cards[j].section == s) { cout << this->cards[j]; } } } return sections; } vector <cardIndex> lib::findBooks(const set <string>& sections) { vector <cardIndex> books; cout << "Available sections:" << endl; for (auto it = sections.begin(); it != sections.end(); it++) { cout << *it << endl; } string requestedSection; do { cout << "Enter the section you are interested in: "; getline(cin, requestedSection); auto it = sections.find(requestedSection); if (it != sections.end()) { break; } } while (true); cout << "Books in section \"" << requestedSection << "\":" << endl; for (int i = 0; i < this->count; i++) { if (this->cards[i].section == requestedSection) { books.push_back(this->cards[i]); cout << "- " << this->cards[i].title << endl; } } return books; } void lib::getBook(const vector <cardIndex>& books) { string requestedTitle; do { cout << "Enter the title of the book you are interested in: "; getline(cin, requestedTitle); for (int i = 0; i < books.size(); i++) { if (books[i] == requestedTitle) { cout << books[i]; return; } } } while (true); } <file_sep>#include <iostream> #include <cstring> #include <fstream> #include <string> #include "header.h" using namespace std; int main() { int size = cntLines("sklad.txt"); Product* p; allocate_sklad(p, size); fill_sklad(p, size, "sklad.txt"); find_null(p,size); free_sklad(p, size); } <file_sep>#ifndef _HEADER_H #define _HEADER_H #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <stdio.h> const int STEP = 10; class TProductsDatabase; class TReceipt; class TReceiptLine; template <typename T> class TContainer { private: int size; int max_size; int step; int current_index; T* elements; void realloc(); public: TContainer(); TContainer(int, int); TContainer(const TContainer<T>& c); ~TContainer(); T& operator[] (int); const T& operator[] (int) const; const TContainer& operator=(const TContainer& c); friend std::ostream& operator<<(std::ostream& out, const TContainer<T>& c) { for (int i = 0; i < c.size; i++) { out << c.elements[i]; } return out; } int Get_size() const; void insert(const T&); void insert_forward(const T&); void insert_back(const T&); void remove(const int); void remove(const T&); void remove_forward(); void remove_back(); int find_elem(const T&); void reset(); T& next(); T& previous(); T& current(); bool IsEnded(); }; struct TProduct { long code; std::string name; double cost; bool operator==(const TProduct&) const; friend std::ostream& operator<<(std::ostream&, const TProduct&); }; struct TInfoProduct { TProduct product; int count; bool operator==(const TInfoProduct&) const; }; class TReceiptLine { private: TProduct product; int count; double sum_cost; public: TReceiptLine(); TReceiptLine(TProduct&, int, double); TReceiptLine(const TReceiptLine&); const TReceiptLine& operator= (const TReceiptLine&); bool operator==(const TReceiptLine&) const; friend std::ostream& operator<<(std::ostream& out, const TReceiptLine& rec_line); const TProduct& Get_product() const; int Get_count() const; double Get_sum_cost() const; void Set_count(int); void Set_sum_cost(double); }; struct TDate { int day; int month; int year; TDate(); }; struct TTime { int hour; int minute; int second; TTime(); }; class TReceipt { private: static long code; TDate date; TTime time; TContainer<TReceiptLine> products; static void Code_increase(); int get_barcode_delete(TProductsDatabase& db); int get_barcode_add(TProductsDatabase& db); public: TReceipt(); TReceipt(const TReceipt&); TReceiptLine& operator[](int); friend std::ostream& operator<<(std::ostream& out, TReceipt& rec); const TReceipt& operator= (const TReceipt&); int Find_product(const long) const; int Get_num_products() const; void Add_new_prod(const TReceiptLine&); double Get_total_sum() const; void Get_data_n_time(); void Delete_prod(const int ind); void Delete(TProductsDatabase& db); void Add(TProductsDatabase& db); }; class TProductsDatabase { private: TContainer<TInfoProduct> productsInStock; void get_correct_file_name(const std::string& fname) const; bool check_file_name(const std::string& fname) const; public: TProductsDatabase(const std::string& filename); TInfoProduct& operator[](int); int barcode_search(const long barcode); int Get_num_prods() const; void Updating_data_remove(const TProduct& prod); void Updating_data_add(const TProduct& prod); void create_updating_db(); }; // T_CONTAINER: // Constructors&destructors template <typename T> TContainer<T>::TContainer() { size = 0; max_size = 0; step = STEP; current_index = -1; elements = nullptr; } template <typename T> TContainer<T>::TContainer(int max_size, int step_value) { size = 0; current_index = -1; step = step_value; this->max_size = max_size; elements = new T[max_size]; } template <typename T> TContainer<T>::TContainer(const TContainer<T>& c) { size = c.size; step = c.step; current_index = c.current_index; max_size = c.max_size; elements = new T[max_size]; for (int i = 0; i < size; i++) { elements[i] = c.elements[i]; } } template <typename T> TContainer<T>::~TContainer() { if (elements != nullptr) { delete[] elements; } } // overloading template <typename T> const TContainer<T>& TContainer<T>::operator=(const TContainer<T>& c) { if (this == &c) return (*this); size = c.size; max_size = c.max_size; step = c.step; current_index = c.current_index; if (elements) { delete[] elements; } elements = new T[max_size]; for (int i = 0; i < size; i++) { elements[i] = c.elements[i]; } return (*this); } template <typename T> const T& TContainer<T>::operator[] (int ind) const { if (ind >= max_size || ind < 0) throw "Index out of range"; return elements[ind]; } template <typename T> T& TContainer<T>::operator[] (int ind) { if (ind >= max_size || ind < 0) throw "Index out of range"; current_index = ind; return elements[ind]; } // methods template <typename T> void TContainer<T>::insert(const T& elem) { if (size == max_size) { realloc(); } elements[size] = elem; current_index = size; size++; } template <typename T> void TContainer<T>::insert_forward(const T& elem) { if (size == max_size) { realloc(); } T* tmp = new T[max_size]; int i; for (i = 0; i <= current_index; i++) { tmp[i] = elements[i]; } tmp[i] = elem; for (; i < size; i++) { tmp[i + 1] = elements[i]; } delete[] elements; elements = tmp; current_index++; size++; } template <typename T> void TContainer<T>::insert_back(const T& elem) { if (size == max_size) { realloc(); } T* tmp = new T[max_size]; int i; for (i = 0; i < current_index; i++) { tmp[i] = elements[i]; } tmp[i] = elem; for (; i < size; i++) { tmp[i + 1] = elements[i]; } delete[] elements; elements = tmp; size++; } template <typename T> void TContainer<T>::realloc() { max_size = max_size + step; T* tmp = new T[max_size]; for (int i = 0; i < size; i++) { tmp[i] = elements[i]; } delete[] elements; elements = tmp; } template <typename T> void TContainer<T>::remove(const int ind) { if (ind < 0 or ind >= size) throw "Incorrect index"; T* tmp = new T[max_size]; for (int i = 0; i < ind; i++) { tmp[i] = elements[i]; } for (int i = ind; i < size - 1; i++) { tmp[i] = elements[i + 1]; } delete[] elements; elements = tmp; size--; } template <typename T> void TContainer<T>::remove(const T& elem) { int index = find_elem(elem); if (index == -1) return; this->remove(index); } template <typename T> void TContainer<T>::remove_forward() { this->remove(current_index + 1); } template <typename T> void TContainer<T>::remove_back() { this->remove(current_index - 1); } template <typename T> void TContainer<T>::reset() { current_index = 0; } template <typename T> int TContainer<T>::find_elem(const T& elem) { for (int i = 0; i < size; i++) { if (elements[i] == elem) { return i; } } return -1; } template <typename T> T& TContainer<T>::next() { if (current_index == -1) throw std::exception("Conteiner is Empty! Isert some element in it"); if (current_index >= size - 1) throw std::exception("Index out of range"); current_index++; return elements[current_index]; } template <typename T> T& TContainer<T>::previous() { if (current_index == -1) throw std::exception("Conteiner is Empty! Isert some element in it"); if (current_index < 1) throw std::exception("Index out of range"); current_index--; return elements[current_index]; } template <typename T> T& TContainer<T>::current() { if (current_index == -1) throw std::exception("Conteiner is Empty! Isert some element in it"); return elements[current_index]; } template <typename T> bool TContainer<T>::IsEnded() { return current_index == (size - 1); } template <typename T> int TContainer<T>::Get_size() const { return size; } #endif<file_sep>#include <stdio.h> #include <string.h> #define AMOUNT (sizeof(product)/ sizeof(product[0])) struct goods { const char* name; const char* description; double price; const char* barcodes; int discount; }; struct goods product[]={ {"cabbage", "This is an average head of an average cabbage", 54.99, "1613", 46}, {"carrot", "A carrot. Just a carrot...", 9.99, "5144", 4}, {"candies", "Sweet! Some candies!",89.99 ,"3134", 28}, {"spaghetti", "Spaghetti italian",79.99 ,"4114", 8}, {"zucchini", "Zucchini - schiacciata italian",49.99 ,"6613", 5}, {"cheese", "Cheese, not cheese",239.99 ,"1117", 21}, {"tomato", "Tomato is like an apple but better",14.99 ,"1335", 25}, {"bacon", "Bacon - cool part of a cool pig",149.99 ,"0552", 2}, {"lettuce", "Lettuce - when cabbage is not an option",29.99 ,"3333", 16}, {"chicken", "Chicken... KFC...",199.99 ,"2015", 17}, {"muffin", "Muffin - Delicious small piece of a cake",74.99 ,"4497", 16}, {"pickles", "Pickles are just forgotten cucumbers in a jar...",319.99 ,"2395", 14}, {"mushroom", "Mushroom - \"it's me, Mario!\"", 29.99, "0000", 38}, }; int products[AMOUNT] = {0}; double cost = 0; double cost_without_discounts = 0; void rules(){ printf ("All items scaned automatically\n"); printf("c - print check\n"); printf("f - sum up and show final cost\n"); printf("All barcodes:\n"); for (int i = 0; i < AMOUNT; i++) { printf(product[i].name); printf(": "); printf(product[i].barcodes); printf("\n"); } printf("\n"); } int find_barcodes(char* barcodes){ for (int i=0; i<AMOUNT; i++) if (!strcmp(barcodes, product[i].barcodes)) return i; return -1; } void add(int index){ printf(product[index].description); do { char confirm[2]; printf("\nBuy one (Yes/No)? "); fgets(confirm, sizeof(confirm), stdin); fseek(stdin, 0, SEEK_END); switch(confirm[0]) { case '\n': printf("Yes\n"); case 'y': case 'Y': products[index]++; printf("Added\n"); break; case 'n': case 'N': printf("Done\n"); return; } } while (1); } void make_check(){ cost_without_discounts = 0; cost = 0; char buffer[80]; int i; printf("\n"); snprintf(buffer, sizeof(buffer), "\n %-20s %8s %5s %9s\n", "Name", "Price", "Count", "Total"); printf(buffer); printf("\n"); for (int i = 0; i < AMOUNT; i++) { if (products[i] > 0) { snprintf(buffer, sizeof(buffer), " %-20s %8.2lf %4d %9.2lf\n", product[i].name, product[i].price, products[i], (double)products[i] * product[i].price); printf(buffer); cost_without_discounts += (double)products[i] * product[i].price; cost += (double)products[i] * product[i].price * (1.0 - ((double)(product[i].discount))/100); } } printf("\n"); printf("Cost without discount: "); printf("%.2lf\n\n", cost_without_discounts); } void fin_cost(){ make_check(); printf("Discount: "); printf("%.2f", cost_without_discounts - cost); printf("\nTotal price: "); printf("%.2f", cost); } int move(){ char scan[5]; fgets(scan, sizeof(scan), stdin); fseek(stdin, 0, SEEK_END); switch(scan[0]){ case 'f': fin_cost(); return -1; case 'c': make_check(); break; default:{ int index=find_barcodes(scan); if (index<0) printf("Couldn't find this barcode"); else add(index); } } return 0; } int main(){ rules(); while(!move()); }<file_sep>#include<stdio.h> #define LENGTH (sizeof(price)/sizeof(price[0])) float price[] = { 25.00, 69.00, 75.00, 80.00, 300.00, 120.00, 30.00, 80.00, 250.00, 400.00 }; const char* products[] = { "Lemon","Milk","Eggs","Apple","Honey","Oil","Bread","Tea","Sausage","Cheese" }; const char* barcodes[] = { "0101","2020","0303","4040","0505","6060","0707","8080","0909","1010" }; float skidka[] = { 4.50, 7.00, 5.00, 6.55, 21.35, 12.50, 5.00, 13.90, 42.10, 51.30 }; const char* infos[] = { "Country of origin: Russia","Country of origin: Russia\nFat content of milk - 3,2%","Country of origin: Russia\nCategory of eggs - C0","Country of origin: Russia\nGreen apples","Country of origin: Russia\nMountain honey", "Country of origin: Russia\nOlive oil","Country of origin: Russia\nRye bread","Country of origin: Russia\nBleak tea","Country of origin: Russia\nCheese smoked sausage","Country of origin: Russia\nCheese with blue mold" }; int count[LENGTH] = { 0 }; void intro() { printf("Scan your barcodes below\n"); printf("Enter \"print\" when you are done\n"); } void description(int num) { printf("%s, price: %.2f, discount: %.2f\n", products[num], price[num], skidka[num]); printf("%s\n", infos[num]); } void line() { for (int i = 0; i < 50; i++) { printf("-"); } printf("\n"); } void scan() { static int tmp = 0; char* entered[6]; int counts[LENGTH] = { 0 }; printf("Enter barcode\n"); gets(entered); if (strcmp(entered, "print")) { for (int i = 0; i < LENGTH; i++) { if (strcmp(barcodes[i], entered) == 0) { description(i); count[i] += 1; tmp = 1; } } if (tmp == 0) printf("Couldn't find this barcode, please try again\n"); scan(); } } void print_check() { float cost = 0.0; printf("Your check:\n"); line(); for (int i = 0; i < LENGTH; i++) { if (count[i] != 0) { printf("%s, price with discount - %.2f, %d\n", products[i], price[i] - skidka[i], count[i]); line(); cost += (price[i] - skidka[i]) * count[i]; } } printf("Price - %.2f\n", cost); } int main() { intro(); scan(); print_check(); return 0; } <file_sep>#include <stdio.h> int main() { double a, h, w, d, bw, sw, uw, shelves, doors, m; int n = 0; printf("enter height, width, depth (in cm): "); scanf_s("%lf %lf %lf", &h, &w, &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) { printf("error"); return 1; } a = h - 3; h = h * 0.01; w = w * 0.01; d = d * 0.01; while (a >= 40) { a = a - 40; n++; } bw = h * w * 0.005 * 800; sw = (h - 0.03) * d * 0.015 * 650 * 2; uw = w * d * 0.015 * 650 * 2; doors = h * w * 0.01 * 550; shelves = d * (w - 0.015 - 0.015) * 0.015 * 650 * n; m = bw + sw + uw + doors + shelves; printf("mass of wardrobe = %lf", m); return 0; }<file_sep>#include <iostream> #include <fstream> #include <string> #include <vector> #include "banki.h" using namespace std; int main() { string path = getfile();//C:\Users\abobi\banki2.txt banklib banks(path); cout << banks; float sum; int kMonths; string vkladType; cout << "Enter count of money" << endl; cin >> sum; cout << "For how long is the contribution made" << endl; cin >> kMonths; cout << "Enter type of vklad(saving, debit or cumulative)." << endl; cin >> vkladType; if (vkladType != "saving" && vkladType != "debit" && vkladType != "cumulative") { printf("ERROR!This type of vklad does not exist\n"); } banklib mybank= banks.search(sum, kMonths, vkladType);//1 стр. -конструктор копирования, 2- опер. присваивания cout << mybank; return 0; }<file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { float* x; int n; }Matrix; void allocate_matrix(Matrix** matrix, int n); void fill_matrix(Matrix* matrix); void print_matrix(Matrix* matrix); void free_matrix(Matrix** matrix); Matrix* addition_matrix(Matrix* matrix1, Matrix* matrix2); Matrix* addition_const(Matrix* matrix1, float c); Matrix* multi_const(Matrix* matrix, float c); Matrix* multi_matrix(Matrix* matrix1, Matrix* matrix2); #endif // !_MATRIX_H <file_sep>#pragma once #ifndef _PROTOTYPES_H #define _PROTOTYPES_H #include <string> using namespace std; enum class FileExeption { NullPtrFile = -1 };//enumeration for file errors struct TService// list of service { string country; string travel_conditions; string excursion_services; string host_service; string ticket_price; TService(void); TService(const TService& obj); }; struct TAgency // Tourist agency { int num_services; string name; TService* services; TAgency(void); TAgency(int num_services);//initialisation of TAgency objects TAgency(const TAgency& object);//copy object ~TAgency(); }; struct TAgencyBook { TAgency** agencies; int count_agencies;//num no european countries TAgencyBook(void); TAgencyBook(const string& path);//initialising TAgencyBook + call constructor TAgency TAgencyBook(const TAgencyBook& object);//copy_object ~TAgencyBook(); void CountAgencies(ifstream& file); int* CountTServices(ifstream& file);//count directions int* counter_euro_countries();//count euro countries int counter_euro_agencies();//count euro agencies void search_string(ifstream& file);//look for the first occurrence of the string void file_reader(ifstream& file); TAgencyBook Get_Europe_Countries();//find european countries and create european massive const TAgencyBook& operator=(const TAgencyBook& obj); }; ostream& operator<<(ostream& stream, const TAgencyBook& obj);//overloading for TAgencyBook #endif<file_sep>#include <fstream> #include <iostream> #include <vector> #include "Header.h" using namespace std; int main() { string path; input_path(path); int n; int* p = &n; BanksData* data; int q; do { q = BanksData::read(data, p, path); if (q != 0) { input_path(path); } } while (q != 0); cout << "Yours data: " << "\n \n"; for (int i = 0; i < n; i++) { cout << data[i]; } int user_year; float user_money; input_user_data(&user_year, &user_money); triple ans = comparing(data, user_year, user_money, n); cout << "!!!" << endl; cout << "\n" << "The best suggestion for you in " << data[ans.id1].get_ownership() << " " << data[ans.id1].get_name() << endl; cout << "\n" << "if you would invest " << user_money << " in " << data[ans.id1].get_deposits()[ans.id2].get_name() << " at a " << data[ans.id1].get_deposits()[ans.id2].get_condition() << " per year"; cout << "\n \n" << "Your benefit in " << user_year << " years will be " << ans.profit << " rubles" << endl; return 0; }<file_sep>#ifndef _TRIANGLE_H #define _TRIANGLE_H #include <string> using namespace std; struct Coord { float x, y; }; struct Triangle { Coord vertices[3]; void CountSquare(); void CountPerimeter(); float* Sides(); void Height(); void TriangleType(); }; int read(Triangle*& triangles, const string& f); #endif _TRIANGLE_H <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 10 char* barcodes[N] = { "1010","2020","3030","4040","5050","6060","7070","8080","9090","1111" }; char* products[N] = { "Asus","Lenovo","InVidia","Apple","Blackberry","Hp","Acer","Honor","Infinix","Digma" }; int price_for_one_item[N] = { 100,110,120,130,140,150,160,170,180,190 }; float discount[N] = { 0.04,0.04,0.06,0.07,0.08,0.09,0.1,0.11,0.12,0.13 }; void Scan(int* arr) { int i; int flag; float price_with_discount; char a[5]; printf("====================\n"); printf("WELCOME TO MY KASSA!\nLets start scanning your barcodes\nEnter 0 to print check.\n"); do { printf("Enter your barcode\n"); gets(a); flag = 0; for (i = 0; i < N; i++) { if (strcmp(barcodes[i], a) == 0) { arr[i]++; price_with_discount = price_for_one_item[i] - (discount[i] * price_for_one_item[i]); printf("Beep!!! \n %s Price: %.2d rubles Discount: %.2f Final Price is %.2f rubles\n", products[i], price_for_one_item[i], discount[i] * 100, price_with_discount); flag = 1; } } if ((flag == 0) && (strcmp(a, "0") != 0)) { printf("It looks like you entered the barcode wrong\nThere should be 4 digits"); } } while (strcmp(a, "0")); } void Print_check(int* array) { int i, Price_Without_Discount = 0; float Summa_discounts = 0, Totally_summa = 0, PriceDDisk; for (i = 0; i < N; i++) { if (array[i] > 0) { Price_Without_Discount = price_for_one_item[i] * array[i] + Price_Without_Discount; PriceDDisk = (price_for_one_item[i] - price_for_one_item[i] * discount[i]) * array[i]; Totally_summa = Totally_summa + PriceDDisk; Summa_discounts = Summa_discounts + (price_for_one_item[i] * discount[i]) * array[i]; printf("%10s: Price: %d, Count Products: %d, Price with discount: %.2f\n", products[i], price_for_one_item[i], array[i], PriceDDisk); } } printf("\n \n"); printf("===================================================================="); printf("\t\nPrice: %d Rubles, Discounts: %.2f Rubles, Amount Payable: %.2f\n", Price_Without_Discount, Summa_discounts, Totally_summa); printf("===================================================================="); printf("\n \n"); } int main() { int Basket[N] = { 0 }; Scan(Basket); Print_check(Basket); return 0; }<file_sep>cmake_minimum_required(VERSION 3.23) project(Practice3 C) set(CMAKE_C_STANDARD 23) add_executable(Practice3 main.c) <file_sep>#define _CRT_SECURE_NO_WARNINGS #include "matrix.h" void main() { TMatrix matrix; TMatrix* m1, *m2, *result; printf("Enter the number of dimension with Enter\n"); int dimension; do { scanf("\t%d", &dimension); } while (dimension < 1); //выделение памяти allocate_matrix(&m1, dimension); allocate_matrix(&m2, dimension); //заполнение printf("\nFill in the first matrix with Enter (line-by-line filling)\n"); build_matrix(m1); print_matrix(m1, dimension); printf("\nFill in the second matrix with Enter (line-by-line filling)\n"); build_matrix(m2); print_matrix(m2, dimension); //складывание матриц printf("\n\n\nMatrix addition\n"); result = addition(m1, m2, dimension); print_matrix(result, dimension); free_m(&result); //умножение матриц printf("\n\n\nMatrix multiplication\n"); result = multiplication(m1, m2, dimension); print_matrix(result, dimension); free_m(&result); //умножение на const printf("\n\n\nMatrix multiplication(const * matrix)\nenter a constant\n"); int constant; scanf("%d", &constant); result = multiplication_const(m1, constant, dimension); print_matrix(result, dimension); free_m(&result); free_m(&m1); free_m(&m2); }<file_sep>#include <stdio.h> int main() { float h, d, w; // height, deep, width of wardrobe float density_of_tree = 900; float density_of_dsp = 800; float density_of_dvf = 800; float mass_of_backdoor; float mass_of_side_walls; float mass_of_overhead_lids; float mass_of_frontdoors; float mass_of_shelves; float control_mass; int counting_shelves; // input of data printf("enter the heigth of the wardrobe in cm\n"); scanf_s("%f", &h); printf("enter the deep of the wardrobe in cm\n"); scanf_s("%f", &d); printf("enter the width of the wardrobe in cm\n"); scanf_s("%f", &w); // validation of entered data if ((180 > h) || (h > 220)) { printf("input correct data"); return 0; } if ((50 > d) || (d > 90)) { printf("input correct data"); return 0; } if ((80 > w) || (w > 120)) { printf("input correct data"); return 0; } // converting data h = h / 100; w = w / 100; d = d / 100; counting_shelves = (h / 0.4) - 1; // counting shelves // calculation mass_of_backdoor = (0.005 * h * w) * density_of_dvf; mass_of_side_walls = 2 * (0.015 * d * (h-0.03)) * density_of_dsp; mass_of_overhead_lids = 2 * (0.015 * d * w) * density_of_tree; mass_of_frontdoors = (0.01 * h * w) * density_of_tree; mass_of_shelves = counting_shelves * (0.0015 * d * (w-0.03)) * density_of_dsp; control_mass = mass_of_backdoor + mass_of_overhead_lids + mass_of_side_walls + mass_of_frontdoors + mass_of_shelves; printf("mass of the cupboard\n"); printf("%f", control_mass); return 0; } <file_sep>//табличные значения для ДСП: 650 кг/м^3, ДВП: 800 кг/м^3, дерева: 550 кг/м^3// #include<stdio.h> int main() { double h, w, d, a, massa_zadnya_chast, massa_dverey, massa_polok, massa_verha_and_niza, massa_bokovyih_sten, massa_shcafa; int n = 0; printf("Vvedite znachenia v sm:"); //запрос на ввод размеров scanf("%lf %lf %lf", &h, &w, &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) // проверка на корректность ввеедённых данных { printf("Nekorrektnyi vvod"); return 1; } a = h - 3; //высота боковых стен h *= 0.01; //перевод в метры w *= 0.01; d *= 0.01; { massa_zadnya_chast = h * w * 0.005 * 800; //масса задней части шкафа massa_dverey = h * w * 0.01 * 550; //масса дверей while (a >= 40) //цикл на подсчёт количества полок { a -= 40; n++; } massa_polok = n * (w - 0.03) * d * 650 * 0.015; //масса полок massa_verha_and_niza = 2 * d * w * 0.015 * 650; //масса накладных верха и низа massa_bokovyih_sten = 2 * (h - 0.03) * d * 0.015 * 650; //масса боковых стен massa_shcafa = massa_zadnya_chast + massa_dverey + massa_polok + massa_verha_and_niza + massa_bokovyih_sten; //подсчёт общей массы шкафа printf("%lf", massa_shcafa); } return 0; } //пояснение по сборке шкафа: верх и низ накладываем на боковые стенки, поэтому из высоты вычитаем толщину обеих крышек, от общей ширины вычитаем толщину стенок и получаем ширину<file_sep>#include <stdio.h> #include <stdlib.h> #include "zagolovok.h" int main() { Owners* owner = read_inf(); print_inf(owner, owner[0].n); search_owner(owner, owner[0].n); free_inf(&owner, owner[0].n); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); int X_n = 1 + rand() % (1000), user_n; int min = 1, max = 1000, attempts = 0; char mode, ans; printf("Choose mode 1 or 2 "); scanf("%c", &mode); switch (mode) { case '1': printf("The program made a number from 1 to 1000. Try to guess it : \n"); do { printf("Input number from 1 to 1000 "); scanf ("%d", &user_n); while ((user_n > 1000) || (user_n < 1)) { printf("Incorrect data. Try again. "); scanf ("%d", &user_n); } if (user_n == X_n) printf("Congratulations, you guessed the number in %d attempts!", attempts); else if (user_n < X_n) { printf("The hidden number is greater than your number. Try again: "); attempts++; } else { printf("The hidden number is less than your number. Try again: "); attempts++; } } while (user_n != X_n); break; case '2': printf("Enter a number from 1 to 1000. The program will try to guess it: "); do { scanf ("%d", &user_n); if (user_n > 1000 || user_n < 1) { printf("Incorrect data. Try again: "); } } while (user_n > 1000 || user_n < 1); while (user_n != X_n) { X_n = min + rand() % (max - min + 1); printf("Is this the number %d ? ", X_n); scanf ("%c", &ans); if (scanf("%c", &ans) != 1) { // != 1 means scanf failed while ((ans = getchar()) != '\n' && ans != EOF) { ; } } attempts++; switch (ans) { case '=': printf("The program guessed the number %d in %d attempts!", X_n, attempts); break; case '>': min = 1 + X_n; break; case '<': max = X_n - 1; break; default: printf("Incorrect answer. Try again. Input '=' or '>' or '<' \n"); } } break; default: printf("Incorrect data, try again"); } return 0; }<file_sep>#ifndef _USERSIDE_H #define _USERSIDE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fileProcessing.h" #define MAX_LEN_ANSWER 100 // Два раза использовался switch -- вынес в функцию из-за его объемности! // Переводит название формы обучения из константы в слово) char* switch_form(EducationalForm form); //Для ВУЗов // Берет от пользователя название ВУЗа, работает пока не будет введет существующий вуз int getting_univ(University_t* uns, int c, char in[]); // Проверка, что введены 1 или 2 для вызова мода void entering_mode(char in[]); // Поиск минимального конкурса по специальностям каждого конкретного вуза void print_minimal_spec(University_t* uns, int c, char name_univ[MAX_LEN_ANSWER], int ind); // Всё о данном ВУЗе void print_all_about_univ(University_t* uns, int c, char name_univ[MAX_LEN_ANSWER], int ind); // возвращает индекс вуза в массиве структур вузов, или -1, если не нашёл int check_index_univ(University_t* uns, int c, char name_univ[MAX_LEN_ANSWER]); // функция запускает работу с университетами void about_univercity(University_t* uns, int c); // Для специальностей // функция запускает работу с специальностями void about_spec(University_t* uns, int c); // Проверяет существование специальности int check_existing_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]); // Всё о данной специальности void print_all_about_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]); // берет от пользователя название специальности, работает пока не будет введет существующая специальность void getting_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]); // Поиск минимального конкурса по специальности void print_min_score_for_spec(University_t* uns, int c, char name_spec[MAX_LEN_ANSWER]); // Проверка, что введены 1 или 2 или 0 для вызова мода void main_entering_mode(char in[]); // основаная функция работы с пользователем void working_with_user(University_t* uns, int c); #endif<file_sep>#include <string> #ifndef _BOOK_H #define _BOOK_H using namespace std; class TBook { private: int Couaut; string* Author; string Name; string Publishing; string Section; bool Availability; int Score; public: TBook(); ~TBook(); TBook(const TBook& book); TBook& operator=(const TBook&); friend ostream& operator << (ostream& out, TBook& book); void SetBook( const int TCouaut, const string* TAuthor, const string TName, const string TPublishing, const string TSection, const bool TAvailability, const int TScore); string GetSection(); }; struct TLib { private: TBook* books; int count; int CountUnic; string* unic_section; public: TLib(); TLib(const string& path); TLib(const TLib& lib); TLib& operator=(const TLib&); ~TLib(); int count_books(const string& path) const; int count_unic() const; void create_section(); void print_unique_sections(); TLib search_by_section(const string section_name); friend ostream& operator << (ostream& out, TLib& lib); void Set_unic(int unic); TBook GetBook(int i) const; int GetCountUnic() const; void SetUnicSection(string* Unic_Section); string GetUnicSection(int i) const; }; string get_path(); #endif _BOOK_H <file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { float* x; int n; } TMatrix; void allocate_matrix(TMatrix** matrix, int n); void free_matrix(TMatrix** matrix); void fill_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix); TMatrix* add_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* add_const(TMatrix* matrix, float c); TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* multi_const(TMatrix* matrix, float c); #endif<file_sep>#include <stdio.h> #include <stdlib.h> #include "Header.h" void main() { One_Person** peop; int n; int i; int flag_m; char f[150]; printf("Enter the name of the file to be sorted: \n"); scanf("%s", f); Reading_File(&peop, &n, f); for (i = 0; i < n; i++) Print_Inforamation(peop[i]); sorting_for_surname(peop, n); do { printf("\nHow to dislay a sorted list:\n1)Asceling\n2)Ascending\n Choose a method: "); scanf("%d", &flag_m); if (flag_m == 1) { printf("\n"); for (i = 0; i < n; i++) Print_Inforamation(peop[i]); } if (flag_m == 2) { printf("\n"); for (i = n - 1; i >= 0; i--) Print_Inforamation(peop[i]); } } while ((flag_m <= 0) || (flag_m > 2)); for (i = 0; i < n; i++) Free_memory(&(peop[i])); } <file_sep>#include<stdio.h> int main() { const float dsp = 1.5f; // mm const float dvp = 0.5f; // mm const float drv = 1.0f; // mm const float plt_drv = 1.5f; // g/cm^3 const float plt_dsp = 0.7f; // g/cm^3 const float plt_dvp = 0.9f; // g/cm^3 int h, w, d; float mass, polka, back_stenka, bokovina, krishka, dveri; printf("h="); scanf_s("%d", &h); printf("w="); scanf_s("%d", &w); printf("d="); scanf_s("%d", &d); if ((h<180)||(h>220)||(w<80)||(w>120)||(d<50)||(d>90)) //if h<200 4 polki, else 5 { printf("input error"); return 0; } back_stenka = h * w * dvp; bokovina = h * d * dsp; krishka = dsp * (w - dsp * 2) * (d - dvp); dveri = h * w * drv; polka = dsp * (w - dsp * 2) * (d - dvp); if (h < 200) { mass = (back_stenka * plt_dvp + 2 * bokovina * plt_dsp + 2 * krishka * plt_dsp + dveri * plt_drv + 4 * polka * plt_dsp)/1000; } else { mass = (back_stenka * plt_dvp + 2 * bokovina * plt_dsp + 2 * krishka * plt_dsp + dveri * plt_drv + 5 * polka * plt_dsp)/1000; } printf("%f", mass); return 0; }<file_sep> #include <stdio.h> int main() { double h, w, d, BackWall, SideWall, WallUp, hg, doors, shelves; int a = 0; double k = 0.005; printf("Enter the heiht,width and depth of the cabinet in centimeters\n"); scanf_s("%lf %lf %lf", &h, &w, &d); if ((h < 180) || (h > 220) || (w < 80) || (w > 120) || (d < 50) || (d > 90)) { printf("You have entered incorrect data"); return 1; } hg = h; while (hg >= 40) { hg = hg - 40; a++; } w = w * 0.01; h = h * 0.01; d = d * 0.01; BackWall = h * w * k * 800; SideWall = 2 * h * d * 0.015 * 650; WallUp = 2 * w * d * 0.015 * 650; doors = h * w * 0.010 * 550; shelves = a * d * (w - (0.015 * 2)) * 0.015 * 650; printf("Total Cabinet weight %lf Kilograms\n", BackWall + SideWall + WallUp + shelves + doors); return 0; }<file_sep>#include <stdio.h> #include <math.h> int main() { float x1, y1, x2, y2, r1, r2, d; printf("Enter x1: "); scanf("%f", &x1); printf("Enter y1: "); scanf("%f", &y1); printf("Enter x2: "); scanf("%f", &x2); printf("Enter y2: "); scanf("%f", &y2); printf("Enter r1: "); scanf("%f", &r1); printf("Enter r2: "); scanf("%f", &r2); d = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); // distance between the centers of circles if (r1 <= 0 || r2 <= 0) { //Input control printf("Data entered incorrectly..."); return 1; } if (d > r1 + r2) { printf("Circles have no common points. \n"); return 0; } if (x1 == x2 && y1 == y2 && r1 == r2) { printf("Circles is equals. \n"); return 0; } if (d < (fmax(r1, r2)-fmin(r1,r2))) { // d < R - r printf("Circles have no common points(one circle inside another). \n"); return 0; } if (d == r1 + r2) { printf("Circles have one common point (external touch). \n"); return 0; } if (d == (fmax(r1, r2) - fmin(r1, r2))) { // d = R - r printf("Circles have one common point (inner touch). \n"); return 0; } else { printf("Circles have two points in common (intersect). \n"); return 0; } return 0; }<file_sep>#ifndef _DATENTIME_H #define _DATENTIME_H #include <iostream> #include <chrono> #include <iomanip> // setfill(), setw() #include "utility.h" using namespace std; struct TDate { int d = 0; int m = 0; int y = 0; TDate() { setCurrentDay(); } void setCurrentDay() { auto now = chrono::system_clock::now(); auto now_time_t = chrono::system_clock::to_time_t(now); auto now_tm = *localtime(&now_time_t); y = now_tm.tm_year + 1900; m = now_tm.tm_mon + 1; d = now_tm.tm_mday; } void Print() { cout << setfill('0') << setw(2) << d << '.' << setfill('0') << setw(2) << m << '.' << y; } string StringDate() const { string ans = intToString(d, 2) + intToString(m, 2) + intToString(y - 2000, 2); return ans; } friend ostream& operator<<(ostream& out, const TDate& date) { out << setfill('0') << setw(2) << date.d << '.' << setfill('0') << setw(2) << date.m << '.' << date.y; return out; } const TDate& operator=(const TDate& date) { if (this == &date) return (*this); d = date.d; m = date.m; y = date.y; return *this; } }; struct TTime { int h = 0; int m = 0; int s = 0; TTime() { setCurrentTime(); } void setCurrentTime() { auto now = chrono::system_clock::now(); auto now_time_t = chrono::system_clock::to_time_t(now); auto now_tm = *localtime(&now_time_t); h = now_tm.tm_hour; m = now_tm.tm_min; s = now_tm.tm_sec; } void Print() const { cout << setfill('0') << setw(2) << h << ':' << setfill('0') << setw(2) << m << ':' << setfill('0') << setw(2) << s; } string StringTime() const { string ans = intToString(h, 2) + intToString(m, 2) + intToString(s, 2); return ans; } friend ostream& operator<<(ostream& out, const TTime& time) { out << setfill('0') << setw(2) << time.h << ':' << setfill('0') << setw(2) << time.m << ':' << setfill('0') << setw(2) << time.s; return out; } const TTime& operator=(const TTime& time) { if (this == &time) return (*this); h = time.h; m = time.m; s = time.s; return *this; } }; #endif // !_DATENTIME_H<file_sep>// Спортивная команда.Спортивная команда характеризуется названием, городом, // за который играет, количеством сыгранных игр, количеством очков, // количеством игроков.Среди множества спортивных команд определить команду, // которая имеет максимальное количество очков. #pragma once #include <stdlib.h> #define STRLEN 10 typedef struct comand{ char* Name; char* City; int Games; int Points; int Players; } Scommand; typedef struct commandbook { Scommand* comands; size_t length; } Scommandbook; <file_sep>#include <stdio.h> #include <stdlib.h> #include <locale.h> #include "polynom.h" #include "display.h" /* Чтение происходит из файла "data.txt" -В первой строке - количество полиномов -В второй строке перечисленны степени каждого полинома -В последующих строках перечисленны коэффициенты полиномов !!!Предполагается, что введенные данные верны!!! */ int main() { setlocale(LC_ALL, "rus"); int i, n, dgr, ans = 1; float x; int ind_1; int ind[2]; TPolynom* res; TPolynom** p; // массив полиномов read_file(&p, &n); while (ans) { system("cls"); print_p(p, n); choose(); answer(&ans); switch (ans) { case 0: break; case 1: // Сложение system("cls"); print_p(p, n); index(ind, n); system("cls"); print_2p(p[ind[0]], p[ind[1]], ind); res = plus_polynom(p[ind[0]], p[ind[1]]); printf("f%d + f%d = ", ind[0], ind[1]); print_polynom(res); free_polynom(&res); retry(&ans); break; case 2: // Вычитание system("cls"); print_p(p, n); index(ind, n); system("cls"); print_2p(p[ind[0]], p[ind[1]], ind); res = minus_polynom(p[ind[0]], p[ind[1]]); printf("f%d - f%d = ", ind[0], ind[1]); print_polynom(res); free_polynom(&res); retry(&ans); break; case 3: // Умножение system("cls"); print_p(p, n); index(ind, n); system("cls"); print_2p(p[ind[0]], p[ind[1]], ind); res = multi_polynom(p[ind[0]], p[ind[1]]); printf("f%d * f%d = ", ind[0], ind[1]); print_polynom(res); free_polynom(&res); retry(&ans); break; case 4: // Вычесление system("cls"); print_p(p, n); printf("Выберите полином: "); do { scanf("%d", &ind_1); } while (ind_1 < 0 || ind_1 > n); printf("Введите значение x: "); scanf("%f", &x); system("cls"); printf("f%d = ", ind_1); print_polynom(p[ind_1]); printf("\nf%d(%f) = %f \n", ind_1, x, value_polynome(p[ind_1], x)); retry(&ans); break; case 5: // Производная system("cls"); print_p(p, n); printf("Выберите полином: "); do { scanf("%d", &ind_1); } while (ind_1 < 0 || ind_1 > n); system("cls"); printf("f%d = ", ind_1); print_polynom(p[ind_1]); printf("\n"); res = diff_polynom(p[ind_1]); printf("f'%d = ", ind_1); print_polynom(res); free_polynom(&res); retry(&ans); break; default: printf("ERROR"); } } for (i = 0; i < n; i++) { free_polynom(&p[i]); } free(p); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main() { float x1, x2, y1, y2, R1, R2, S; printf("Input x1 "); scanf("%f", &x1); printf("Input y1 "); scanf("%f", &y1); printf("Input R1 "); scanf("%f", &R1); printf("Input x2 "); scanf("%f", &x2); printf("Input y2 "); scanf("%f", &y2); printf("Input R2 "); scanf("%f", &R2); S = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if (S > R1 + R2) { printf("The circle does not intersect "); return 0; } if (S == R1 + R2) { printf("External touch of circles "); return 0; } if ((S < R1 + R2) && (S > abs(R1 - R2))) { printf("The circles intersect "); return 0; } if ((S == abs(R1 - R2)) && (x1 != x2)) { printf("Inner touch of circles "); return 0; } if ((S == 0) && (R1 == R2)) { printf("The circles are equal "); return 0; } if (R1 > R2) printf("The second circle is inside the first one"); else printf("The first circle is inside the second "); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include "workers.h"; #define N 100 string get_path() { string path; do { cout << "Enter the file path:"; cin >> path; ifstream in(path); if (!in.is_open()) { cout << "Ooops.....Something went wrong......" << endl; } else { in.close(); return path; } } while (true); } worker::worker() { id=" "; profession = " "; education = " "; last_job = " "; rsn_dismiss = " "; family_status = " "; contact_info = 0; } worker::worker(const string id, const string profession, const string education, const string last_job, const string rsn_dismiss, const string family_status, int contact_info) { this->id = id; this->profession = profession; this->education = education; this->last_job = last_job; this->rsn_dismiss = rsn_dismiss; this->family_status = family_status; this->contact_info = contact_info; } void worker::adding(string _id, string _profession, string _education, string _last_job, string _rsn_dismiss, string _family_status, int _contact_info) { id = _id; profession = _profession; education = _education; last_job = last_job; rsn_dismiss = _rsn_dismiss; family_status = _family_status; contact_info = _contact_info; } int labor::amount(const string& path) { fstream file; file.open(path); string line; int count{ 0 }; ifstream in(path); while (getline(in, line)) { if (line != "\0") { count++; } } in.close(); return count; } labor::labor(const string& path) { this->n = amount(path); this->w = new worker[n]; fstream file; string id, profession, education, last_job, rsn_dismiss, family_status; int contact_info; file.open(path); int i = 0, j = 0; string line, s; ifstream in(path); while (getline(in, line)) { if (line == "\0") { continue; } stringstream ss(line); while (getline(ss, s, ';')) { switch (i) { case 0: id = s; break; case 1: profession = s; break; case 2: education = s; break; case 3: last_job = s; break; case 4: rsn_dismiss = s; break; case 5: family_status = s; break; case 6: contact_info = stoi(s); w[j].adding(id, profession, education, last_job, rsn_dismiss, family_status, contact_info); j++; i = -1; break; } i++; } } in.close(); } string worker::get_education() { return education; } float labor::higher_education() { float counter = 0; int i; cout << "All employees with higher education from the database:" << endl; for (i = 0; i < n; i++) { if ((w[i].get_education()) != "no") { cout << w[i]; counter++; } } return (counter / n) * 100; } labor::~labor() { delete[] this->w; } ostream& operator<<(ostream& out, const worker& w) { out << w.id << " " << w.education << endl; return out; } <file_sep>#include <iostream> #include <string> #include <vector> #include "Header.h" #include <fstream> using namespace std; //Input data int BanksData::read(BanksData*& data, int* p, const string& path) { ifstream infile(path); if (!infile) { cout << "This file isn`t exist" << endl; return 1; } else { infile >> (*p); int n = *p; int q; data = new BanksData[n]; for (int i = 0; i < n; i++) { infile >> data[i]; } infile.close(); return 0; } return 0; } //overloading operations ifstream& operator>>(ifstream& buf, Deposit& data) { buf >> data.name >> data.period >> data.conditions; return buf; } ostream& operator<<(ostream& buf, const Deposit& data) { buf << data.name << " " << data.period << " " << data.conditions << endl; return buf; } ifstream& operator>>(ifstream& buf, BanksData& data) { buf >> data.name >> data.ownership >> data.count; data.deposits.resize(data.count); for (int j = 0; j < data.count; j++) { buf >> data.deposits[j]; } return buf; } ostream& operator<<(ostream& buf, const BanksData& data) { buf << data.name << " " << data.ownership << " " << data.count << endl; for (int j = 0; j < data.count; j++) { buf << data.deposits[j]; } cout << endl; return buf; } //user interaction void input_path(string& path) { cout << "Input a path with file type: " << endl; cin >> path; cout << "\nYour path: \n" << path << " \n" << endl; } void input_user_data(int* user_year, float* user_money) { do { cout << "For how long would you like to open a deposit?" << endl; cin >> (*user_year); if ((*user_year) <= 0 || (*user_year) >= 100) { cout << "Wrong period, try again" << endl; } } while ((*user_year) <= 0 || (*user_year) >= 100); do { cout << "How much would you like to open a deposit for (rubles)? " << endl; cin >> (*user_money); if ((*user_money) <= 0) { cout << "Wrong period, try again" << endl; } } while ((*user_money) <= 0); } //functions for comparing pair<int, float> BanksData::best_deposit(int user_year, float user_money) { float profit = 0; int id = -1; for (int j = 0; j < count; j++) { if (user_year % deposits[j].get_period() == 0) { float tmp_profit = user_money * (pow(1 + (deposits[j].get_condition() * 0.01), user_year));// formule if (profit < tmp_profit) { profit = tmp_profit; id = j; } } } pair<int, float> q; q.first = id; q.second = profit; return q; } triple comparing(BanksData* data, int user_year, float user_money, int n) { triple ans; BanksData best_data = data[0]; best_data.set_best_suggestion(best_data.best_deposit(user_year, user_money)); ans.id1 = 0; ans.id2 = best_data.get_best_suggestion().first; ans.profit = best_data.get_best_suggestion().second; for (int i = 1; i < n; i++) { data[i].set_best_suggestion(data[i].best_deposit(user_year, user_money)); if (best_data < data[i]) { best_data = data[i]; ans.id1 = i; ans.id2 = data[i].get_best_suggestion().first; ans.profit = data[i].get_best_suggestion().second; } } return ans; } //BanksData getters pair<int, float> BanksData::get_best_suggestion() const { return best_suggestion; } string BanksData::get_name() const { return name; } string BanksData::get_ownership() const { return ownership; } vector<Deposit> BanksData::get_deposits() const { return deposits; } //BanksData setter void BanksData::set_best_suggestion(pair <int, float> new_suggestion) { best_suggestion = new_suggestion; } //Deposit getters int Deposit::get_period() const { return period; } float Deposit::get_condition() const { return conditions; } string Deposit::get_name() const { return name; } <file_sep>#pragma once using namespace std; #include <iostream> #include <string> #include <fstream> #include <string.h> #include <tuple> #include "class.h" <file_sep>#include <iostream> #include <fstream> #include <cstring> #include <string> #include <iomanip> #include "header.h" using namespace std; int cntLines(const string &filename) { string line; int f = 0; ifstream file(filename); // окрываем файл для чтения if (!file.is_open()) throw "File open error"; if (file.is_open()) { while (getline(file, line)) { // cout << line << endl; f++; } } file.close(); // закрываем файл // cout << f << endl; // cout << "End of program" << endl; return f; } void allocate_sklad(Product*& p, int size) { p = new Product[size]; } void fill_sklad(Product*& p, int size, const string& filename) { string line; char str[200]; char* istr; ifstream file(filename); // окрываем файл для чтения int j = 0,flag=0; if (!file.is_open()) throw "File open error"; if (file.is_open()) { while (j != size) { while (getline(file, line)) { strcpy(str, line.c_str()); istr = strtok(str, ";/"); flag++; if (flag == 1) { (p[j].name)=string( istr); ; } while (istr != NULL) { istr = strtok(NULL, ";/"); flag++; if (flag == 2) { (p[j].unit)=string(istr); } if (flag == 3) { p[j].price = atoi(istr); } if (flag == 4) { p[j].number = atoi(istr); } if (flag == 5) { p[j].data.day = atoi(istr); } if (flag == 6) { p[j].data.month = atoi(istr); } if (flag == 7) { p[j].data.year = atoi(istr); } } flag = 0; j++; } } } file.close(); } void find_null(Product*& p, int size) { for (int i = 0; i < size; i++) { if (p[i].number == 0) { cout << p[i].name << "\t" << p[i].unit << "\t" << p[i].price << "\t" << p[i].number << "\t"; cout<< p[i].data.day << "." << p[i].data.month << "."<< p[i].data.year << endl; } } } void free_sklad(Product*& p, int size) { delete[] p; } <file_sep>#define _CRT_SECURE_NO_WARNINGS #include "workers.h"; using namespace std; int main() { string path = get_path(); labor labor_exchange(path); labor_exchange.higher_education(path); return 0; } <file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { float* x; int n; }TMatrix; void allocate_matrix(TMatrix** matrix, int n);//выделение памяти void fill_matrix(TMatrix* matrix);//заполнение матриц void print_matrix(TMatrix* matrix); void free_matrix(TMatrix** matrix); TMatrix* addition_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* addition_const(TMatrix* matrix1, float c); TMatrix* multi_const(TMatrix* matrix, float c); TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2); #endif // !_MATRIX_H <file_sep>#include<stdio.h> #include<stdlib.h> #include<time.h> #include<stdbool.h> int n; int Check(int* arr); int main() { int i, x, j, cow=0, bull=0, k; int a[5]; int b[5]; do { printf("Enter the length of the number (2-5) "); scanf("%d", &n); } while ((n < 0) || (n > 5)); srand((unsigned int)time(NULL)); do { for (i = 0; i < n; i++) a[i] = rand() % 10; } while (Check(a)==0 || a[0]==0); for (i = 0; i < n; i++) printf("%d ", a[i]); do { printf("\nEnter a number of non-repeating digits with a length of %d\n", n); scanf("%d", &x); while(x > 0) { k = n; for (i = n - 1; i >= 0; i--) { b[i] = x % 10; x = x / 10; k--; } } } while (Check(b)==0 || k!=0 || b[0]==0); while (true) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (a[i] == b[j]) { if (i == j) bull++; else cow++; } } } if (bull == n) { printf("You guessed the number!"); break; } else printf("%d cow(s) and %d bull(s) were found\n", cow, bull); do { printf("\nEnter a number of non-repeating digits with a length of %d\n", n); scanf("%d", &x); while (x > 0) { k = n; for (i = n - 1; i >= 0; i--) { b[i] = x % 10; x = x / 10; k--; } } } while (Check(b) == 0 || k != 0 || b[0] == 0); cow = 0; bull = 0; } return 0; } int Check(int* arr) { int Un_index = 0, Cur_index; for (Cur_index = 0; Cur_index < n; Cur_index++) { if ((Cur_index != Un_index) && (arr[Cur_index] == arr[Un_index])) return 0; if (Cur_index == n-1 && Un_index != n-1) { Un_index++; Cur_index = 0; } } return 1; } <file_sep># Система оценивания практики по курсу "Методы программирования 1_1" (1 курс, 1 семестр) ## Схема практики: - 2 аудиторных часа в неделю - 2 часа т.к. в неделю - продолжительность: 16 недель ## Отчетность по практике: - зачет (зачтено/не зачтено) - вклад в годовую рекомендацию к оценке за практику для лектора ## Схема оценивания практики: ### Система баллов - Общая оценка по практике формируется в баллах - Баллы начисляются за: - с.р. на аудиторной практике: - 5 баллов за каждую из семи в семестре - __Итого__: 5 * 7 = 35 баллов - задания (выполняются в т.к. и дома): - 7 заданий на разработку программ - 1 балл за вводное задание №0 - по 6 баллов за задания №1, №2 - по 8 баллов за задания №3, №4 - по 12 баллов за задания №5, №6 - __Итого__: 1 + 6 + 6 + 8 + 8 + 12 + 12 = 53 балла - отчеты: - по 6 баллов за отчет по заданию №5, №6 - __Итого__: 6 * 2 = 12 баллов - Баллы за задания №1-6 складываются из - 50% - оценка за функциональность (полнота реализации требований постановки задачи) - 25% - оценка за качество проектирования программы - 25% - оценка за качество кода (стиль кодирования) - Баллы за отчет складываются из - 50% - оценка за наличие и наполнение всех требуемых пунктов - 25% - за качество текста - 25% - за качество оформления - __Итого__: - высший балл 100 складывается из: - 35 баллов за с.р. - 53 балла за задания - 12 баллов за отчеты ### Прием заданий - выполняется через систему контроля версий git (сайт github) - задание считается сданным, если Pull request в upstream репозиторий преподавателя одобрен ### Бонусы - за каждую с.р. может быть получено дополнительно 0.5 балла за оригинальное и/или эффективное решение - за каждое задание №1-№6 может быть получено дополнительно по 0.5 балла за функциональность сверх требований или оригинальное решение при условии высокого качества проектирования и качества кода - __Итого__: максимальный бонус может достигать 0.5 * 7 + 0.5 * 6 = 6.5 балла ### Штрафы - для каждого задания будет установлен срок сдачи - 0.5 балла будет вычитаться из баллов за задание за каждый день просрочки со сдачей - плагиат - при подозрении на плагиат или прямое использование чужого кода следует очный прием задания - при невнятном ответе на вопросы по коду факт плагиата считается подтвержденным - оценка за задание с подтвержденным плагиатом уменьшается вдвое ### Перевод балла в оценку | Балл | Оценка | | -------- | ----------------------- | | >= 99 | Превосходно (5.5) | | [92, 99) | Отлично (5) | | [82, 92) | Очень хорошо (4.5) | | [69, 82) | Хорошо (4) | | [50, 69) | Удовлетворительно (3) | | < 50 | Неудовлетворительно (2) | Зачет выставляется при сумме баллов 50 и выше <file_sep>#include <stdio.h> #include <malloc.h> #include "Matrix.h" int main(int argc, char *argv[]) { int i = 0; float c = 6; TDmatrix Matrix; TDmatrix*dynamic_matrix1; TDmatrix* dynamic_matrix2; //Declare three pointers to square matrices TDmatrix* res; int size_2d; printf("Specify the dimension of the square matrix: \n"); //Determine the size of the square matrices scanf("%d", &size_2d); allocate_matrix(&dynamic_matrix1, size_2d); fill_matrix(dynamic_matrix1); //Creating and filling square matrices allocate_matrix(&dynamic_matrix2, size_2d); fill_matrix(dynamic_matrix2); // print_matrix(dynamic_matrix1); // print_matrix(dynamic_matrix2); res = add_matrix(dynamic_matrix1, dynamic_matrix2);//returned address matrix res1 print_matrix(res); free_matrix(&res); res =multi_const(dynamic_matrix1, c);//returned address matrix res2 print_matrix(res); free_matrix(&res);//structure number 3 is free res =add_const(dynamic_matrix2, c);//returned address matrix res3 print_matrix(res); free_matrix(&res); res = multi_matrix(dynamic_matrix1, dynamic_matrix2);//returned address matrix res4 print_matrix(res); free_matrix(&res); free_matrix(&dynamic_matrix1); free_matrix(&dynamic_matrix2); return 0; }<file_sep> #include "Receipt.h" #include "Container.h" #include <iostream> #include <fstream> #include <sstream> #include <ctime> TProductsDatabase::TProductsDatabase(const string& filename) { get_correct_file_name(filename); ifstream file(filename); string line; while (getline(file, line)) { stringstream f_line(line); string stuff; TInfoProduct tmp; TProduct curr_prod; getline(f_line, stuff, ';'); curr_prod.code = stol(stuff); getline(f_line, stuff, ';'); curr_prod.name = stuff; getline(f_line, stuff, ';'); curr_prod.price = stod(stuff); tmp.product = curr_prod; getline(f_line, stuff, ';'); tmp.count = stoi(stuff); products.insert(tmp); } file.close(); } void TProductsDatabase::get_correct_file_name(const string& fname) const { bool file_exist; do { getline(cin, const_cast<string&>(fname)); file_exist = check_file_name(fname); if (!file_exist) cout << "Such file doesn't exist" << std::endl; } while (!file_exist); } bool TProductsDatabase::check_file_name(const string& fname) const { ifstream fin(fname); return !fin.fail(); } TInfoProduct& TProductsDatabase::operator[](int ind) { return products[ind]; } int TProductsDatabase::Get_num_prods() const { return products.getSize(); } int TProductsDatabase::barcode_search(const int barcode) { for (int i = 0; i < products.getSize(); i++) { if (products[i].product.code == barcode) { return i; } } return -1; } void TProductsDatabase::Updating_remove(const TProduct& prod) { int ind_such_prod = this->barcode_search(prod.code); (*this)[ind_such_prod].count -= 1; } void TProductsDatabase::Updating_add(const TProduct& prod) { int ind_such_prod = this->barcode_search(prod.code); (*this)[ind_such_prod].count += 1; } ostream& operator<<(ostream& out, const TInfoProduct& prod) { out << endl; out << "Product: "<< endl << prod.product; out << "Quantity of product in stock: " << prod.count; return out; } bool TInfoProduct::operator==(const TInfoProduct& p) const { return (product == p.product && count == p.count); } bool TProduct::operator==(const TProduct& p) const { return (code == p.code && name == p.name && price == p.price); } ostream& operator<<(ostream& out, const TProduct& p) { out << "Product code: " << p.code << " "; out << "Product name: " << p.name << " "; out << "Cost per unit: " << p.price; return out; } ostream& operator<<(ostream& out, const TProductsDatabase& db) { out << db.products; return out; } TReceiptLine::TReceiptLine() { count = 0; summ = 0; } TReceiptLine::TReceiptLine(TProduct& product, int count, double sum_price) { this->product = product; this->count = count; this->summ = sum_price; } TReceiptLine::TReceiptLine(const TReceiptLine& rec_line) { this->product = rec_line.product; this->count = rec_line.count; this->summ = rec_line.summ; } const TProduct& TReceiptLine::Get_product() const { return product; } int TReceiptLine::Get_count() const { return count; } double TReceiptLine::Get_sum_cost() const { return summ; } void TReceiptLine::Set_count(int c) { count = c; } void TReceiptLine::Set_sum_cost(double s) { summ = s; } const TReceiptLine& TReceiptLine::operator=(const TReceiptLine& rec_line) { this->product = rec_line.product; this->count = rec_line.count; this->summ = rec_line.summ; return (*this); } bool TReceiptLine::operator==(const TReceiptLine& rec_line) const { return (this->product == rec_line.product); } ostream& operator<<(std::ostream& out, const TReceiptLine& rec_line) { out << rec_line.product << endl; out << rec_line.count << " counts" << endl; out << "total cost:" << rec_line.summ << "rubles" << endl << endl; return out; } TTime::TTime() { hour = 0; minute = 0; second = 0; } TDate::TDate() { year = 0; month = 0; day = 0; } long TReceipt::code = -1; void TReceipt::Code_increase() { code++; } TReceipt::TReceipt() {} TReceipt::TReceipt(const TReceipt& rec) { this->code = rec.code; this->time = rec.time; this->date = rec.date; this->products = rec.products; } TReceiptLine& TReceipt::operator[](int ind) { return products[ind]; } const TReceipt& TReceipt::operator= (const TReceipt& rec) { if (this == &rec) return (*this); this->code = rec.code; this->time = rec.time; this->date = rec.date; this->products = rec.products; return (*this); } std::ostream& operator<<(std::ostream& out, TReceipt& rec) { rec.Code_increase(); out << "\n------------------------------------------\n"; out << "Receipt code: " << rec.code << "\n\n"; out << rec.date.day << "." << rec.date.month << "." << rec.date.year << " "; out << rec.time.hour << ":" << rec.time.minute << ":" << rec.time.second << "\n"; out << "Your products: \n"; out << rec.products; out << "TOTAL SUM: " << rec.Get_total_sum() << " rubles\n"; out << "------------------------------------------\n"; return out; } int TReceipt::Get_num_products() const { return products.getSize(); } void TReceipt::Add_new_prod(const TReceiptLine& rec_line) { products.insert(rec_line); } int TReceipt::Find_product(const long code) const { for (int i = 0; i < products.getSize(); i++) { if (products[i].Get_product().code == code) { return i; } } return -1; } double TReceipt::Get_total_sum() const { double total_sum = 0; int count = this->Get_num_products(); for (int i = 0; i < count; i++) { total_sum += this->products[i].Get_sum_cost(); } return total_sum; } void TReceipt::SetTime() { std::time_t now = std::time(0); std::tm* localtime = std::localtime(&now); this->time.hour = localtime->tm_hour; this->time.minute = localtime->tm_min; this->time.second = localtime->tm_sec; this->date.day = localtime->tm_mday; this->date.month = localtime->tm_mon + 1; this->date.year = localtime->tm_year + 1900; } void TReceipt::Delete_prod(const int ind) { cout << "This product was deleted: " << this->products[ind].Get_product() << endl; if (this->products[ind].Get_count() == 1) this->products.remove(ind); else this->products[ind].Set_count(this->products[ind].Get_count() - 1); } void TReceipt::Delete(TProductsDatabase& db) { if (this->Get_num_products() == 0) { cout << "The receipt is empty" << endl; } else { cout << "Enter product barcode" << endl; int search; string barcode; do { getline(cin, barcode); search = this->Find_product(stol(barcode)); if (search == -1) { cout << "No product with this barcode" << endl; } } while (search == -1); db.Updating_add((*this)[search].Get_product()); this->Delete_prod(search); } } void TReceipt :: Add(TProductsDatabase& db, int search) { TProduct curr_product = db[search].product; cout << endl << curr_product << endl; int idx_prod_in_receipt = this->Find_product(curr_product.code); if (idx_prod_in_receipt != -1) { ((*this)[idx_prod_in_receipt]).Set_count(( (*this)[idx_prod_in_receipt]).Get_count() + 1); ((*this)[idx_prod_in_receipt]).Set_sum_cost (((*this)[idx_prod_in_receipt]).Get_sum_cost() + curr_product.price); } else { TReceiptLine curr_rec_line(curr_product, 1, curr_product.price); (*this).Add_new_prod(curr_rec_line); } db.Updating_remove(curr_product); }<file_sep>#pragma once class vacancy { private: string nameCompany; string employee; int salary; string workCond; string request; public: vacancy(); string getInfoVacancy(int select); friend ostream& operator << (ostream& os, const vacancy& vac); friend istream& operator >> (istream& is, vacancy& vac); }; class vacancyLib { private: vacancy* Vacancy; int count; vacancy* fill_from_txt(ifstream& stream, int countVacancy); ifstream read_list(const string& path); int count_vacancy(ifstream& stream); public: vacancyLib(); vacancyLib(const string& path); vacancyLib(vacancy* OutVacancy, int OutCount); vacancyLib(const vacancyLib& vac_copy); ~vacancyLib(); vacancyLib search_vacancy(); vacancyLib& operator= (const vacancyLib& cp_vac); friend ostream& operator << (ostream& os, const vacancyLib& vacLib); }; string enter_path(); <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int z[5]; int a; int razr_a[5]; int attemps = 0; int num_of_bulls = 0; int num_of_cows = 0; int k; int answer; printf("GAME:Bulls and cows\n"); printf("Are you ready?\n"); system("pause"); printf("Choose the length of the guessed number n (2-5) "); scanf("%d", &k); if ((k >= 6) || (k <= 1)) { do { printf("Length can be only in the range of 2-5.Try again: "); scanf("%d", &k); } while ((k >= 6) || (k <= 1)); } time_t t; srand((unsigned int)time(&t) << 16); z[0] = (rand() % 9) + 1; int i, j; for (i = 1; i < k; i++) { z[i] = rand() % 10; } int flag = 0; while (1) { flag = 0; for (i = 0; i < k; i++) { for (j = i + 1; j < k; j++) { if (z[i] == z[j]) { z[i] = (i == 0) ? ((rand() % 9) + 1) : (rand() % 10); flag = 1; } } } if (flag == 0) { break; } } while (num_of_bulls != k) { int q=0; num_of_bulls = 0; num_of_cows = 0; printf("input the number: "); scanf("%d", &a); int tmp = a; while (tmp > 0) { tmp /= 10; q++; } if (k != q) { printf("You have specified a different number length (%d)\n", k); printf ("Do you want to try again ? (yes-1;no-2): "); scanf("%d", &answer); switch (answer) { case 1: {system("cls"); main(); } case 2: return 0; } } tmp = a; int b[5]; for (i = 0; i < 5; i++) b[i] = 0; while (tmp) { b[tmp% 10] ++; tmp /= 10; } for (i = 0; i < 10; i++) { if (b[i] > 1) { printf("Digits in a number cannot be repeated\n"); printf("Do you want to try again ? (yes-1;no-2) :"); scanf("%d", &answer); switch (answer) { case 1: {system("cls"); main(); } case 2: return 0; }; } } for (i = k - 1; i >= 0; i--) { razr_a[i] = a % 10; a /= 10; } for (i = 0; i < k; i++) { for (j = 0; j < k; j++) { if (z[j] == razr_a[i]) { if (i == j) { num_of_bulls++; } else { num_of_cows++; } } } } printf("%d bulls, %d cows.\n", num_of_bulls, num_of_cows); attemps++; } printf("Congradulations!\n"); printf("it took you %d attemps\n", attemps); system("pause"); return 0; } <file_sep>#ifndef _POLYNOM_H #define _POLYNOM_H #include <fstream> class TPolynom { private: int degree; float* coeff; public: TPolynom(void); // По умолчанию TPolynom(const TPolynom& p);// Копирование TPolynom(int _degree); // Инициализатор (Преобразование типа?) TPolynom(int _degree, float _coeff); // Инициализатор, все coeff = _coeff ~TPolynom(void); // Деконструктор bool operator==(const TPolynom& p) const; bool operator!=(const TPolynom& p) const; const TPolynom& operator=(const TPolynom& p); TPolynom operator+(const TPolynom& p); TPolynom operator-(const TPolynom& p); TPolynom operator*(const TPolynom& p); float operator()(float _x); //!!! WIP !!! TPolynom& operator+=(const TPolynom& p); TPolynom& operator-=(const TPolynom& p); TPolynom& operator*=(const TPolynom& p); int& Degree(); float& Coeff(int ind); void Fill_hand(); // Заполнение от руки void Copy(const TPolynom& p); friend std::ostream& operator<<(std::ostream& out, const TPolynom& p) { out << p.coeff[p.degree]; if (!p.coeff[p.degree]) { out << "x^0" << std::endl; return out; } out << "x^" << p.degree << " "; for (int i = p.degree - 1; i >= 0; i--) { if (p.coeff[i] > 0) out << "+ " << p.coeff[i] << "x^" << i << " "; else if (p.coeff[i] < 0) out << "- " << -p.coeff[i] << "x^" << i << " "; } out << std::endl; return out; } TPolynom Diff(const TPolynom& p); TPolynom& DiffEq(); void Rebuffer(int newDegree); void Rebuffer(); private: void Resize(int newDegree); void _coeffcopy(float* c1, float* c2); }; void read_file(TPolynom*& p, int& n); inline int max_d(int a, int b) { return (a > b) ? a : b; }; #endif<file_sep>#ifndef _STRUCT_H #define _STRUCT_H typedef struct { char* postal_code; char* Country; char* Region; char* Area; char* City; char* Street; char* House; char* Apart; }Address; typedef struct { int year; int month; int day; }Date; typedef struct { char* Surname; char* Name; char* Middle_name; char* Gender; char* Nation; Date date; char* height; char* weight; char* phone_number; Address address; }One_Person; void Allocate_memory_for_one_person(One_Person** person); int Count_struct_in_file(FILE* file); void Reading_a_file_line(One_Person* person,FILE* file); void Print_Inforamation(One_Person* person); void sorting_for_surname(One_Person** person, int n); void Reading_File(One_Person*** person, int* n); void Free_memory(One_Person** person); #endif;<file_sep>#include <stdio.h> #include <math.h> int main() { /* 2е окружности задаются координатами центра и радиусами - определите взаимное расположение окружностей 1. */ double x1, x2, y1, y2, r1, r2, d; scanf_s("%lf%lf%lf%lf%lf%lf", &x1, &x2, &y1, &y2, &r1, &r2); d = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if (d == 0) { if (r1 == r2) { printf("the same circles"); } else { printf("one circle into other and there is no touching"); } } else if (d > (r1 + r2)) { printf("circles do not touch"); } else if (d == (r1 + r2)) { printf("circles touch at one point and no circle is inside the other "); } else { //расстояние между центрами меньше чем сумма их радиусов if (d == fabs(r1 - r2)) { printf("circles touch at one point and one of circles is inside the other"); } else if (d < fabs(r1 - r2)) { printf("one of circles is inside the other and no touching"); } else { printf("2 points"); } } return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdlib.h> #include <stdio.h> #include <time.h> void first() { int n, count = 1, num; srand((unsigned int)time(NULL)); n = rand() % 1000 + 1; printf("================================\n"); printf("Guess the number\n"); scanf("%d", &num); while (num != n) { if (num < 1 || num > 1000) { printf("The number belongs to the segment [1, 1000]\n"); scanf("%d", &num); continue; } (num > n) ? printf("Less \n") : printf("More \n"); scanf("%d", &num); count += 1; } printf("Number guessed \n"); printf("Attempts are made: %d\n", count); printf("================================\n\n"); } void second() { int left = 1, right = 1000, count = 0, mid; char sign; printf("================================\n"); printf("Use '<' if hidden number less\n"); printf("Use '>' if hidden number more\n"); printf("Use '=' if hidden number equal\n"); while (left <= right) { mid = (left + right) / 2; count += 1; printf("%d?\n", mid); do { scanf(" %c", &sign); } while (sign != '>' && sign != '<' && sign != '='); if (sign == '<') right = mid - 1; else if (sign == '>') left = mid + 1; else if (sign == '=') { printf("Attempts are made: %d\n", count); left = right + 1; } } printf("================================\n\n"); } int main() { printf("Game modes: \n"); printf("\t1. You guess the number guessed by the computer\n"); printf("\t2. The computer guesses the number you guessed\n"); printf("Enter '0' to end the game\n\n"); int num; do { printf("Select game mode: "); scanf("%d", &num); printf("\n"); if (num == 1) first(); if (num == 2) second(); } while (num != 0); return 0; }<file_sep>#include <iostream> #include <fstream> #include<string> #include<string.h> using namespace std; #ifndef _TITLE_H #define _TITLE_H struct Time{ string hours; string minutes; Time(); } ; struct Opening_Hours { string Day; Time open; Time close; Opening_Hours(); Opening_Hours& operator=(const Opening_Hours& other); }; struct Adress{ string street; string postcode; Adress& operator=(const Adress& other); }; struct Shop { string name; string phone_number; string specialization; Opening_Hours* op; Adress adress; string form_of_ownership; Shop(); Shop& operator=(const Shop& other); friend istream& operator >>(istream& os, Shop& shop); }; struct List { friend ostream& operator<<(ostream& os, const List& list); Shop* shop; int count; List(string adress); List(); ~List(); List& correct_base(List& first); List& operator=(const List& other); }; ostream& operator<<(ostream& os, const List& list); istream& operator >>(istream& os, Shop& shop); #endif <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <locale.h> int main() { float x1, y1, r1, x2, y2, r2, d; setlocale(LC_ALL, "Russian"); printf("Введите координаты центра окружности номер 1 и ее радиус"); scanf(" %f %f %f", &x1, &y1, &r1); printf("Введите координаты центра окружности номер 2 и ее радиус"); scanf(" %f %f %f", &x2, &y2, &r2); d = sqrt(x2 * x2 - 2 * x2 * x1 + x1 * x1 + y2 * y2 - 2 * y1 * y2 + y1 * y1); if (d > r1 + r2) { printf("Окружности не касаются"); } else if (d < abs(r1 - r2)) { printf("Малая окружность лежит внутри большой"); } else if ((r1 == r2) && (d == 0)) { printf("Окружности совпадают"); } else if (d == abs(r1 - r2)) { printf("Внутреннее касание окружностей"); } else if ((abs(r1 - r2) < d) && (d < r1 + r2)) { printf("Окружности пересекаются"); } else if (d == r1 + r2) { printf("Внешнее касание окружностей"); } return 0; }<file_sep>#include <stdio.h> #include "matrix.h" int main() { TMatrix* matrix_d, *m1, *m2, *res; allocate_m(&matrix_d, 2); fill_matrix(matrix_d); print_matrix(matrix_d); free_matrix(&matrix_d); allocate_m(&m1, 2); allocate_m(&m2, 2); fill_matrix(m1); fill_matrix(m2); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); res = add_constant(m1, 2); print_matrix(res); free_matrix(&res); res = multi_constant(m1, 2); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); return 0; } <file_sep>#include <string.h> #include <stdlib.h> #include <stdio.h> #include "card.h" #define LENGTH 512 #define WORD_LEN 128 cardIndex* alloc(int stringCount, int authorsCount) { int i, g; cardIndex* cards = (cardIndex*)malloc(stringCount * sizeof(cardIndex)); for (i = 0; i < stringCount; i++) { cards[i].authors = (char**)malloc(authorsCount * sizeof(char*)); for (g = 0; g < authorsCount; g++) { cards[i].authors[g] = (char*)malloc(WORD_LEN * sizeof(char)); } } return cards; } void memoryFree(cardIndex* cards, int stringCount, char** section, int authorsCount, int sectionCount, char* path) { int i,g; free(path); for (i = 0; i < stringCount; i++) { for (g = 0; g < authorsCount; g++) { free(cards[i].authors[g]); } free(cards[i].authors); } free(cards); for (i = 0; i < sectionCount; i++) { free(section[i]); } free(section); } char* menu() { char* path = (char*)malloc(_MAX_PATH * sizeof(char)); do{ printf("Enter the file path...\n"); scanf("%s", path); FILE* file = fopen(path, "r"); if (file == NULL) { printf("ERROR: Could not open file!\n"); } else { fclose(file); return path; } } while (1); } int strCount(char* path) { int count = 0; char* s = (char*)malloc(LENGTH * sizeof(char)); FILE* file = fopen(path, "r"); while (1) { if (fgets(s, LENGTH, file) != NULL) { if (strcmp(s, "\n") != 0) { count++; } } else { break; } } fclose(file); free(s); return count; } void readFile(cardIndex* cards, char* path, int stringCount, int authorsCount) { char* token; char delim[] = ";\n"; int i = 0; int j = 0; int g; char** b = (char**)malloc(stringCount * sizeof(char*)); for (g = 0; g < stringCount; g++) { b[g] = (char*)malloc(LENGTH * sizeof(char)); } FILE* file = fopen(path, "r"); char str [LENGTH]; while (1) { if (fgets(str, 512, file) != NULL) { for (token = strtok(str, delim); token; token = strtok(NULL, delim)) { switch (i) { case 0: strcpy(b[j], token); break; case 1: strcpy(cards[j].title, token); break; case 2: strcpy(cards[j].publisher, token); break; case 3: strcpy(cards[j].section, token); break; case 4: if (strcmp(token, "Available") == 0) { cards[j].avb = AVAILABLE; } else { cards[j].avb = UNAVAILABLE; } break; case 5: cards[j].evaluation = strtof(token, NULL); i = -1; j++; break; } i++; } } else { break; } } for (i = 0; i < stringCount; i++) { g = 0; for (token = strtok(b[i], ","); token; token = strtok(NULL, ",")) { strcpy(cards[i].authors[g], token); g++; } for (; g < authorsCount; g++) { strcpy(cards[i].authors[g], "NULL"); } } for (g = 0; g < stringCount; g++) { free(b[g]); } free(b); fclose(file); } int isEqual(char** mass, char* word, int count) { for (int i = 0; i < count; i++) { if (strcmp(mass[i], word) == 0) { return 1; } } return 0; } int countSubs(char* string, char* sub) { int l = strlen(sub); int n = 0; while ((string = strstr(string, sub)) != NULL) { ++n; string += l; } return n; } int authorsCount(char* path, int stringCount) { char* token; char delim[] = ";\n"; int i = 0; int j = 0; int count = 0; int g; FILE* file = fopen(path, "r"); char str[LENGTH]; while (1) { if (fgets(str, LENGTH, file) != NULL) { for (token = strtok(str, delim); token; token = strtok(NULL, delim)) { switch (i) { case 0: if (count > countSubs(token, ",")) { break; } count = countSubs(token, ","); break; case 5: i = -1; j++; break; } i++; } } else { break; } } fclose(file); return count+1; } void bookPrint(cardIndex* cards, int authorsCount, int g) { int j; printf("--------------|--------------\n"); printf("%s\n", cards[g].title); printf("Authors: "); for (j = 0; j < authorsCount; j++) { if (strcmp(cards[g].authors[j], "NULL") == 0) continue; printf("%s", cards[g].authors[j]); } printf("\n"); printf("Publisher: %s\n", cards[g].publisher); printf("Availability: "); if (cards[g].avb == 0) { printf("available\n"); } else { printf("unavailable\n"); } printf("Evaluation: %.1f\n", cards[g].evaluation); } int secCt(cardIndex* cards, int stringCount) { int ind = 0,i = 0; char** buff = (char**)malloc(stringCount * sizeof(char*)); for (i = 0; i < stringCount; i++) { buff[i] = (char*)malloc(WORD_LEN * sizeof(char)); } for (i = 0; i < stringCount; i++) { if (isEqual(buff, cards[i].section, stringCount) == 0) { strcpy(buff[ind], cards[i].section); ind++; } } for (i = 0; i < stringCount; i++) { free(buff[i]); } free(buff); return ind; } char** booksBySection(cardIndex* cards, int stringCount, int authorsCount, int* ct) { int ind = 0; int i; *ct = secCt(cards, stringCount); char** section = (char**)malloc((*ct) * sizeof(char*)); for (i = 0; i < (*ct); i++) { section[i] = (char*)malloc(WORD_LEN * sizeof(char)); } for (i = 0; i < stringCount; i++) { if (isEqual(section, cards[i].section, *ct) == 0) { strcpy(section[ind], cards[i].section); ind++; } } for (i = 0; i < *ct; i++) { printf("\nBooks from %s:\n", section[i]); for (int g = 0; g < stringCount; g++) { if (strcmp(cards[g].section, section[i]) == 0) { bookPrint(cards, authorsCount, g); } } } return section; } void selectBook(cardIndex* cards, char** section, int stringCount, int authorsCount, int sectionCount) { int i; int j = 0; int userInput; int* indexes = (int*)malloc((stringCount+1) * sizeof(int)); do{ printf("\nSelect the library section you are interested in:\n"); for (i = 0; i < sectionCount; i++) { printf("%d) %s\n", i, section[i]); } if (scanf("%d", &userInput) != 1) { printf("Scanf error!"); return 1; } } while (userInput > i-1 || userInput < 0); for (i = 0; i < stringCount; i++) { if (strcmp(cards[i].section, section[userInput]) == 0) { printf("%d) %s\n", j, cards[i].title); indexes[j] = i; j++; } } do { printf("\nChoose the book you are interested in:\n"); if (scanf("%d", &userInput) != 1) { printf("Scanf error!"); return 1; } } while (j-1 < userInput || userInput < 0); for (i = 0; i < stringCount; i++) { if (strcmp(cards[i].title, cards[indexes[userInput]].title) == 0) { bookPrint(cards, authorsCount, i); break; } } free(indexes); }<file_sep>#ifndef _CARD_H #define _CARD_H #include <string> #include <vector> #include <set> using namespace std; enum availability { available, not_available }; struct cardIndex { string* authors; int authorsCount; string title; string publisher; string section; availability avb; float evaluation; bool operator==(const string& otherTitle) const; bool operator!=(const string& otherTitle) const; friend ostream& operator<<(ostream& os, const cardIndex& card); }; struct lib { cardIndex* cards; int count; lib(const string& path); ~lib(); set <string> booksBySection(); vector <cardIndex> findBooks(const set <string>& sections); void getBook(const vector <cardIndex>& books); int strCount(const string& path); }; string menu(); #endif // !_CARD_H <file_sep>#ifndef _INTERFACE_H #define _INTERFACE_H #include "container.h" #include "receipt.h" string start(); void menu(dataBase& data, Container<Receipt>& receipts); #endif // !_INTERFACE_H <file_sep>#include <stdio.h> void main() { float h, w, d; // 180 <= h, w <= 220 sm, 50 <= d <= 90 sm float th_DSP = 0.015f, th_DVP = 0.005f, th_door = 0.01f; // m float back_wall, side_walls, caps, doors, shelves; // cm float q_tree = 900.0f, q_DSP = 800.0f, q_DVP = 800.0f; // kg / m^3 int n; // amount of shelves printf("Input h, w, d: \n"); printf("(180 <= h, w <= 220 sm, 50 <= d <= 90 sm)\n"); scanf("%f %f %f", &h, &w, &d); if (h < 180 || h > 220 || w < 180 || w > 220 || d < 50 || d > 90) { printf("Incorrect data."); return; } else { // amount of shelves n = (int)(h / 40.f); // sm > m h = h / 100.f; w = w / 100.f; d = d / 100.f; // kg back_wall = q_DVP * h * w * th_DVP; side_walls = q_DSP * h * d * th_DSP * 2; caps = q_DSP * (w - 2 * th_DSP) * (d - th_DVP) * th_DSP * 2; doors = q_tree * h * w * th_door; shelves = q_DSP * (w - 2 * th_DSP) * (d - th_DVP) * th_DSP * n; printf("%f", back_wall + side_walls + caps + doors + shelves); } }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include "workers.h"; int main() { worker** w; char* path = get_Path(); int N = amount(path); allocate_workers(&w, N); adding(w, path); higher_education(w, N); free_workers(&w, N); } // //C:\Users\itmm-y23a\Desktop\mp1-practice\Chistov AD\Practice2.1\Practice2.1\workers.txt<file_sep>#ifndef _RECEIPT_H #define _RECEIPT_H #include "container.h" #include <vector> #include <string> using namespace std; class Product { public: Product(int code, const string& name, double price); Product(); int getCode() const; float getPrice() const; string getName() const; private: int code; string name; float price; }; struct dataBase { dataBase(const string& path); ~dataBase(); Product* searchProductByCode(); void writeData(const string& path); vector<pair<Product*, int>> data; }; struct Time { int hour; int minute; }; struct date { int day; int mounth; int year; }; class ReceiptLine { public: ReceiptLine(); ReceiptLine(Product* product, int count); Product* getProduct() const; int getCount() const; float getSumm() const; void setCount(int count); void setSumm(int summ); private: Product* product; int count; float summ; }; class Receipt { public: Receipt(); Receipt(int code); Receipt(const Receipt& other); void reset(); double getTotal(); void dataUpdate(dataBase& data); void addItem(Product* product, dataBase& data); void removeItem(Product* product); Receipt& operator=(const Receipt& other); friend ostream& operator<<(ostream& os, Receipt& receipt); private: int code; Time time_; date date; void setTime(); Container<ReceiptLine> pr; }; #endif // !_RECEIPT_H <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> int random_function(int start, int end) { int n; n = start + rand() % (end - start + 1); return n; } int main() { int guess, n, mode, w, count = 1; n = random_function(1, 1000); printf("Witch of this game mode do u want to choose: Input 1 or 2 "); scanf("%i", &mode); if (mode == 1) { int c = 0, number; while (c == 0) { printf("Input a number. Can u guess it now?"); scanf("%d", &number); while (number > 1000 || number < 0) { printf("Input a number from 0 to 1000 "); scanf("%d", &number); } if (number == n) { c = 1; printf("You are a winner! Congretulations!. You won for %d attempts", count); } else { if (number < n) printf("Your number is smoller "); else printf("Your number is too huge "); count++; } } } else { int n1, number, r = 1000, l = 1, z = 0; char q; printf("Input a number and I`ll try to guess it "); scanf("%d", &number); getchar(); while (z == 0) { n1 = random_function(l+1,r-1); if (number == n1) { printf("OHHH, wait I GUESSED for %d attempts! ", count); return 0; } printf("Input > or < if my variant is bigger or smoller pls \n "); printf("It is a my number:\n %d ", n1); printf(" It is bigger, smaller or mb i guessed? \n"); count++; scanf("%c", &q); getchar(); if (q == '>') r = n1; else if (q == '<') l = n1; } } return 0; } <file_sep>#ifndef _WORKERS_H #define _WORKERS_H #include <string> using namespace std; struct worker { string id; string profession; string education; string last_job; string rsn_dismiss; string family_status; int contact_info; friend ostream& operator<<(ostream& out, const worker& w); }; struct labor { worker* w; int n; int amount(const string& path); labor(const string& path); void higher_education(const string& path); ~labor(); }; string get_path(); #endif <file_sep>#include <iostream> #include <fstream> void output(); using namespace std; int main() { output(); return 0; } <file_sep>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <locale.h> #include <windows.h> #include <stdbool.h> #include "header.h" int main(){ setlocale(LC_ALL, "Russian"); SetConsoleCP(1251); SetConsoleOutputCP(1251); int n; TSchool **sc; n = counting(); allocation(&sc, n); read_file(sc); print_file(sc, n); sorting(sc, n); printf("\n"); printf("\n"); print_file(sc, n); release(&sc, n); return 0; }<file_sep>#include "comand.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define N 1023 int new_initializing(Scommandbook* phonebook) { if (phonebook->comands != NULL) { //SPhone* copy = phonebook->phones; if (phonebook->comands == (Scommand*)malloc(100 * sizeof(Scommand))) { phonebook->length = 100; } else { printf("You have to much contacts"); return 0; } } else { if (!(phonebook->comands == (Scommand*)malloc(100 * sizeof(Scommand)))) { printf("Something went wrong\n"); return 0; } phonebook->length = 100; } return 1; } void scan(Scommandbook* book) { int len; int length; char filename[1023]; printf("Enter file path: "); // scanf("%s", filename); fgets(filename, N,stdin); FILE* f; len = strlen(filename); filename[len-1] = 0; f = fopen(filename, "r"); if (f == NULL) { printf("I can not open %s", filename); return 1; } fscanf(f,"%d",&length); book->length = length; // file operations... book->comands = (Scommand*)malloc(book->length * sizeof(Scommand)); for (int i = 0; i < book->length; i++) { char bufer[STRLEN] = { 0 }; fgets(bufer, STRLEN, f); size_t length = strlen(bufer) - 1; bufer[length] = '\0'; book->comands[i].Name = (char*) malloc((length + 1) * sizeof(char)); memcpy(book->comands[i].Name, bufer, (length + 1) * sizeof(char)); fgets(bufer, STRLEN, f); length = strlen(bufer) - 1; bufer[length] = '\0'; book->comands[i].City = (char*) malloc((length + 1) * sizeof(char)); memcpy(book->comands[i].City, bufer, (length + 1) * sizeof(char)); fscanf(f, "%d %d %d", &(book->comands[i].Games), &(book->comands[i].Points), &(book->comands[i].Players)); fgetc(f); } fclose(f); return 0; } void output() { Scommandbook book; book.comands = NULL; book.length = 0; scan(&book); size_t best_id = 0; if (book.comands != NULL) { for (size_t i = 1; i < book.length; i++) { if (book.comands[best_id].Points < book.comands[i].Points) best_id = i; } printf("%s\n%s\n%d\n%d\n%d", book.comands[best_id].Name, book.comands[best_id].City, book.comands[best_id].Games, book.comands[best_id].Players, book.comands[best_id].Points); } }<file_sep>#include "title.h" istream& operator >>(istream& os, Shop& shop) { os >> shop.name >> shop.adress.street >> shop.phone_number >> shop.specialization >> shop.op[0].Day >> shop.op[0].open.hours >> shop.op[0].open.minutes >> shop.op[0].close.hours >> shop.op[0].close.minutes >> shop.op[1].Day >> shop.op[1].open.hours >> shop.op[1].open.minutes >> shop.op[1].close.hours >> shop.op[1].close.minutes >> shop.op[2].Day >> shop.op[2].open.hours >> shop.op[2].open.minutes >> shop.op[2].close.hours >> shop.op[2].close.minutes >> shop.op[3].Day >> shop.op[3].open.hours >> shop.op[3].open.minutes >> shop.op[3].close.hours >> shop.op[3].close.minutes >> shop.op[4].Day >> shop.op[4].open.hours >> shop.op[4].open.minutes >> shop.op[4].close.hours >> shop.op[4].close.minutes >> shop.op[5].Day >> shop.op[5].open.hours >> shop.op[5].open.minutes >> shop.op[5].close.hours >> shop.op[5].close.minutes >> shop.op[6].Day >> shop.op[6].open.hours >> shop.op[6].open.minutes >> shop.op[6].close.hours >> shop.op[6].close.minutes >> shop.form_of_ownership >> shop.adress.postcode; return os; } ostream& operator<<(ostream& os, const List& list) { for (int j = 0; j < list.count; j++) { os << "\nName: " << list.shop[j].name << "\nAdress: " << list.shop[j].adress.street << "\nPhone number: " << list.shop[j].phone_number << "\nSpecialization : " << list.shop[j].specialization << "\nForm of ownership: " << list.shop[j].form_of_ownership << "\nPostcode: " << list.shop[j].adress.postcode << endl; for (int i = 0; i < 7; i++) { if (list.shop[j].op[i].open.hours == "closed") cout << list.shop[j].op[i].Day << ": closed" << endl; else { cout << list.shop[j].op[i].Day << ": " << list.shop[j].op[i].open.hours << ":" << list.shop[j].op[i].open.minutes << "-" << list.shop[j].op[i].close.hours << ":" << list.shop[j].op[i].close.minutes << endl; } } } return os; } List::List(string adress) { ifstream base(adress); string line; int count = 0; if (base.is_open()) { cout << "File opened successfully!\n"; while (!base.eof()) { getline(base, line); count++; } } else { cout << "Error opening file"; exit(1); } //base.seekg(0); base.close(); ifstream file(adress); this->count = count-1; shop = new Shop[this->count]; for (int j = 0; j < this->count; j++) shop[j].op = new Opening_Hours[7]; for (int i = 0; i < this->count; i++) { file >> shop[i]; } file .close(); } List::List() { count = 1; shop = new Shop[1]; shop[0] = Shop(); } List::~List() { for (int i = 0; i < count; i++) { delete[] shop[i].op; } delete[] shop; } Shop::Shop() { name = " "; phone_number = " "; specialization = " "; op = new Opening_Hours[7]; for (int i = 0; i < 7; i++) op[i] = Opening_Hours(); form_of_ownership = " "; adress = Adress(); } Time::Time() { minutes = " "; hours = " "; } Opening_Hours::Opening_Hours() { Day = " "; open = Time::Time(); close = Time::Time(); } Opening_Hours& Opening_Hours::operator=(const Opening_Hours& other) { this->Day = other.Day; this->open = other.open; this->close = other.close; return *this; } List& List::correct_base(List& first) { int count = 0; for (int i = 0; i < first.count; i++) { if (((first.shop[i].specialization.compare("Products")) == 0)) { for (int j = 0; j < 7; j++) { if (first.shop[i].op[j].open.hours != "00" || first.shop[i].op[j].open.minutes != "00" || first.shop[i].op[j].close.hours != "00" || first.shop[i].op[j].close.minutes != "00") break; else { if (j == 6) count++; } } } } this->count = count; this->shop = new Shop[this->count]; for (int c = 0; c < this->count; c++) this->shop[c].op = new Opening_Hours[7]; for (int j = 0; j < this->count; j++) { for (int i = 0; i < first.count; i++) { if (first.shop[i].specialization.compare("Products") == 0) { for (int d = 0; d < 7; d++) { if (first.shop[i].op[d].open.hours != "00" || first.shop[i].op[d].open.minutes != "00" || first.shop[i].op[d].close.hours != "00" || first.shop[i].op[d].close.minutes != "00") d = 6; else { if (d == 6) { this->shop[j] = first.shop[i]; j++; } } } } } } return *this; } Adress& Adress::operator=(const Adress& other) { this->street = other.street; this->postcode = other.postcode; return *this; } Shop& Shop::operator=(const Shop& other) { this->name = other.name; this->specialization = other.specialization; this->form_of_ownership = other.form_of_ownership; this->phone_number = other.phone_number; this->adress = other.adress; this->op = new Opening_Hours[7]; for (int i = 0; i < 7; i++) { this->op[i] = other.op[i]; } return *this; } List& List::operator=(const List& other) { this->count = other.count; if (this->shop != nullptr) delete[] this->shop; this->shop = new Shop[other.count]; for (int j = 0; j < other.count; j++) this->shop[j].op = new Opening_Hours[7]; for (int i = 0; i < other.count; i++) this->shop[i] = other.shop[i]; return *this; } <file_sep>#include<stdio.h> #include<math.h> int main() { double h, w, d, q_dsp = 725, q_dvp = 850, q_wood = 700, k, t_dsp = 0.015, t_dvp = 0.005, t_wood = 0.01, v1, v2, v3, v4, v5, v_dsp, m_dvp, m_dsp, m_wood, m; printf("Enter the height of the cabinet in meters: "); scanf_s("%lf", &h); printf("\nEnter the width of the cabinet in meters: "); scanf_s("%lf", &w); printf("\nEnter the depth of the cabinet in meters: "); scanf_s("%lf", &d); if ((h < 1.8) || (h > 2.2)) { printf("Incorrect height, 1.8<=height>=2.2"); return 1; } if ((w < 0.8) || (w > 1.2)) { printf("Incorrect width, 0.8<=width>=1.2"); return 1; } if ((d < 0.5) || (d > 0.9)) { printf("Incorrect depth, 0.5<=depth>=0.9"); return 1; } k = (int)(h / 0.4); v1 = h * w * t_dvp; v2 = 2 * h * d * t_dsp; v3 = 2 * (w - 2 * t_dsp) * d * t_dsp; v4 = w * h * t_wood; v5 = k * (w - 2 * t_dsp) * d * t_dsp; v_dsp = v2 + v3 + v5; m_dvp = v1 * q_dvp; m_dsp = (v2 + v3 + v5) * q_dsp; m_wood = v4 * q_wood; m = m_dvp + m_dsp + m_wood; printf("%f", m); return 0; }<file_sep>#include <iostream> #include "Header.h" #include "ClientSide.h" int main() { std::string file_name; TProductsDatabase database(file_name); work_with_client(database); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <string> #include <vector> #include "cars.h" using namespace std; Car::Car() { brand = " "; color = " "; serial_number = " "; registration_number = " "; count_door = " "; year = " "; price = " "; } Car::Car(string _brand, string _color, string _serial_number, string _registration_number, string _count_door, string _year, string _price) { this->brand = _brand; this->color = _color; this->serial_number = _serial_number; this->registration_number = _registration_number; this->count_door = _count_door; this->year = _year; this->price = _price; } ostream& operator<<(ostream& output_stream, const Car& car) { output_stream << "Brand: " << car.brand << endl; output_stream << "Color: " << car.color << endl; output_stream << "Serial number: " << car.serial_number << endl; output_stream << "Regestrarion number: " << car.registration_number << endl; output_stream << "Numbers of doors: " << car.count_door << endl; output_stream << "Year of car manufacture: " << car.year << endl; output_stream << "Price: " << car.price << endl; return output_stream; } string GetFilePath() { string filepath; cout << "Enter file path: "; cin >> filepath; return filepath; } Car ReadCarEntity(ifstream& file) { string car_brand; getline(file, car_brand); string car_color; getline(file, car_color); string car_serial_number; getline(file, car_serial_number); string car_registration_number; getline(file, car_registration_number); string car_count_door; getline(file, car_count_door); string car_year; getline(file, car_year); string car_price; getline(file, car_price); Car new_car = { car_brand, car_color, car_serial_number, car_registration_number, car_count_door, car_year, car_price }; return new_car; } vector<Car> ReadCarFile(const string& filepath) { ifstream file; file.open(filepath); if (!file.is_open()) { // check if the file can be opened throw "Failed to open file\n"; } vector <Car> cars; // we assume that the file contains information about at least one car string tmp; while (!file.eof()) { Car current_car = ReadCarEntity(file); cars.push_back(current_car); getline(file, tmp); } file.close(); return cars; } bool Car::operator<(const Car& guest_car) const { if (year < guest_car.year) { return true; } return false; } Car FindOldestCar(const vector <Car>& cars) { Car oldest_car = cars[0]; for (int i = 1; i < cars.size(); ++i) { if (cars[i] < oldest_car) { oldest_car = cars[i]; } } return oldest_car; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <string> #include <iostream> #include <vector> #include "films.h" int main() { // get path to file with films std::string message = "Enter the path to file : "; std::string path = getInput(message); std::cout << path << '\n'; // read file and save info about Films to array std::vector<Film> films; films = ReadFileWithFilms(path); // get films by procuder while (true) { std::string producer_info = getInput("Enter producer's name and surname separated by a space: "); Producer inputProducer = getProducerFromString(producer_info); std::cout << inputProducer << '\n'; std::vector<Film> found_films = getFilmsByProducer(films, inputProducer); // print answer std::cout << "Count of found films by entered producer = " << found_films.size() << "\n\n"; for (int i = 0; i < found_films.size(); ++i) { std::cout << found_films[i] << '\n'; } // ask to continue std::cout << "Do you want to continue? (Y/N) : "; std::string choice; std::getline(std::cin, choice); if (choice == "N" || choice == "n") { break; } } return 0; } <file_sep> #ifndef _MATRIX_H #define _MATRIX_H typedef struct { int n; float* x; } TMatrix; void matrix_alloc(TMatrix** matrix, int n); void free_matrix(TMatrix** matrix); void scan_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix); TMatrix* matrix_add_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* matrix_add_constant(TMatrix* matrix, float c); TMatrix* matrix_multi_constant(TMatrix* matrix, float c); TMatrix* matrix_multi_matrix(TMatrix* matrix1, TMatrix* matrix2); #endif <file_sep>#include "Book.h" #include <iostream> #include <string> #include <fstream> #include <locale.h> #include <sstream> #define SECTION "Любой" string get_path() { string line; cout << "Введите название файла" << endl; ifstream file; file.exceptions(ifstream::badbit | ifstream::failbit); int c; do { getline(cin, line); try { file.open(line); c = 1; } catch (const std::exception& ex) { cout << "Неверно введён файл" << endl; c = 0; } } while (c != 1); return line; } int TLib::count_books(const string& path) const { string line; ifstream file; file.open(path); int count = 0; while (file.peek() != EOF) { getline(file, line); count++; } file.close(); return count; } TBook::TBook() { this->Couaut = 0; this->Author = nullptr; this->Name = ""; this->Publishing = ""; this->Section = ""; this->Availability = false; this->Score = 0; } TLib::TLib() { this->books = nullptr; this->count = 0; this->CountUnic = 0; this->unic_section = nullptr; } ostream& operator << (std::ostream& out, TBook& book) { out << "Автор - "; for (int j = 0; j < book.Couaut; j++) { out << book.Author[j] << " "; } out << " | Название книги - " << book.Name; out << "| Издательство - " << book.Publishing; out << "| Жанр - " << book.Section; if (book.Availability) { out << "| Наличие - Есть"; } else { out << "| Наличие - Нет"; } out << "| Оценка - " << book.Score << endl; return out; } ostream& operator <<(std::ostream& out, TLib& lib) { out << "Имеются следующие книги в нашей библиотеке: " << endl; for (int i = 0; i < lib.count; i++) { out << lib.books[i] << endl; } return out; } TBook TLib :: GetBook(int i) const { return this->books[i]; } int TLib::count_unic() const { int unic = 0; for (int i = 0; i < count; i++) { int flag = 0; for (int j = i + 1; j < count; j++) { if (this->GetBook(i).GetSection() == this->GetBook(j).GetSection()) { flag++; break; } } if (flag == 0) unic++; } return unic; } string TBook :: GetSection() { return this->Section; } int TLib::GetCountUnic() const { return this->CountUnic; } void TLib::SetUnicSection(string* Unic_Section) { this->unic_section = new string[this->GetCountUnic()]; for (int i = 0; i < this->GetCountUnic(); i++) { this->unic_section[i] = Unic_Section[i]; } } void TLib::create_section() { string* unic_section = new string[this->GetCountUnic()]; int k = 0; for (int i = 0; i < count; i++) { int flag = 0; for (int j = i + 1; j < count; j++) { if (this->GetBook(i).GetSection() == this->GetBook(j).GetSection()) { flag++; break; } } if (flag == 0) { unic_section[k] = this->GetBook(i).GetSection(); k++; } } this->SetUnicSection(unic_section); } void TLib::print_unique_sections() { for (int i = 0; i < this->CountUnic; i++) { cout << (i + 1) << "." << this->unic_section[i] << endl; } cout << endl << "0- Если хотите выйти" << endl; } TLib::TLib(const TLib& lib) { this->count = lib.count; this->books = new TBook[this->count]; this->CountUnic = lib.CountUnic; for (int i = 0; i < this->count; i++) { this->books[i] = lib.books[i]; } this->unic_section = new string[this->CountUnic]; for (int i = 0; i < this->CountUnic; i++) { this->unic_section[i] = lib.unic_section[i]; } } TBook::TBook(const TBook& book) { this->Couaut = book.Couaut; this->Author = new string[Couaut]; for (int i = 0; i < Couaut; i++) { this->Author[i] = book.Author[i]; } this->Name = book.Name; this->Publishing = book.Publishing; this->Section = book.Section; this->Availability = book.Availability; this->Score = book.Score; } string TLib :: GetUnicSection(int i) const { return this->unic_section[i]; } TLib TLib::search_by_section(const string section_name) { int count_unqie_books = 0; for (int i = 0; i < this->count; i++) { if (section_name == this->GetBook(i).GetSection()) { count_unqie_books++; } } TLib sectionLibrary; sectionLibrary.books = new TBook[count_unqie_books]; sectionLibrary.unic_section = new string[1]; sectionLibrary.unic_section[0] = section_name; int j = 0; for (int i = 0; i < this->count; i++) { if (section_name == this->GetBook(i).GetSection()) { sectionLibrary.books[j] = this->books[i]; j++; } } sectionLibrary.count = count_unqie_books; sectionLibrary.CountUnic = 1; return sectionLibrary; } TLib::TLib(const string& path) { this->count = count_books(path); this->books = new TBook[count]; int i = 0; string line; string authorNames; ifstream file; file.open(path);; while (i < count) { string name, publishing, section ; string* author; bool availability; int score; getline(file, authorNames, ';'); getline(file, name, ';'); getline(file, publishing, ';'); getline(file, section, ';'); getline(file, line, ';'); if (line == "Есть") availability = true; else availability = false; getline(file, line, '\n'); score = atoi(line.c_str()); int couaut = 0; stringstream authorNameStream(authorNames); string Name; while (getline(authorNameStream, Name, ',')) { couaut++; } author = new string[couaut]; int j = 0; authorNameStream.clear(); authorNameStream.seekg(0, std::ios::beg); while (getline(authorNameStream, Name, ',')) { author[j] = Name; j++; } books[i].SetBook(couaut, author, name, publishing, section, availability, score); i++; delete[] author; } int CountUnic; CountUnic= count_unic(); this->Set_unic(CountUnic); create_section(); file.close(); } void TLib::Set_unic(int unic) { this->CountUnic = unic; } void TBook::SetBook( const int TCouaut, const string* TAuthor, const string TName, const string TPublishing, const string TSection, const bool TAvailability, const int TScore) { this->Couaut = TCouaut; this->Author = new string[Couaut]; for (int j = 0; j < Couaut; j++) { this->Author[j] = TAuthor[j]; } this->Name = TName; this->Publishing = TPublishing; this->Section = TSection; this->Availability = TAvailability; this->Score = TScore; } TBook::~TBook() { delete[] this->Author; } TLib::~TLib() { delete[] this->books; if (this->unic_section != nullptr) { delete[] this->unic_section; } } TBook& TBook::operator=(const TBook& book) { this->Couaut = book.Couaut; this->Author = new string[book.Couaut]; for (int i = 0; i < book.Couaut; i++) { this->Author[i] = book.Author[i]; } this->Name = book.Name; this->Publishing = book.Publishing; this->Section = book.Section; this->Availability = book.Availability; this->Score = book.Score; return *this; } TLib& TLib:: operator=(const TLib& lib) { this->count = lib.count; this->CountUnic = lib.CountUnic; this->books = new TBook[count]; for (int i = 0; i < count; i++) { this->books[i] = lib.books[i]; } this->unic_section = new string[CountUnic]; for (int i = 0; i < CountUnic; i++) { this->unic_section[i] = lib.unic_section[i]; } return *this; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "matrix.h" void allocate_matrix(Matrix** matr, int n) { (*matr) = (Matrix*)malloc(sizeof(Matrix) * 1); (*matr)->n = n; (*matr)->x = (float*)malloc(sizeof(float) * (n * n)); } void free_matrix(Matrix** matr) { free((*matr)->x); free(*matr); } void fill_matrix(Matrix* matr, int n) { int i; for (i = 0; i < n * n; i++) { scanf("%f", &(matr->x[i])); } } void print_matrix(Matrix* matr, int n) { int i; for (i = 0; i < n * n; i++) { printf("%.1f ", matr->x[i]); if ((i + 1) % n == 0) { printf("\n "); } } printf("\n"); } Matrix* add_dot(Matrix* matr, float a){ printf("\nadd dot:\n\n "); Matrix* res; int i; allocate_matrix(&res, 3); int n = res->n; for (i = 0; i < n * n; i++) { res->x[i] = (matr->x[i]) + a; } return res; } Matrix* multiple_dot(Matrix* matr, float a) { printf("multiple dot:\n\n "); Matrix* res; int i; allocate_matrix(&res, 3); int n = res->n; for (i = 0; i < n * n; i++) { res->x[i] = (matr->x[i]) * a; } return res; } Matrix* add_matrix(Matrix* matr1, Matrix* matr2) { printf("add matrix:\n\n "); Matrix* res; int i, j; if (matr1->n != matr2->n) { printf("matrices must be of the same order"); return NULL; } allocate_matrix(&res, 3); int n = res->n; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { res->x[i * n + j] = (matr1->x[i * n + j]) + (matr2->x[i * n + j]); } } return res; } Matrix* multiple_matrix(Matrix* matr1, Matrix* matr2) { printf("multiple_matrix:\n\n "); Matrix* res; int i, j, k; if (matr1->n != matr2->n) { printf("matrices must be of the same order"); return NULL; } allocate_matrix(&res, matr1->n); for (k = 0; k < (res->n) * (res->n); k++) { res->x[k] = 0.0f; } for (k = 0; k < res->n; k++) { for (i = 0; i < res->n; i++) { for (j = 0; j < res->n; j++) { res->x[k * res->n + i] += matr1->x[k * res->n + j] * matr2->x[j * res->n + i]; } } } return res; }<file_sep>#include <stdio.h> #include <windows.h> #include <stdlib.h> #include"Sorts.h" char names[LENGTH][LENGTH]; CHAR path[MAX_PATH]; long long int count = 0; void findfiles(CHAR* path); file_t* cpy_arr(file_t* files, int len, int* lensNames) { int i; file_t* copy_files; copy_files = (file_t*)malloc(len * sizeof(file_t)); for (i = 0; i < len; i++) { copy_files[i].name = (char*)malloc((lensNames[i] + 1) * sizeof(char)); } for (i = 0; i < len; i++) { strcpy(copy_files[i].name, files[i].name); copy_files[i].l = files[i].l; } return copy_files; } void StartTimer() { LARGE_INTEGER A; QueryPerformanceCounter(&A); count = A.QuadPart; } void StopTimer() { LARGE_INTEGER A; QueryPerformanceCounter(&A); printf("and spent %.2lf ms\n", (double)(A.QuadPart - count) / 1000); } void print_files(file_t* files, int len) { int i; for (i = 0; i < len; i++) { printf("%s %d\n", files[i].name, files[i].l); } } void findfiles(CHAR* path, file_t* filess) { int i = 0; WIN32_FIND_DATAA files; HANDLE lastfile; lastfile = FindFirstFileA(path, &files); FindNextFileA(lastfile, &files); if (lastfile != INVALID_HANDLE_VALUE) { while (FindNextFileA(lastfile, &files)) { strcpy(filess[i].name, files.cFileName); filess[i].l = files.nFileSizeLow; i++; } } FindClose(lastfile); } int l_files(CHAR* path) { int c = 0; WIN32_FIND_DATAA files; HANDLE lastfile; lastfile = FindFirstFileA(path, &files); FindNextFileA(lastfile, &files); if (lastfile != INVALID_HANDLE_VALUE) { while (FindNextFileA(lastfile, &files)) { c++; } } FindClose(lastfile); return c; } int* l_names_files(CHAR* path, int count_files) { int i = 0; int* lens_names = (int*)malloc(count_files * sizeof(int)); WIN32_FIND_DATAA files; HANDLE lastfile; lastfile = FindFirstFileA(path, &files); FindNextFileA(lastfile, &files); if (lastfile != INVALID_HANDLE_VALUE) { while (FindNextFileA(lastfile, &files)) { lens_names[i] = strlen(files.cFileName); i++; } } FindClose(lastfile); return lens_names; } int main() { int n, i, count_files; int* lensNames; file_t* files; printf("Enter directory:"); scanf("%s", &path); count_files = l_files(path); lensNames = l_names_files(path, count_files); files = (file_t*)malloc(count_files * sizeof(file_t)); for (i = 0; i < count_files; i++) { files[i].name = (char*)malloc((lensNames[i] + 1) * sizeof(char)); } printf("%d\n", count_files); findfiles(path, files); do { file_t* copy; printf("choose a sort\n"); scanf("%d", &n); copy = cpy_arr(files, count_files, lensNames); StartTimer(); if (n == 1) { mergeSort(copy, 0, i - 1); printf("MergeSort did this:\n"); } else if (n == 2) { BubbleSort(copy, i); printf("BubbleSort did this:\n"); } else if (n == 3) { QuickSort(copy, 0, i - 1); printf("QuickSort did this:\n"); } else if (n == 0) { return 0; } print_files(copy, count_files); StopTimer(); } while (1); for (i = 0; i < count_files; i++) { free(files[i].name); } free(files); } <file_sep>#include <iostream> #include <string> #include "products.h" using namespace std; TProduct::TProduct(const string& _code, const string& _name, const double _cost) { code = _code; name = _name; cost = _cost; } void TProduct::Set(const string _code, const string _name, const double _cost) { code = _code; name = _name; cost = _cost; } bool TProduct::operator==(const TProduct& p) const { if (code == p.code) return true; return false; } const TProduct& TProduct::operator=(const TProduct& p) { if (this != &p) { code = p.code; name = p.name; cost = p.cost; } return (*this); } ostream& TProduct::ostreamProduct(ostream& out) { out << code << " " << name << " " << cost; return out; }<file_sep>#ifndef _USERSIDE_H #define _USERSIDE_H #include "fileProcessing.h" #include <iostream> #include <string> #include <Windows.h> void working_with_user(Univ_database_t& unsdata); #endif<file_sep>#include <string.h> #include <stdlib.h> #include <stdio.h> #include "Header.h" void Allocate_memory_for_one_person(One_Person** person) { (*person) = (One_Person*)malloc(sizeof(One_Person) * 1); (*person)->Surname = (char*)malloc(sizeof(char) * 50); (*person)->Name = (char*)malloc(sizeof(char) * 50); (*person)->Middle_name = (char*)malloc(sizeof(char) * 50); (*person)->Gender = (char*)malloc(sizeof(char) * 50); (*person)->Nation = (char*)malloc(sizeof(char) * 50); (*person)->height = (char*)malloc(sizeof(char) * 50); (*person)->weight = (char*)malloc(sizeof(char) * 50); (*person)->phone_number = (char*)malloc(sizeof(char) * 50); (*person)->address.postal_code = (char*)malloc(sizeof(char) * 50); (*person)->address.Country = (char*)malloc(sizeof(char) * 50); (*person)->address.Region= (char*)malloc(sizeof(char) * 50); (*person)->address.Area = (char*)malloc(sizeof(char) * 50); (*person)->address.City = (char*)malloc(sizeof(char) * 50); (*person)->address.Street = (char*)malloc(sizeof(char) * 50); (*person)->address.House = (char*)malloc(sizeof(char) * 50); (*person)->address.Apart = (char*)malloc(sizeof(char) * 50); } int Count_struct_in_file(FILE* file) { int count = 0; int symbol; FILE* source_file = fopen(file, "r"); if (source_file == NULL) { printf("Error opening the file"); return -1; } do { symbol = fgetc(source_file); if (symbol == '\n') count ++; } while (symbol != EOF); //EOF - end file fclose(source_file); //Clouse file return count; } void Reading_a_file_line(One_Person* person,FILE* file) { char Current_line[300]; char Sepapration_Element[10] = ";"; int number = 0; char* ishod_str; fgets(Current_line, 300, file); ishod_str = strtok(Current_line, Sepapration_Element); while (Current_line != NULL) { if (number == 0) { strcpy(person->Surname,ishod_str); } if (number == 1) { strcpy(person->Name, ishod_str); } if (number == 2) { strcpy(person->Middle_name, ishod_str); } if (number == 3) { strcpy(person->Gender, ishod_str); } if (number == 4) { strcpy(person->Nation, ishod_str); } if (number == 5) { person->date.year= atoi(ishod_str); } if (number == 6) { person->date.month=atoi(ishod_str); } if (number == 7) { person->date.day=atoi(ishod_str); } if (number == 8) { strcpy(person->height, ishod_str); } if (number == 9) { strcpy(person->weight, ishod_str); } if (number == 10) { strcpy(person->phone_number, ishod_str); } if (number == 11) { strcpy(person->address.postal_code, ishod_str); } if (number == 12) { strcpy(person->address.Country, ishod_str); } if (number == 13) { strcpy(person->address.Region, ishod_str); } if (number == 14) { strcpy(person->address.Area, ishod_str); } if (number == 15) { strcpy(person->address.City, ishod_str); } if (number == 16) { strcpy(person->address.Street, ishod_str); } if (number == 17) { strcpy(person->address.House, ishod_str); } if (number == 18) { strcpy(person->address.Apart, ishod_str); } if ((number == 19)||(number>19)) { break; } ishod_str = strtok(NULL, Sepapration_Element); number++; } } void Print_Inforamation(One_Person* person) { printf("=================================================================\n"); printf("\nSurname: %s", person->Surname); printf("\n Name %s", person->Name); printf("\n Middle_name %s", person->Middle_name); printf("\nGender: %s", person->Gender); printf("\n Nationality: %s", person->Nation); printf("\n Height: %s", person->height); printf("\n Weight: %s", person->weight); printf("\nBirthday: %d %d %d", person->date.day, person->date.month, person->date.year); printf("\nTelephone Number: %s", person->phone_number); printf("\nHome address: "); printf("\nPostal Code: %s", person->address.postal_code); printf("\nCountry: %s", person->address.Country); printf("\nDistrict: %s", person->address.Region); printf("\nAreal: %s", person->address.Area); printf("\nTown: %s", person->address.City); printf("\nStreet: %s", person->address.Street); printf("\nHouse: %s", person->address.House); printf("\nApartament: %s", person->address.Apart); printf("\n=================================================================\n"); } void sorting_for_surname(One_Person** person, int n) { One_Person* temp; Allocate_memory_for_one_person(&temp); int i; int j; for (i = 0; i < n; i++) for (j = i + 1; j < n; j++) { if (strcmp(person[j]->Surname, person[i]->Surname) != 0) { if (strcmp(person[j]->Surname, person[i]->Surname) < 0) { temp = person[i]; person[i] = person[j]; person[j] = temp; } } else if (strcmp(person[j]->Surname, person[i]->Surname) == 0) { if (strcmp(person[j]->Name, person[i]->Name) < 0) { temp = person[i]; person[i] = person[j]; person[j] = temp; } } else if ((strcmp(person[j]->Surname, person[i]->Surname) == 0)&&(strcmp(person[j]->Name, person[i]->Name))) { if (strcmp(person[j]->Middle_name, person[i]->Middle_name) < 0) { temp = person[i]; person[i] = person[j]; person[j] = temp; } } } }//linear sorting by surname void Free_memory(One_Person** person) { free((*person)->address.Apart); free((*person)->address.House); free((*person)->address.Street); free((*person)->address.City); free((*person)->address.Area); free((*person)->address.Region); free((*person)->address.Country); free((*person)->address.postal_code); free((*person)->phone_number); free((*person)->weight); free((*person)->height); free((*person)->Nation); free((*person)->Gender); free((*person)->Middle_name); free((*person)->Name); free((*person)->Surname); free(*person); } void Reading_File(One_Person*** person, int* n, const FILE* file) { int i; int j; file = fopen(file, "r"); if (file == NULL) { printf("Error with open file"); return -1; } (*n) = Count_struct_in_file("Many_Persons.txt"); *person = (One_Person**)malloc(sizeof(One_Person*) * (*n)); for (i = 0; i < (*n); i++) { Allocate_memory_for_one_person(&((*person)[i])); Reading_a_file_line((*person)[i], file); } fclose(file); }<file_sep>#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include "banki.h" #define LENGTH 512 #define LEN 30 using namespace std; banklib::banklib(const string& path) { int stringcount = 0; ifstream file(path); if (!file.is_open()) { cout << "ERROR: Could not open file!" << endl; } else { string line; while (getline(file, line)) { if (line != "\0") { stringcount++; } } } //int stringcount = strcount(path); this->banki = new bankstruct[stringcount]; this->count = stringcount; int i = 0; int j = 0; //ifstream file(path); if (!file.is_open()) { cout << "ERROR: Could not open file!" << endl; } else { string str; string line; string token; ifstream file(path); while (getline(file, line)) { if (line == "\0") { continue; } stringstream ss(line); while (getline(ss, token, ',')) { switch (i) { case 0: banki[j].bankname = token; break; case 1: banki[j].banktype = token; break; case 2: banki[j].count = stoi(token); banki[j].our_vklad = new vkladstruct[banki[j].count]; break; case 3: banki[j].our_vklad[0].vkladname = token; break; case 4: banki[j].our_vklad[0].rate = stoi(token); break; case 5: banki[j].our_vklad[0].times = stoi(token); if (banki[j].count == 1) { i = -1; j++; } break; case 6: banki[j].our_vklad[1].vkladname = token; break; case 7: banki[j].our_vklad[1].rate = stoi(token); break; case 8: banki[j].our_vklad[1].times = stoi(token); if (banki[j].count == 2) { i = -1; j++; } break; case 9: banki[j].our_vklad[2].vkladname = token; break; case 10: banki[j].our_vklad[2].rate = stoi(token); break; case 11: banki[j].our_vklad[2].times = stoi(token); if (banki[j].count == 3) { i = -1; j++; } break; } i++; } } } file.close(); } banklib& banklib::search(float sum, int kMonths, string vkladType) { this->vkladType = vkladType; int a = 0; if (vkladType == "saving") { a = 0; } else if (vkladType == "debit") { a = 1; } else if (vkladType == "cumulative") { a = 2; } int maxI = 0; int i; float maxproc = -1; int koef = 0; int j = 0; int k = 0; for (i = 1; i < this->count; i++) { if (banki[i].count >= (a + 1)) { if (banki[i].our_vklad[a].rate > maxproc && kMonths >= banki[i].our_vklad[a].times) { koef = (int)kMonths / banki[i].our_vklad[a].times; maxproc = banki[i].our_vklad[a].rate; maxI = i; } } } double final_sum = sum; double s = (double)banki[maxI].our_vklad[a].times / 12; for (j = 0; j < koef; j++) { final_sum *= (double)(1.00 + maxproc * s / 100); } if (maxproc == -1) { cout << "The debit invest is not suitable for the terms" << endl; } else { cout << banki[maxI]; cout << banki[maxI].our_vklad[a]; cout << "If your invest " << sum << ", you will receive " << final_sum << endl; } return *this; } banklib::~banklib() { for (int i = 0; i < count; i++) { delete[] banki[i].our_vklad; } delete[] banki; } string getfile() { string path; while (true) { cout << "Enter the full location of the file" << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } else { cout << "ERROR: Could not open file!\n" << endl; } } } banklib::banklib(const banklib& banks) { //return *this;//опер присваивания count = banks.count; banki = new bankstruct[count]; for (int i = 0; i <count; i++) { banki[i].bankname = banks.banki[i].bankname; banki[i].banktype = banks.banki[i].banktype; //banki[i].count = banks.banki[i].count; int a; if (banks.vkladType == "saving") { a = 0; } else if (banks.vkladType == "debit") { a = 1; } else if (banks.vkladType == "cumulative") { a = 2; } banki[i].count = 1; banki[i].our_vklad = new vkladstruct[banki[i].count]; for (int j = 0; j < banks.banki[i].count; j++) { if(banks.banki[i].our_vklad[j].vkladname == banks.vkladType){ banki[i].our_vklad[0].rate = banks.banki[i].our_vklad[a].rate; banki[i].our_vklad[0].times = banks.banki[i].our_vklad[a].times; banki[i].our_vklad[0].vkladname = banks.banki[i].our_vklad[a].vkladname; } else { banki[i].our_vklad[0].rate = 0; banki[i].our_vklad[0].times = 0; banki[i].our_vklad[0].vkladname = "nothing"; } } } //return *this;//опер присваивания } bool vkladstruct::operator==(const string& vkladType) const { return (vkladname == vkladType); } bool vkladstruct::operator!=(const string& vkladType) const { return !(vkladname == vkladType); } ostream& operator<<(ostream& os, const banklib& banks) { /*int count = 0; if (banks.vkladType == "saving") { count = 1; } else if (banks.vkladType == "debit") { count = 1; } else if (banks.vkladType == "cumulative") { count = 1; }*/ os << "-----------------------" << endl; for (int i = 0; i < banks.count; i++) { //os << banks.banki[i]; for (int j = 0; j < banks.banki[i].count; j++) { if (banks.banki[i].our_vklad[j].vkladname != "nothing") { os << banks.banki[i]; os << banks.banki[i].our_vklad[j] << " "; os << endl; } } } os << "-----------------------" << endl; //count++; return os; } ostream& operator<<(ostream& os, const bankstruct& banki) { os << "Name of bank - " << banki.bankname << " "; os << "Type of bank - " << banki.banktype << endl; return os; } ostream& operator<<(ostream& os, const vkladstruct& our_vklad) { os << " Name of vklad - " << our_vklad.vkladname << " "; os << " Rate of vklad - " << our_vklad.rate << " "; os << " Minimum times of vklad - " << our_vklad.times << endl; return os; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <windows.h> #include <winbase.h> #include <profileapi.h> #define _FilesLimit 100000 typedef struct _FIND_DATA { DWORD nFileSize; WCHAR cFileName[MAX_PATH]; } FIND_DATA, * P_FIND_DATA, * LP_FIND_DATA; void bubble_sort(FIND_DATA* arr, ULONGLONG n); void merge(FIND_DATA* arr, ULONGLONG left, ULONGLONG mid, ULONGLONG right); void mergeSort(FIND_DATA* arr, ULONGLONG left, ULONGLONG right); void qSort(FIND_DATA* arr, ULONGLONG left, ULONGLONG right); int FindFiles(LPCSTR directory, FIND_DATA* filesArray); int check(LPCSTR directory); int main() { ULONGLONG i,j; int n,k,r; //переменные для запросов пользователя для выбора сортировки и т.п. long long time1, time2, time3, time4, time5, time6; int fB=0, fM=0, fQ=0; char directoryName[255], directoryNameNC[255]; FIND_DATA* filesArray, *filesArrayTmpB, *filesArrayTmpM, *filesArrayTmpQ; WIN32_FIND_DATA FindFileData; HANDLE hFind; filesArray = (FIND_DATA*)malloc(sizeof(FIND_DATA) * _FilesLimit); filesArrayTmpB = (FIND_DATA*)malloc(sizeof(FIND_DATA) * _FilesLimit); filesArrayTmpM = (FIND_DATA*)malloc(sizeof(FIND_DATA) * _FilesLimit); filesArrayTmpQ = (FIND_DATA*)malloc(sizeof(FIND_DATA) * _FilesLimit); printf("Pls write directory\n"); i = 0; do { gets_s(directoryName, 254); strcpy(directoryNameNC, directoryName); strcat(directoryName, "\\*"); n=check(directoryName); switch (n) { case (1): { printf(""); break; } case (2): { printf("No Files. Try with other dir\n"); break; } case (3): { printf("No such dir. Try again\n"); break; } } } while (n != 1); i=FindFiles(directoryName, filesArray); printf("\n\nFiles Found:\n"); for (j = 0; j < i; j++) { printf("%s %lld\n", filesArray[j].cFileName, filesArray[j].nFileSize); } printf("\nYou can check how long it takes different sorts to sort files in your directory\n"); printf("If you want to leave, write 0\n"); printf("\nChoose method:\n 1-bubble sort\n 2-mergeSort\n 3-qSort\n 4-Show which directory we are in\n"); printf(" 5-If you want to output a certain sort with the execution time and sorted directory in ascending or descending order\n"); do { scanf("%d", &n); switch (n) { case(1): { fB = 0; for (j = 0; j < i; j++) { filesArrayTmpB[j].nFileSize = filesArray[j].nFileSize; strcpy(filesArrayTmpB[j].cFileName, filesArray[j].cFileName); } QueryPerformanceCounter(&time1); bubble_sort(filesArrayTmpB, i); QueryPerformanceCounter(&time2); fB++; printf("\nThe directory is sorted. Write - 5 if you want to see the result and you will see further instructions\n"); break; } case(2): { fM = 0; for (j = 0; j < i; j++) { filesArrayTmpM[j].nFileSize = filesArray[j].nFileSize; strcpy(filesArrayTmpM[j].cFileName, filesArray[j].cFileName); } QueryPerformanceCounter(&time3); mergeSort(filesArrayTmpM, 0, i); QueryPerformanceCounter(&time4); fM++; printf("\nThe directory is sorted. Write - 5 if you want to see the result and you will see further instructions\n"); break; } case(3): { fQ = 0; for (j = 0; j < i; j++) { filesArrayTmpQ[j].nFileSize = filesArray[j].nFileSize; strcpy(filesArrayTmpQ[j].cFileName, filesArray[j].cFileName); } QueryPerformanceCounter(&time5); qSort(filesArrayTmpQ, 0, i-1); QueryPerformanceCounter(&time6); fQ++; printf("\nThe directory is sorted. Write - 5 if you want to see the result and you will see further instructions\n"); break; } case(4): { printf("\n%s\n", directoryNameNC); break; } case(5): { printf("Choose which method you want to see\n 1-bubble sort\n 2-mergeSort\n 3-qSort\n\n"); scanf("%d", &k); printf("\n"); switch (k) { case(1): { if (fB == 0) { printf("Sorting was not requested for the directory\n"); break; } else { printf("If you want to sort:\n write 1 - for increment\n write 2 - for decrement\n\n"); scanf("%d",&r); printf("\n\n"); switch (r) { case (1): { printf("\n\n-----\nSorted Files:\n-----\n\n"); for (j = 0; j < i; j++) { printf("%s %lld\n", filesArrayTmpB[j].cFileName, (LONGLONG)filesArrayTmpB[j].nFileSize); } printf("\nThe time it took to sort the bubble = %lld milliseconds\n\n", time2 - time1); break; } case (2): { printf("\n\n-----\nSorted Files:\n-----\n\n"); for (j = i; j > 0; j--) { printf("%s %lld\n", filesArrayTmpB[j-1].cFileName, (LONGLONG)filesArrayTmpB[j-1].nFileSize); } printf("\nThe time it took to sort the bubble = %lld milliseconds\n\n", time2 - time1); break; } } } break; } case(2): { if (fM == 0) { printf("Sorting was not requested for the directory\n"); } else { printf("If you want to sort:\n write 1 - for increment\n write 2 - for decrement\n\n"); scanf("%d", &r); switch (r) { case (1): { printf("\n\n-----\nSorted Files:\n-----\n\n"); for (j = 0; j < i; j++) { printf("%s %lld\n", filesArrayTmpM[j].cFileName, (LONGLONG)filesArrayTmpM[j].nFileSize); } printf("\nThe time it took to sort the mergeSort = %lld milliseconds\n\n", time4 - time3); break; } case (2): { printf("\n\n-----\nSorted Files:\n-----\n\n"); for (j = i; j > 0; j--) { printf("%s %lld\n", filesArrayTmpM[j-1].cFileName, (LONGLONG)filesArrayTmpM[j-1].nFileSize); } printf("\nThe time it took to sort the mergeSort = %lld milliseconds\n\n", time4 - time3); break; } } } break; } case(3): { if (fQ == 0) { printf("Sorting was not requested for the directory\n"); } else { printf("If you want to sort:\n write 1 - for increment\n write 2 - for decrement\n\n"); scanf("%d", &r); switch (r) { case (1): { printf("\n\n-----\nSorted Files:\n-----\n\n"); for (j = 0; j < i; j++) { printf("%s %lld\n", filesArrayTmpQ[j].cFileName, (LONGLONG)filesArrayTmpQ[j].nFileSize); } printf("\nThe time it took to sort the qSort = %lld milliseconds\n\n", time6 - time5); break; } case (2): { printf("\n\n-----\nSorted Files:\n-----\n\n"); for (j = i; j > 0; j--) { printf("%s %lld\n", filesArrayTmpQ[j-1].cFileName, (LONGLONG)filesArrayTmpQ[j-1].nFileSize); } printf("\nThe time it took to sort the qSort = %lld milliseconds\n\n", time6 - time5); break; } } } break; } } printf("\n"); } } } while (n != 0); free(filesArray); free(filesArrayTmpB); free(filesArrayTmpM); free(filesArrayTmpQ); return 0; } void bubble_sort(FIND_DATA* arr, ULONGLONG n) { ULONGLONG i, j ; FIND_DATA tmp; for (i = 0; i < n - 1; i++) { for (j = n-1; j > i; j--) { if (arr[j - 1].nFileSize > arr[j].nFileSize) { tmp.nFileSize = arr[j - 1].nFileSize; strcpy(tmp.cFileName, arr[j - 1].cFileName); arr[j - 1].nFileSize = arr[j].nFileSize; strcpy(arr[j - 1].cFileName, arr[j].cFileName); arr[j].nFileSize = tmp.nFileSize; strcpy(arr[j].cFileName, tmp.cFileName); } } } } void merge(FIND_DATA* arr, ULONGLONG left, ULONGLONG mid, ULONGLONG right) { ULONGLONG i=0, i1 = 0, i2 = 0; FIND_DATA* b = (FIND_DATA*)malloc(sizeof(FIND_DATA) * (right-left)); while ((left + i1 < mid) && (mid + i2 < right)) { if (arr[left + i1].nFileSize < arr[mid + i2].nFileSize) { b[i1+i2].nFileSize = arr[left + i1].nFileSize; strcpy(b[i1 + i2].cFileName, arr[left + i1].cFileName); i1++; } else { b[i1+i2].nFileSize = arr[mid + i2].nFileSize; strcpy(b[i1 + i2].cFileName, arr[mid + i2].cFileName); i2++; } } while (left + i1 < mid) { b[i1+i2].nFileSize = arr[left + i1].nFileSize; strcpy(b[i1 + i2].cFileName, arr[left + i1].cFileName); i1++; } while (mid + i2 < right) { b[i1 + i2].nFileSize = arr[mid + i2].nFileSize; strcpy(b[i1 + i2].cFileName, arr[mid + i2].cFileName); i2++; } for (i = 0; i < (i1 + i2); i++) { arr[left + i].nFileSize = b[i].nFileSize; strcpy(arr[left + i].cFileName, b[i].cFileName); } free(b); } void mergeSort(FIND_DATA* arr, ULONGLONG left, ULONGLONG right) { ULONGLONG mid ; if (left+1 >= right) return; mid = (left + right) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid, right); merge(arr, left, mid, right); } int FindFiles(LPCSTR directory, FIND_DATA* filesArray) { char name[250]; WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA(directory, &FindFileData); int i=0; FindNextFileA(hFind, &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { while (FindNextFileA(hFind, &FindFileData) != 0) { filesArray[i].nFileSize = FindFileData.nFileSizeLow; strcpy(filesArray[i].cFileName, FindFileData.cFileName); i++; } FindClose(hFind); } return i; } int check(LPCSTR directory) { WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA(directory, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { if (GetLastError() == 2) { FindClose(hFind); return 2; } if (GetLastError() == 3) { FindClose(hFind); return 3; } } else { FindClose(hFind); return 1; } } void qSort(FIND_DATA* arr, ULONGLONG left, ULONGLONG right) { FIND_DATA pivot; ULONGLONG l = left; ULONGLONG r = right; pivot.nFileSize = arr[left].nFileSize; strcpy(pivot.cFileName, arr[left].cFileName); while (left < right) { while ((arr[right].nFileSize >= pivot.nFileSize) && (left < right)) right--; if (left != right) { arr[left].nFileSize = arr[right].nFileSize; strcpy(arr[left].cFileName, arr[right].cFileName); left++; } while ((arr[left].nFileSize <= pivot.nFileSize) && (left < right)) left++; if (left != right) { arr[right].nFileSize = arr[left].nFileSize; strcpy(arr[right].cFileName, arr[left].cFileName); right--; } } arr[left].nFileSize = pivot.nFileSize; strcpy(arr[left].cFileName,pivot.cFileName); pivot.nFileSize = left; left = l; right = r; if (left < pivot.nFileSize) qSort(arr, left, pivot.nFileSize - 1); if (right > pivot.nFileSize) qSort(arr, pivot.nFileSize + 1, right); }<file_sep>#include <stdio.h> #include "HUser_Matrix.h" int choice(CMatrix* matrix1) { int choice; do { printf("Choose: 0) for kill the programm 1) matrix+const; 2) matrix * conts; 3) matrix + matrix; 4) matrix * matrix; \n"); scanf("%d", &choice); //functions if (choice == 1) { int user_const; printf("Input a number "); scanf("%d", &user_const); CMatrix* ans = add_const(matrix1, user_const); mprint(ans); free_matrix(&ans); } if (choice == 2) { int user_const; printf("Input a number "); scanf("%d", &user_const); CMatrix* ans = multi_const(matrix1, user_const); mprint(ans); free_matrix(&ans); } if (choice == 3) { //second matrix int size2; CMatrix* matrix2; printf("Input a size of the second square matrix: "); scanf("%d", &size2); allocate_matrix(&matrix2, size2); allocate_matrix(&matrix2, size2); fill_matrix(matrix2); printf("\n The First matrix: \n"); mprint(matrix1); printf("The Second matrix:\n "); mprint(matrix2); CMatrix* ans = add_matrix(matrix1, matrix2); if (ans == NULL) { continue; } printf("Answer: "); mprint(ans); free_matrix(&ans); free_matrix(&matrix2); } if (choice == 4) { //second matrix int size2; CMatrix* matrix2; printf("Input a size of the second square matrix: "); scanf("%d", &size2); allocate_matrix(&matrix2, size2); fill_matrix(matrix2); printf("\n The First matrix: \n"); mprint(matrix1); printf("The Second matrix:\n "); mprint(matrix2); CMatrix* ans = multi_matrix(matrix1, matrix2); if (ans == NULL) { continue; } printf("\n Answer: "); mprint(ans); free_matrix(&ans); free_matrix(&matrix2); } if (choice == 0) { return 0; } } while (choice != 0); } int main() { CMatrix* matrix1, * matrix2; int size1; //input data + memory printf("Input a size of the first square matrix: "); scanf("%d", &size1); //first matrix // Можно было сделать main в 1 строку, но как-то не красиво allocate_matrix(&matrix1, size1); fill_matrix(matrix1); mprint(matrix1); choice(matrix1); free_matrix(&matrix1); }<file_sep>#define STRLEN 10 #include "action.h" #include <iostream> #include <fstream> #include "action.h" using namespace std; void My_scan(teamarray& book) { string filepath; cin >> filepath; ifstream file(filepath); file >> book.length; book.teams = new team[book.length]; for (size_t i = 0; i < book.length; i++) { file >> book.teams[i]; } } void output() { teamarray book; book.teams = NULL; book.length = 0; My_scan(book); size_t best_id = 0; if (book.teams != NULL) { for (size_t i = 1; i < book.length; i++) { if (book.teams[best_id].Points < book.teams[i].Points) best_id = i; } cout << book.teams[best_id]; } } using namespace std; <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { char a; printf("Select game 1 or 2:\n "); do { scanf("%c", &a); } while ((a != '1') && (a != '2')); if (a == '1') { int a, n, i = 0; srand((unsigned int)time(NULL)); n = rand() % 1000; printf("Enter a number from 0 to 1000...\n"); while (1) { do { scanf("%d", &a); } while (a > 1000 || a < 0); if (a < n) { printf("Bigger\n"); i++; } else if (a > n) { printf("Smaller\n"); i++; } else { printf("WOW, you guessed it!\n Number of attempts: %d", i + 1); break; } } return 0; } else { int a1 = 1, a2 = 1000, d = 0, c = d, i1 = 0; char b = ' '; printf("Guess a number from 1 to 1000\n"); while (b != '=') { i1++; c = (a1 + a2) / 2; if (c == d) { c = c - 1; } printf("%d", c); printf("?\n"); do { scanf("%c", &b); } while ((b != '<') && (b != '>') && (b != '=')); if (b == '<') { a2 = c; } else if (b == '>') { a1 = c; } else { printf("WOW, I guessed it!\n Number of attempts: %d", i1); } d = c; } } return 0; }<file_sep>#include "person.h" #include <iostream> using namespace std; int main() {//C:\Users\Ivan\Desktop\Prctice 2.2_00\Prctice 2.2_00\Persons.txt string path = getPath(); persons_list ps(path); cout << ps; ps.surname_sort(); menu(ps); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> void main() { int mode_game; printf("Welcome to the 'Guess the number game'!\n"); do { printf("Please select mode:\n 1: you guess the number of the computer\n 2: the computer guesses your number\n"); scanf("%d", &mode_game); } while ((mode_game > 2) || (mode_game < 1)); if (mode_game == 1) { int random_num; int k = 0; int player_num = 0; printf("I made a number, guess it!\n"); srand(time(NULL)); random_num = 1 + rand() % (1000 - 1 + 1); while (player_num != random_num) { printf("Enter your number "); scanf("%d", &player_num); k++; if (player_num > random_num) { printf("The hidden number is less\n"); } else if (player_num < random_num) { printf("The hidden number is greater\n"); } } k++; printf("Congratulations! You guessed the number\nThe number of your attempts: %d", k); } else if (mode_game == 2) { int min_num = 1, max_num = 1000; int k = 0; int random_num2, player_num; char symbol; do { printf("During the game, enter\n '>' if your number is greater\n '<' if your number is less\n '=' if the computer guessed the number\n"); printf("Enter your number from 1 to 1000 "); scanf("%d", &player_num); } while ((player_num > 1000) || (player_num < 1)); srand(time(NULL)); random_num2 = min_num + rand() % (max_num - min_num + 1); k++; printf("%d? ", random_num2); scanf(" %c", &symbol); while (true) { if (symbol == '>') min_num = random_num2 + 1; else if (symbol == '<') max_num = random_num2 - 1; else if (symbol == '=') break; srand(time(NULL)); random_num2 = min_num + rand() % (max_num - min_num + 1); k++; printf("%d? ", random_num2); scanf(" %c", &symbol); } printf("The computer guessed the number!\nThe number of attempts %d ", k); } } <file_sep>#ifndef _PERSON_H #define _PERSON_H #include <string> using namespace std; enum gender { male, female }; struct address { int postal_code; string Country; string Region; string City; string Area; string Street; int House; int Apart; }; struct date { int day; int mounth; int year; }; class Person { public: Person(); string getName() const; string getSurname() const; friend ostream& operator<<(ostream& out, const Person& p); Person(const string& surname, const string& name, const string& middle_name, gender gender, const string& nation, const date& birth_date, float height, float weight, long long phone_number, const address& address_); private: string Surname; string Name; string Middle_name; gender Gender; string Nation; date date_; float Height; float Weight; long long phone_number; address address_; }; class PersonsList { public: PersonsList(const string& path); ~PersonsList(); void surname_sort(); int getCount() const; Person* getPersons() const; friend ostream& operator<<(ostream& out, const PersonsList& pl); private: int person_count(const string& path) const; Person* persons; int count; }; string getPath(); void menu(const PersonsList& ps); #endif // !_PERSON_H <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main() { float Qdsp, Qdvp, Q, h, w, d, t_back, t_covers, t_sides, t_door, t_shelves, m_back, m_sides, m_covers, m_door, k_shelves, count, m_shelves, res; float o1 = 1.8, o2 = 2.2, o3 = 0.8, o4 = 1.2, o5 = 0.5, o6 = 0.9; Qdsp = 800; Qdvp = 750; Q = 640; float eps = 0.00000001; printf("Input h "); scanf("%f", &h); if (((fabs(h - o1) > eps) && (h < o1 )) || ((fabs(h - o2) > eps) && (h > o2 ))) { printf("Incorrect data, 1.8 <= h <= 2.2 "); return 0; } printf("Input w "); scanf("%f", &w); if (((fabs(w - o3) > eps) && (w < o3)) || ((fabs(w - o4) > eps) && (w > 04))) { printf("Incorrect data, 0.8 <= w <= 1.2 "); return 0; } printf("Input d "); scanf("%f", &d); if (((fabs(d - o5) > eps) && (d < o5)) || ((fabs(d - o6) > eps) && (d > o6))) { printf("Incorrect data, 0.5 <= d <= 0.9 "); return 0; } t_back = 0.005; t_sides = 0.015; t_covers = 0.015; t_door = 0.01; t_shelves = 0.015; m_back = Qdvp * (t_back * h * w); m_sides = 2 * (Qdsp * (t_sides * h * d)); m_covers = 2 * (Qdsp * (t_covers * (w-0.03) * d)); m_door = Q * (t_door * h * w); k_shelves = h / (0.415) - 1.03; count = (int)k_shelves; m_shelves = count * (Qdsp * (t_shelves * (w-0.03) * d)); res = m_back + m_covers + m_door + m_shelves + m_sides; printf ("mass = %f ", res); }<file_sep>#ifndef _TRIANGLE_H #define _TRIANGLE_H typedef struct { float x, y; }Coord; typedef struct { Coord vertices[3]; }Triangle; char* read_string(FILE* stream); char* getPath(); Triangle* ReadTriangleFile(char* file_path, int* number_of_triangles); Triangle ReadTriangleEntity(FILE* file); float CountSquare(Triangle triangle); float CountPerimeter(Triangle triangle); float* Sides(Triangle triangle); float* Height(Triangle triangle); void PrintTriangleType(Triangle triangle); #endif _TRIANGLE_H<file_sep>#ifndef FILM_H #define FILM_H typedef struct Producer { char* Name; char* Surname; } Producer; typedef struct Film { char* film_name; Producer creator; char* country; int year; int budget; int fees; } Film; char* read_string(FILE* stream); char* getInput(char* message); Producer getProducerFromString(char* str); Film ReadFilmEntity(FILE* file); Film* ReadFileWithFilms(char* file_path, int* number_of_films); int compareProducers(const Producer* x, const Producer* y); Film* getFilmsByProducer(Film* all_films, int count_all_films, Producer creator, int* needed_count); void PrintFilm(Film film); #endif <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Film.h" char* read_string(FILE* stream) { int buffer_size = 8; int buffer_size_divizer = 1; int offset = 0; int additional_length; char* buffer = (char*)malloc(sizeof(char) * buffer_size); if (buffer == NULL) { return NULL; } buffer[0] = '\0'; // read string while not face with '\n' while (1) { // read string to buffer with current offset if (fgets(buffer + offset, buffer_size / buffer_size_divizer, stream) == NULL) { free(buffer); // free allocated memory return NULL; } else { additional_length = strlen(buffer + offset); if (buffer[offset + additional_length - 1] != '\n') { // increase buffer_size by 2 times buffer_size *= 2; // realloc new memory buffer = (char*)realloc(buffer, sizeof(char) * buffer_size); // update offset to number of read elements offset += additional_length; buffer_size_divizer = 2; } else { buffer[offset + additional_length - 1] = '\0'; break; } } } return buffer; } char* getInput(char* message) { char* input; while (1) { printf(message); input = read_string(stdin); if (input != NULL) break; } return input; } Producer getProducerFromString(char* str) { char* current_part; Producer p; current_part = strtok(str, " "); if (current_part == NULL) { printf("Incorrect format of producer name and surname, please type info use pattern: 'Name Surname' "); } char* name = current_part; char* surname = strtok(NULL, " "); p.Name = name; p.Surname = surname; return p; } Film ReadFilmEntity(FILE* file) { char* film_name = read_string(file); // create Producer from string char* producer = read_string(file); Producer p = getProducerFromString(producer); char* country = read_string(file); int film_year = atoi(read_string(file)); int film_budget = atoi(read_string(file)); int film_fees = atoi(read_string(file)); Film new_film = { film_name, p, country, film_year, film_budget, film_fees }; return new_film; } Film* ReadFileWithFilms(char* file_path, int* number_of_films) { FILE* file = fopen(file_path, "r"); if (file == NULL) { printf("\nRead file error.\n"); } Film* films = (Film*)malloc(sizeof(Film)); *number_of_films = 1; // we assume that the file contains information about at least one film while (1) { Film current_film = ReadFilmEntity(file); films[*number_of_films - 1] = current_film; if (read_string(file) == NULL) { break; } else { films = (Film*)realloc(films, (*number_of_films + 1) * sizeof(Film)); *number_of_films += 1; } } fclose(file); return films; } int compareProducers(const Producer* x, const Producer* y) { if ((strcmp(x->Name, y->Name) == 0) && (strcmp(x->Surname, y->Surname) == 0)) { return 1; } return 0; } Film* getFilmsByProducer(Film* all_films, int count_all_films, Producer creator, int* needed_count) { printf("Search films with producer : %s %s ...\n\n", creator.Name, creator.Surname); Film* needed_films = (Film*)malloc(sizeof(Film)); int count = 0; for (int i = 0; i < count_all_films; ++i) { if (compareProducers(&all_films[i].creator, &creator)) { needed_films[count] = all_films[i]; ++count; needed_films = (Film*)realloc(needed_films, (count + 1) * sizeof(Film)); } } *needed_count = count; return needed_films; } void PrintFilm(Film film) { printf("Film name: %s\n", film.film_name); printf("Producer Name - Surname: %s %s\n", film.creator.Name, film.creator.Surname); printf("Country: %s\n", film.country); printf("Year: %d\n", film.year); printf("Budget: %d\n", film.budget); printf("Fees: %d\n\n", film.fees); } <file_sep>#include "fileProcessing.h" // Default constructors Univ_database_t::Univ_database_t() { count = -1; univs = nullptr; } University_t::University_t() { name = ""; n_spec = 0; specs = nullptr; } Spec_t::Spec_t() { name = ""; n_form = 0; forms = nullptr; examScores = nullptr; costs = nullptr; } Univ_database_t::Univ_database_t(const std::string& fname) { int i = 0; std::string line; count = try_to_open_file(fname); std::ifstream file(fname); univs = new University_t[count]; while (i < count) { getline(file, line, ';'); univs[i].SetName(line); getline(file, line, ';'); univs[i].SetNumSpecs( atoi(line.c_str()) ); univs[i].SetSpecs(univs[i].GetNum_spec()); for (int j = 0; j < univs[i].GetNum_spec(); j++) { getline(file, line, ';'); univs[i].GetSpec(j).SetName(line); getline(file, line, ';'); univs[i].GetSpec(j).SetNumForms( atoi(line.c_str()) ); int num_forms = univs[i].GetSpec(j).GetNum_form(); univs[i].GetSpec(j).Set_Forms(num_forms); univs[i].GetSpec(j).Set_Costs(num_forms); univs[i].GetSpec(j).Set_ExamScores(num_forms); for (int z = 0; z < num_forms; z++) { std::string type_form; getline(file, line, ';'); type_form = line; if (type_form == "дневная") { univs[i].GetSpec(j).Set_Form(z, DNEV); getline(file, line, ';'); univs[i].GetSpec(j).Set_ExamScore(z, atoi(line.c_str())); getline(file, line, ';'); univs[i].GetSpec(j).Set_Cost(z, atoi(line.c_str())); } if (type_form == "вечерняя") { univs[i].GetSpec(j).Set_Form(z, VECHER); getline(file, line, ';'); univs[i].GetSpec(j).Set_ExamScore(z, atoi(line.c_str())); getline(file, line, ';'); univs[i].GetSpec(j).Set_Cost(z, atoi(line.c_str())); } if (type_form == "заочная") { univs[i].GetSpec(j).Set_Form(z, ZAOCH); getline(file, line, ';'); univs[i].GetSpec(j).Set_ExamScore(z, atoi(line.c_str())); getline(file, line, ';'); univs[i].GetSpec(j).Set_Cost(z, atoi(line.c_str())); } } } i++; file.get(); } file.close(); } Univ_database_t::Univ_database_t(int c) { count = c; univs = new University_t[count]; } // Copy constructors Spec_t::Spec_t(const Spec_t& s) { name = s.name; n_form = s.n_form; forms = new EducationalForm[n_form]; costs = new int[n_form]; examScores = new int[n_form]; for (int i = 0; i < n_form; i++) { forms[i] = s.forms[i]; costs[i] = s.costs[i]; examScores[i] = s.examScores[i]; } } University_t::University_t(const University_t& u) { name = u.name; n_spec = u.n_spec; specs = new Spec_t[n_spec]; for (int i = 0; i < n_spec; i++) { specs[i] = u.specs[i]; } } Univ_database_t::Univ_database_t(const Univ_database_t& ud) { count = ud.count; univs = new University_t[count]; for (int i = 0; i < count; i++) { univs[i] = ud.univs[i]; } } // Destuctors Univ_database_t::~Univ_database_t() { delete[]univs; } University_t::~University_t() { delete[]specs; } Spec_t::~Spec_t() { delete[]forms; delete[]examScores; delete[]costs; } // Overloaded operators University_t& Univ_database_t::operator[] (const int ind) { return univs[ind]; } std::ostream& operator<<(std::ostream& out, const University_t& un) { std::cout << "Информация о ВУЗе " << un.GetName() << ":\n"; std::cout << "ВУЗ " << un.GetName() << " имеет " << un.GetNum_spec() << " специальностей:\n"; for (int i = 0; i < un.GetNum_spec(); i++) { std::cout << " " << un.GetSpec(i).GetName() << std::endl; } return out; } std::ostream& operator<<(std::ostream& out, const Spec_t& s) { std::cout << "Название специальности: " << s.GetName() << ":\n"; std::cout << "Количество форм обучения: " << s.GetNum_form() << "\n"; for (int i = 0; i < s.GetNum_form(); i++) { std::string name_form; switch (s.Get_Form(i)) { case 0: name_form = "Дневная"; case 1: name_form = "Вечерняя"; case 2: name_form = "Заочная"; } std::cout << " Форма обучения: " << name_form << std::endl; std::cout << " Стоимость: " << s.Get_Cost(i) << std::endl; std::cout << " Проходные баллы: " << s.Get_ExamScore(i) << std::endl; } return out; } University_t& University_t::operator=(const University_t& u) { if (this != &u) { if (specs) delete[] specs; name = u.name; n_spec = u.n_spec; specs = new Spec_t[n_spec]; for (int i = 0; i < n_spec; i++) { specs[i] = u.specs[i]; } } return *this; } Spec_t& Spec_t::operator=(const Spec_t& s) { if (this != &s) { if (forms) delete[] forms; if (costs) delete[] costs; if (examScores) delete[] examScores; name = s.name; n_form = s.n_form; forms = new EducationalForm[n_form]; costs = new int[n_form]; examScores = new int[n_form]; for (int i = 0; i < n_form; i++) { forms[i] = s.forms[i]; costs[i] = s.costs[i]; examScores[i] = s.examScores[i]; } } return *this; } // Accessors, mutators std::string University_t::GetName() const { return name; } int University_t::GetNum_spec() const { return n_spec; } Spec_t& University_t::GetSpec(int ind) const { return specs[ind]; } std::string Spec_t::GetName() const { return name; } int Spec_t::GetNum_form() const { return n_form; } EducationalForm Spec_t::Get_Form(int ind) const { return forms[ind]; } int Spec_t::Get_ExamScore(int ind) const { return examScores[ind]; } int Spec_t::Get_Cost(int ind) const { return costs[ind]; } void University_t::SetName(const std::string name_u) { name = name_u; } void University_t::SetNumSpecs(const int n) { n_spec = n; } void University_t::SetSpecs(const int num) { specs = new Spec_t[num]; } void Spec_t::SetName(const std::string name_s) { name = name_s; } void Spec_t::SetNumForms(const int n) { n_form = n; } void Spec_t::Set_Form(const int ind, EducationalForm form) { forms[ind] = form; } void Spec_t::Set_Cost(const int ind, int cost) { costs[ind] = cost; } void Spec_t::Set_ExamScore(const int ind, int score) { examScores[ind] = score; } void Spec_t::Set_Forms(const int num) { forms = new EducationalForm[num]; } void Spec_t::Set_Costs(const int num) { costs = new int[num]; } void Spec_t::Set_ExamScores(const int num) { examScores = new int[num]; } // Methods int Univ_database_t::find_num_univ(const std::string& fname) const { std::string line; int c = 0; std::ifstream file(fname); if (file.fail()) throw - 1; while (getline(file, line)) { c++; } file.close(); return c; } int Univ_database_t::try_to_open_file(const std::string& fname) { int c = -1; while (c == -1) { try { getline(std::cin, const_cast<std::string&>(fname)); c = find_num_univ(fname); } catch (...) { std::cout << "Такого файла нет" << std::endl; } } return c; } int Univ_database_t::SearchVUZ(const std::string& name, University_t& u) const { for (int i = 0; i < count; i++) { if (univs[i].GetName() == name) { u = univs[i]; return 1; } } return -1; } float University_t::ComputeAverageScore() const { float sum_examRes = 0, count = 0; for (int i = 0; i < n_spec; i++) { for (int j = 0; j < specs[i].GetNum_form(); j++) { sum_examRes += specs[i].Get_ExamScore(j); count++; } } return sum_examRes / count; } float University_t::ComputeAverageCost() const { float sum_costs = 0, count = 0; for (int i = 0; i < n_spec; i++) { for (int j = 0; j < specs[i].GetNum_form(); j++) { sum_costs += specs[i].Get_ExamScore(j); count++; } } return sum_costs / count; } void University_t::SearchMinScoreSpeciality(std::string& spec_name, int& score, std::string& form) { int min = 1000; EducationalForm edForm; std::string name_form, name_spec; for (int i = 0; i < n_spec; i++) { for (int j = 0; j < specs[i].GetNum_form(); j++) { if (specs[i].Get_ExamScore(j) < min) { min = specs[i].Get_ExamScore(j); edForm = specs[i].Get_Form(j); name_spec = specs[i].GetName(); } } } switch (edForm) { case 0: name_form = "Дневная"; case 1: name_form = "Вечерняя"; case 2: name_form = "Заочная"; } score = min; form = name_form; spec_name = name_spec; } int Univ_database_t::SearchSpecialties(const std::string& name, Spec_t*& specs, std::string*& names_univ) const { int c_spec = 0; for (int i = 0; i < count; i++) { for (int j = 0; j < univs[i].GetNum_spec(); j++) { if (univs[i].GetSpec(j).GetName() == name) c_spec++; } } specs = new Spec_t[c_spec]; names_univ = new std::string[c_spec]; int k = 0; for (int i = 0; i < count; i++) { for (int j = 0; j < univs[i].GetNum_spec(); j++) { if (univs[i].GetSpec(j).GetName() == name) { specs[k] = univs[i].GetSpec(j); names_univ[k] = univs[i].GetName(); k++; } } } return c_spec; }<file_sep>#ifndef _GLOBALFUNCTIONS_H_ #define _GLOBALFUNCTIONS_H_ #include <iostream> #include <fstream> using namespace std; int PathError(); string input_path(); void user(); template<typename Type> void dump_data_base(const NewContainer<Type>& base, const string& filename); #endif <file_sep>cmake_minimum_required(VERSION 3.23) project(Practice2 C) set(CMAKE_C_STANDARD 17) add_executable(Practice2 main.c) <file_sep>#ifndef _SCHOOL_H #define _SCHOOL_H #include <string.h> using namespace std; struct TStudent { string FIO; int Class; string Gender; string Date; string Address; friend ostream& operator<<(ostream& out, const TStudent& student); }; struct TSchool { TStudent* student; int n; int counting(const string& filename); TSchool(const string& filename); friend ostream& operator<<(ostream& out, const TSchool& school); void sorting(); ~TSchool(); }; #endif<file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct{ float** arr_2d; //Declare the structure of square matrices int size; }TDmatrix; //Declare 3 arrays of structures void allocate_matrix(TDmatrix** struct_p, int size); //Creating a square matrix void free_matrix(TDmatrix** struct_p); //Releasing the memory void fill_matrix(TDmatrix*struct_p); //filling square matrix void print_matrix(TDmatrix*struct_p); //Output the contents of a square matrix TDmatrix* add_matrix(TDmatrix* matr1, TDmatrix* matr2); //Matrix addition operation: feed two pointers //to square matrices and a pointer to the resultant matrix //(all from an array of structures) TDmatrix* multi_const(TDmatrix* matr1, float c); //Matrix multiplication operation by constant: //give a pointer to the resulting matrix res and constant. TDmatrix* add_const(TDmatrix* matr2, float c); //The operation of adding a constant to a matrix : //feed a pointer to the resultant matrix resand a constant. TDmatrix* multi_matrix(TDmatrix* matr1, TDmatrix* matr2); //Matrix multiplication operation: //feed 3 pointers to each of the matrices in the structure array. #endif <file_sep>#include <stdio.h> #include <time.h> #include <math.h> int main() { int a[5] = { 0 }, b[5] = { 0 }, n = 0, i = 0, tries = 0, k, l, f = 1, n1, n2, bull = 0, cow = 0, tmp = 0; time_t t; srand((unsigned)time(&t)); printf("Enter the length of the number (from 2 to 5): "); do { scanf_s("%d", &n); if ((n > 5) || (n < 2)) { printf("Invalid number entered. Try again\n "); } } while ((n > 5) || (n < 2)); for (i = 0; i < n; i++) { do { k = (rand() % 9) + 1; //случайное число if ((a[0] != k) && (a[1] != k) && (a[2] != k) && (a[3] != k) && (a[4] != k)) { //проверка, чтобы все элементы в массиве не были равны k a[i] = k; } } while (a[i] == 0); } for (i = 0; i < n; i++) { //проверка степени десятки, чтобы ее длина совпадала с загаданным числом f *= 10; } do { printf("Enter your guess: "); do { scanf_s("%d", &l); if ((l > f) && (l < 10 * f - 1)) { printf("Invalid number entered. Try again\n "); } } while ((l < f) && (l > 10 * f - 1)); //ввод числа пока оно не будет в рамках допустимого for (i = n - 1; i >= 0; i--) { b[i] = l % 10; //каждая цифра, введенная пользователем, должна лежать в своей ячейке массива l /= 10; } tries++; for (n1 = 0; n1 < n; n1++) { //проверяем есть ли быки или коровы for (n2 = 0; n2 < n; n2++) { if ((n1 == n2) && (a[n1] == b[n2])) { bull++; } else if ((n1 != n2) && (a[n1] == b[n2])) { cow++; } } } printf("bulls: %d\n", bull); printf("cows: %d\n", cow); if (bull == n) { printf("Congrats! Total attemts count: %d", tries); return 0; } cow = 0; bull = 0; } while (1); return 0; } <file_sep>#include <iostream> #include <string> #include <fstream> #include <sstream> #include "products.h" #include "container.h" #include "database.h" #include "datentime.h" using namespace std; // ========== TDataLine ========== // TDataLine::TDataLine(const string _code, const string _name, const double _cost, const int _count) { product.Set(_code, _name, _cost); count = _count; } void TDataLine::Set(const string _code, const string _name, const double _cost, const int _count) { product.Set(_code, _name, _cost); count = _count; } void TDataLine::Print() { product.Print(); cout << count << " шт." << endl; } bool TDataLine::operator==(const TDataLine& dl) const { if (product.GetCode() == dl.product.GetCode()) return true; return false; } bool TDataLine::operator!=(const TDataLine& dl) const { return !((*this) == dl); } const TDataLine& TDataLine::operator=(const TDataLine& dl) { if (this != &dl) { product = dl.product; count = dl.count; } return (*this); } // ========== TDataBase ========== // TDataBase::TDataBase(const string& filename) { ScanFile(filename); } void TDataBase::ScanFile(const string& filename) { ifstream file(filename); string line; if (file.is_open()) { products.ChangeMemorry(1000, 100); while (getline(file, line)) { istringstream iss(line); string code; string name; double cost; int count; if (iss >> code >> name >> cost >> count) { TDataLine dl(code, name, cost, count); products.Add(dl); } else { file.close(); string exp = "Ошибка чтения данных из строки: " + line; throw std::out_of_range(exp); } } products.Compress(); file.close(); } else { string exp = "Невозможно открыть файл: " + filename; throw std::out_of_range(exp); } } void TDataBase::ArchiveData(const string& filename) { string tmp_name = filename; tmp_name.erase(tmp_name.length() - 4, tmp_name.length()); TDate date; TTime time; date.setCurrentDay(); time.setCurrentTime(); string new_filename = tmp_name + "_archive_" + time.StringTime() + "_" + date.StringDate() + ".txt"; ofstream file(new_filename); if (file.is_open()) { for (int i = 0; i < products.Count(); i++) { file << products[i].GetCode() << " " << products[i].GetName() << " " << products[i].GetCost() << " " << products[i].GetProductCount() << "\n"; } file.close(); } else { string exp = "fdtbARCHIVEERROR"; throw std::out_of_range(exp); } } void TDataBase::UpdateData(const string& filename) { ofstream file(filename); if (file.is_open()) { for (int i = 0; i < products.Count(); i++) { file << products[i].GetCode() << " " << products[i].GetName() << " " << products[i].GetCost() << " " << products[i].GetProductCount() << "\n"; } file.close(); } else { string exp = "fdtbUPDATEERROR"; throw std::out_of_range(exp); } } int TDataBase::Check(const string& _code) { // -1 - Продукт не найден for (int i = 0; i < products.Count(); i++) if (products[i].GetCode() == _code) return i; return -1; } TProduct* TDataBase::GetProduct(int index) { if (index < 0 || index > products.Count()) { string exp = "dtbINDOUTOFRANGE"; throw std::out_of_range(exp); } return products[index].GetProduct(); } int& TDataBase::GetProductCount(const string& _code) { int ind = Check(_code); if (ind < 0) { string exp = "dtbCOUТNONEXISTPROD"; throw std::out_of_range(exp); } return products[ind].GetProductCount(); }<file_sep>#include <stdio.h> #include "matrix.h" int main() { TMatrix* matrix_dynamic, * m1, * m2, * res; allocate_matrix(&matrix_dynamic, 2); fill_matrix(matrix_dynamic); print_matrix(matrix_dynamic); free_matrix(&matrix_dynamic); allocate_matrix(&m1, 2); allocate_matrix(&m2, 2); fill_matrix(m1); fill_matrix(m2); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); res = add_const(m1, 2); print_matrix(res); free_matrix(&res); res = add_const(m2, 2); print_matrix(res); free_matrix(&res); res = multi_const(m1, 2); print_matrix(res); free_matrix(&res); res = multi_const(m2, 2); print_matrix(res); free_matrix(&res); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; } <file_sep>#ifndef _DISPLAY_H #define _DISPLAY_H #include "polynom.h" void choose(); void answer(int& ans); void retry(int& ans); void print_p(TPolynom*& p, const int n); void index(int* ind, const int n); void print_2p(TPolynom& p1, TPolynom& p2, int* ind); #endif // !_DISPLAY_H<file_sep>#include <iostream> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <windows.h> #include "Header.h" using namespace std; int TSchool::counting(const string& filename) { ifstream file(filename); int n = 0; if (file.is_open()) { string line; while (getline(file, line)) { n++; } } else { cout << "Не удалось открыть файл" << endl; } file.close(); return n; } TSchool::TSchool(const string& filename) { this->n = counting(filename); this->student = new TStudent[n]; ifstream file(filename); int i, j = 0; string line, str; if (file.is_open()) { while (getline(file, line)) { istringstream iss(line); i = 0; while (getline(iss, str, ';')) { switch (i) { case 0: student[j].FIO = str; break; case 1: student[j].Class = stoi(str); break; case 2: student[j].Gender = str; break; case 3: student[j].Date = str; break; case 4: student[j].Address = str; break; } i++; } j++; } } else { cout << "Не удалось открыть файл" << endl; } file.close(); } ostream& operator<<(ostream& out, const TStudent& student) { out << student.FIO << " " << student.Class << " " << student.Gender << " " << student.Date << " " << student.Address << endl; return out; } ostream& operator<<(ostream& out, const TSchool& school) { cout << "ФИО" << " " << "Класс" << " " << "Пол" << " " << "Дата рождения" << " " << "Домашний адрес\n" << endl; for (int i = 0; i < school.n; i++) { out << school.student[i]; } return out; } void TSchool::sorting() { int i = 0, j, k = 1; TStudent tmp; for (; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (student[i].Class > student[j].Class) { tmp = student[i]; student[i] = student[j]; student[j] = tmp; } } } i = 0; while (i < n) { while (student[i].Class == k) { j = i + 1; while (student[j].Class == k) { if (student[i].FIO > student[j].FIO) { tmp = student[i]; student[i] = student[j]; student[j] = tmp; } j++; } i++; } k++; } } TSchool::~TSchool() { delete[] this->student; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <fstream> #include <vector> #include "films.h" using namespace std; std::string getInput(const std::string& message) { std::string input; std::cout << message; std::getline(std::cin, input); return input; } Producer getProducerFromFile(std::ifstream& file) { std::string name; std::string surname; getline(file, name, ' '); getline(file, surname); Producer p = { name, surname }; return p; } Producer getProducerFromString(std::string& producer_str) { std::string name; std::string surname; int ptr = producer_str.find(' '); if (ptr == -1) { std::cout << "Uncorrect format of producer string!"; } else { name = producer_str.substr(0, ptr); surname = producer_str.substr(ptr + 1); } Producer p = { name, surname }; return p; } Film ReadFilmEntity(std::ifstream& file) { std::string film_name; std::getline(file, film_name); // create Producer from string std::string producer; //getline(file, producer); Producer p = getProducerFromFile(file); std::string country; std::getline(file, country); std::string film_year_s; std::getline(file, film_year_s); int film_year = stoi(film_year_s); std::string film_budget_s; std::getline(file, film_budget_s); int film_budget = stoi(film_budget_s); std::string film_fees_s; std::getline(file, film_fees_s); int film_fees = stoi(film_fees_s); Film new_film = { film_name, p, country, film_year, film_budget, film_fees }; return new_film; } std::vector<Film> ReadFileWithFilms(const std::string& file_path) { std::ifstream file; file.open(file_path); if (!file.is_open()) { printf("\nRead file error.\n"); } std::vector<Film> films; // we assume that the file contains information about at least one film std::string tmp; while (!file.eof()) { Film current_film = ReadFilmEntity(file); films.push_back(current_film); std::getline(file, tmp); } file.close(); return films; } std::vector<Film> getFilmsByProducer(const std::vector<Film>& all_films, const Producer& creator) { std::cout << "Search films with producer : " << creator << "\n"; std::vector<Film> needed_films; for (int i = 0; i < all_films.size(); ++i) { Producer creat = all_films[i].getCreator(); if (creat == creator) { needed_films.push_back(all_films[i]); } } return needed_films; } std::istream& operator>>(std::istream& input_stream, Producer& p) { input_stream >> p.Name >> p.Surname; return input_stream; } std::ostream& operator<<(std::ostream& output_stream, const Producer& p) { output_stream << p.Name << " " << p.Surname; return output_stream; } bool Producer::operator==(const Producer& p) const { if (Name == p.Name && Surname == p.Surname) { return true; } return false; } std::istream& operator>>(std::istream& input_stream, Film& film) { input_stream >> film.film_name; input_stream >> film.creator; input_stream >> film.country; input_stream >> film.year >> film.budget >> film.fees; return input_stream; } std::ostream& operator<<(std::ostream& output_stream, const Film& film) { output_stream << "Film name: " << film.film_name << '\n'; output_stream << "Producer Name - Surname: " << film.creator << '\n'; output_stream << "Country: " << film.country << '\n'; output_stream << "Year: " << film.year << '\n'; output_stream << "Budget: " << film.budget << '\n'; output_stream << "Fees: " << film.fees << '\n'; return output_stream; } Producer::Producer(const std::string& name, const std::string& surname) { this->Name = name; this->Surname = surname; } Film::Film(const std::string& film_name, const Producer& creator, const std::string& country, int year, int budget, int fees) { this->film_name = film_name; this->creator = creator; this->country = country; this->year = year; this->budget = budget; this->fees = fees; } Producer::Producer() { Name = ""; Surname = ""; } Producer Film::getCreator() const { return creator; } const Producer& Producer:: operator = (const Producer& p) { Name = p.Name; Surname = p.Surname; return *this; }<file_sep>#include <iostream> #include <string> #include "Header.h" using namespace std; int main(){ setlocale(LC_ALL, "Russian"); string filename; cin >> filename; TSchool school(filename); cout << school; school.sorting(); cout << school; return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { short gameMode, userNum, randomNumber, a = 1, b = 1000; int attemptsNumber = 0; char userSymbol; do { printf("Choose a game mode...\n 1) You guess the number the computer wants\n 2) The computer guesses the number you intend\n"); if (scanf("%hd", &gameMode) != 1) { printf("Enter only numbers..."); return 1; } } while ((gameMode > 2) || (gameMode < 1)); switch (gameMode) { case 1: //Computer guesses number srand((unsigned int)time(NULL)); randomNumber = a + rand() % (b - a + 1); while (1){ do { printf("\nEnter your intended number in range from 1 to 1000...\n"); if (scanf("%hd", &userNum) != 1) { printf("Enter only numbers..."); return 1; } } while ((userNum < 1) || (userNum > 1000)); attemptsNumber++; if (userNum < randomNumber) printf("Your number < than the hidden number\n"); if (userNum > randomNumber) printf("Your num > than the hidden number\n"); if (userNum == randomNumber) { printf("You win! Hidden number is: %hd\n", randomNumber); printf("Attempts number: %d", attemptsNumber); break; } } break; case 2: //User guesses number printf("\nGuess the number from 1 to 1000\n"); printf("Answer, your mysterious number is > or < or = the number claimed by computer.\n"); while (1){ srand((unsigned int)time(NULL)); randomNumber = a + rand() % (b - a + 1); printf("Your mysterious number is %hd?\n", randomNumber); do { scanf("%c", &userSymbol); } while ((userSymbol != '=') && (userSymbol != '<') && (userSymbol != '>')); attemptsNumber++; if (userSymbol == '<') b = randomNumber-1; if (userSymbol == '>') a = randomNumber+1; if (userSymbol == '=') { printf("Your mysterious number is %hd!\n", randomNumber); printf("Attempts number: %d", attemptsNumber); break; } } break; } return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <math.h> #include "triangle.h" int main() { char* path = getPath(); puts(path); int count_of_triangles; Triangle* triangles = ReadTriangleFile(path, &count_of_triangles); int t = 0; while (1) { printf("Select an operation : 1 - area, 2 - perimeter, 3 - height, 4 - type of triangle: "); scanf(" %d", &t); for (int i = 0; i < count_of_triangles; ++i) if (t == 1) CountSquare(triangles[i]); else if (t == 2) CountPerimeter(triangles[i]); else if (t==3) Height(triangles[i]); else if (t==4) PrintTriangleType(triangles[i]); printf("If you want to exit, enter 0: "); scanf(" %d", &t); if (t == 0) break; } return 0; } <file_sep>#include "person.h" #include <iostream> #include <fstream> #include <sstream> using namespace std; string getPath() { string path; while (true) { cout << "Enter the name of your file:" << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } cout << "ERROR:The file isn`t open\n" << endl; } } string Person::getName() const { return Name; } string Person::getSurname() const { return Surname; } int PersonsList::person_count(const string& path) const { int count = 0; string line; ifstream file(path); while (getline(file, line)) { if (!line.empty()) { count++; } } file.close(); return count; } PersonsList::PersonsList(const string& path) { count = person_count(path); persons = new Person[count]; ifstream file(path); if (file.is_open()) { string line; int index = 0; while (getline(file, line)) { string Surname, Name, Middle_name, Nation; address address; date date; gender Gender; int Height, Weight; long long phone_number; stringstream ss(line); string token; getline(ss, token, ';'); // Фамилия Surname = token; getline(ss, token, ';'); // Имя Name = token; getline(ss, token, ';'); // Отчество Middle_name = token; getline(ss, token, ';'); // Пол Gender = (token == "M") ? male : female; getline(ss, token, ';'); // Национальность Nation = token; getline(ss, token, ';'); // Дата рождения stringstream date_ss(token); getline(date_ss, token, '.'); // День date.day = stoi(token); getline(date_ss, token, '.'); // Месяц date.mounth = stoi(token); getline(date_ss, token, '.'); // Год date.year = stoi(token); getline(ss, token, ';'); // Рост Height = stof(token); getline(ss, token, ';'); // Вес Weight = stof(token); getline(ss, token, ';'); // Телефонный номер phone_number = stoll(token); getline(ss, token, ';'); // Почтовый индекс address.postal_code = stoi(token); getline(ss, token, ';'); // Страна address.Country = token; getline(ss, token, ';'); // Область address.Region = token; getline(ss, token, ';'); // Район address.Area = token; getline(ss, token, ';'); // Город address.City = token; getline(ss, token, ';'); // Улица address.Street = token; getline(ss, token, ';'); // Номер дома address.House = stoi(token); getline(ss, token, ';'); // Номер квартиры address.Apart = stoi(token); Person p(Surname, Name, Middle_name, Gender, Nation, date, Height, Weight, phone_number, address); persons[index] = p; index++; } file.close(); } } void PersonsList::surname_sort() { Person* temp = new Person; for (int i = 0; i < count; i++) { for (int j = i + 1; j < count; j++) { if (persons[j].getSurname() != persons[i].getSurname()) { if (persons[j].getSurname() < persons[i].getSurname()) { *temp = persons[i]; persons[i] = persons[j]; persons[j] = *temp; } } else { if (persons[j].getName() < persons[i].getName()) { *temp = persons[i]; persons[i] = persons[j]; persons[j] = *temp; } } } } } PersonsList::~PersonsList() { delete[] persons; } Person::Person(const string& surname, const string& name, const string& middle_name, gender gender, const string& nation, const date& birth_date, float height, float weight, long long phone_number, const address& address) : Surname(surname), Name(name), Middle_name(middle_name), Gender(gender), Nation(nation), date_(birth_date), Height(height), Weight(weight), phone_number(phone_number), address_(address) { } Person::Person() {} ostream& operator<<(ostream& out, const Person& p) { string gender[]{ "male", "female" }; out << "===========================================" << endl; out << "FIO: " << p.Surname << " " << p.Name << " " << p.Middle_name << endl; out << "Gender: " << gender[p.Gender] << endl; out << "Nation: " << p.Nation << endl; out << "Date: " << p.date_.day << "." << p.date_.mounth << "." << p.date_.year << endl; out << "Height: " << p.Height << endl; out << "Weight: " << p.Weight << endl; out << "Phone number: " << p.phone_number << endl; out << "Postal code: " << p.address_.postal_code << endl; out << "Country: " << p.address_.Country << endl; out << "Region: " << p.address_.Region << endl; out << "Address: city: " << p.address_.City << endl; out << "Area: " << p.address_.Area << endl; out << "Street: " << p.address_.Street << endl; out << "House: " << p.address_.House << endl; out << "Apartament: " << p.address_.Apart << endl; return out; } ostream& operator<<(ostream& out, const PersonsList& pl) { for (int i = 0; i < pl.count; i++) { out << pl.persons[i]; } return out; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <windows.h> #include <profileapi.h> #include <malloc.h> #define MAX_PATH_LEN 100 void getFiles(char* path, struct file* files); int getCountOfFiles(char* path); int* getlensFileNames(char* path, int count_files); void quick_sort(struct file* files, int size); void merge(struct file* files, int l, int mid, int r); void mergeSort(struct file* files, int l, int r); void bubble_sort(struct file* files, int len); void print_gap(); void print_files(struct file* files, int len); struct file* cpy_arr(struct file* files, int len, int* lensNames); char* getPath(); void sortFiles(struct file* files, int len, int* lensNames); struct file { char* name; int size; }; int main() { struct file* files; char path[MAX_PATH_LEN]; int count_files; int* lensNames; int i; strcpy(path, getPath()); count_files = getCountOfFiles(path); // counting the number of files lensNames = getlensFileNames(path, count_files); // counting the length of file names files = (struct file*)malloc(count_files * sizeof(struct file)); for (i = 0; i < count_files; i++) { files[i].name = (char*)malloc((lensNames[i] + 1) * sizeof(char)); } getFiles(path, files); sortFiles(files, count_files, lensNames); // free memory for (i = 0; i < count_files; i++) { free(files[i].name); } free(files); return 0; } void sortFiles(struct file* files, int count_files, int* lensNames) { struct file* copy; char sort_selection[100] = ""; char sortEnough[100] = ""; int i; int enough = 1; long long time1; long long time2; printf("\nOk, I got all the files, how do you want to sort them?\n"); while (enough) { printf("Enter '1' - if you want to use a bubble_sort, '2' -- merge_sort, '3' -- quick_sort:\n"); do { gets(sort_selection); if ((strcmp(sort_selection, "1") != 0) && (strcmp(sort_selection, "2") != 0) && (strcmp(sort_selection, "3") != 0)) { printf("incorrest data, please enter '1' - if you want to use a bubble_sort, '2' -- merge_sort, '3' -- quick_sort:\n"); } } while ((strcmp(sort_selection, "1") != 0) && (strcmp(sort_selection, "2") != 0) && (strcmp(sort_selection, "3") != 0)); copy = cpy_arr(files, count_files, lensNames); if (strcmp(sort_selection, "1") == 0) { printf("\nList of files as they are located in the directory\n"); print_files(copy, count_files); print_gap(); QueryPerformanceCounter(&time1); bubble_sort(copy, count_files); QueryPerformanceCounter(&time2); printf("\nThis is sorted list of your files in this directory (sorted by bubble_sort)\n"); print_files(copy, count_files); } else if (strcmp(sort_selection, "2") == 0) { printf("\nList of files as they are located in the directory\n"); print_files(copy, count_files); print_gap(); QueryPerformanceCounter(&time1); mergeSort(copy, 0, count_files - 1); QueryPerformanceCounter(&time2); printf("\nThis is sorted list of your files in this directory (sorted by merge_sort)\n"); print_files(copy, count_files); } else { printf("\nList of files as they are located in the directory\n"); print_files(copy, count_files); print_gap(); QueryPerformanceCounter(&time1); quick_sort(copy, count_files); QueryPerformanceCounter(&time2); printf("\nThis is sorted list of your files in this directory (sorted by quick_sort)\n"); print_files(copy, count_files); } printf("it took exactly %lld milliseconds to sort\n\n", time2 - time1); printf("If you want to sort again this directory -- enter 'again', else - enter 'enough'\n"); do { gets(sortEnough); if ((strcmp(sortEnough, "again") != 0) && (strcmp(sortEnough, "enough") != 0)) { printf("incorrest data, please enter only 'again' or 'enough'\n"); } } while ((strcmp(sortEnough, "again") != 0) && (strcmp(sortEnough, "enough") != 0)); if (strcmp(sortEnough, "enough") == 0) { enough = 0; } // free memory for (i = 0; i < count_files; i++) { free(copy[i].name); } free(copy); } } char* getPath() { char path[MAX_PATH_LEN]; int getPathSuccess = 0; while (!getPathSuccess) { printf("enter the path to directory which files you want to look at:\n"); gets(path); strcat(path, "//*"); if (checkPath(path)) { getPathSuccess = 1; } else { printf("Path is incorrect\n Try again, don't give up!!!\n"); } } return path; } int checkPath(char* path) { WIN32_FIND_DATAA files_data; HANDLE h_file = FindFirstFileA(path, &files_data); FindNextFileA(h_file, &files_data); if (h_file == INVALID_HANDLE_VALUE) { return 0; } return 1; } struct file* cpy_arr(struct file* files, int len, int* lensNames) { int i; struct file* copy_files; copy_files = (struct file*)malloc(len * sizeof(struct file)); for (i = 0; i < len; i++) { copy_files[i].name = (char*)malloc((lensNames[i] + 1) * sizeof(char)); } for (i = 0; i < len; i++) { strcpy(copy_files[i].name, files[i].name); copy_files[i].size = files[i].size; } return copy_files; } int getCountOfFiles(char* path) { int count = 0; WIN32_FIND_DATAA files_data; HANDLE h_file = FindFirstFileA(path, &files_data); FindNextFileA(h_file, &files_data); while (FindNextFileA(h_file, &files_data) != NULL) { if (files_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } count++; } FindClose(h_file); return count; } int* getlensFileNames(char* path, int count_files) { int* lens = (int*)malloc(count_files * sizeof(int)); WIN32_FIND_DATAA files_data; HANDLE h_file = FindFirstFileA(path, &files_data); FindNextFileA(h_file, &files_data); int i = 0; while (FindNextFileA(h_file, &files_data) != NULL) { if (files_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } lens[i] = strlen(files_data.cFileName); i++; } FindClose(h_file); return lens; } void getFiles(char* path, struct file* files) { WIN32_FIND_DATAA files_data; HANDLE h_file = FindFirstFileA(path, &files_data); FindNextFileA(h_file, &files_data); int i = 0; printf("Here what I found:\n"); while (FindNextFileA(h_file, &files_data) != NULL) { if (files_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } printf("%s ", files_data.cFileName); strcpy(files[i].name, files_data.cFileName); printf("%d\n", files_data.nFileSizeLow); files[i].size = files_data.nFileSizeLow; i++; } FindClose(h_file); } void print_files(struct file* files, int len) { int i; for (i = 0; i < len; i++) { printf("%s %d\n", files[i].name, files[i].size); } } void print_gap() { printf("\n-----------------------------------\n"); } void bubble_sort(struct file* files, int len) { int i, j; struct file tmp; tmp.name = ""; tmp.size = 0; for (i = 0; i < len; i++) { for (j = 0; j < len - 1 - i; j++) { tmp.name = "111"; tmp.size = -1; if (files[j + 1].size < files[j].size) { tmp = files[j]; files[j] = files[j + 1]; files[j + 1] = tmp; } } } } void mergeSort(struct file* files, int l, int r) { if (l < r) { int mid = (l + r) / 2; mergeSort(files, l, mid); mergeSort(files, mid + 1, r); merge(files, l, mid, r); } } void merge(struct file* files, int l, int mid, int r) { int i, j, k; int n1 = mid - l + 1; int n2 = r - mid; struct file* L; struct file* R; L = (struct file*)malloc(n1 * sizeof(struct file)); R = (struct file*)malloc(n2 * sizeof(struct file)); //Copy to temperary arrays for (i = 0; i < n1; i++) L[i] = files[l + i]; for (j = 0; j < n2; j++) R[j] = files[mid + 1 + j]; // Merge the temperary arrays i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i].size <= R[j].size) { files[k] = L[i]; i++; } else { files[k] = R[j]; j++; } k++; } // copy ending of L, if it's exists while (i < n1) { files[k] = L[i]; i++; k++; } // copy ending of R, if it's exists while (j < n2) { files[k] = R[j]; j++; k++; } free(R); free(L); } void quick_sort(struct file* files, int size) { // start & end of array int i = 0; int j = size - 1; struct file tmp; tmp.name = "111"; tmp.size = -1; //middle int mid = files[size / 2].size; // greater -- to right, less -- to left do { while (files[i].size < mid) { i++; } while (files[j].size > mid) { j--; } if (i <= j) { tmp = files[i]; files[i] = files[j]; files[j] = tmp; i++; j--; } } while (i <= j); //if there are something to sort if (j > 0) { // left part quick_sort(files, j + 1); } if (i < size) { // right part quick_sort(&files[i], size - i); } }<file_sep>// Две окружности задаются координатами центров и радиусом, // определите взаимное расположение этих окружностей #include <stdio.h> #include <math.h> int main() { float x1, y1, x2, y2, r1, r2; printf("Введите координаты x первой окружности"); scanf("%f", &x1); printf("Введите координаты y первой окружности"); scanf("%f", &y1); printf("Введите радиус первой окружности"); scanf("%f", &r1); printf("Введите координаты x второй окружности"); scanf("%f", &x2); printf("Введите координаты y второй окружности"); scanf("%f", &y2); printf("Введите радиус второй окружности"); scanf("%f", &r2); if (r1>r2) { if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))<(r1-r2)) printf("Одна окружность внутри второй, не пересекаются"); if ((sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))<(r1+r2))&&(sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>(r1-r2))) printf("Окружности пересекаются в 2 точках"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))==(r1+r2)) printf("Окружности касаются внешне"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>(r1+r2)) printf("Окружности не пересекаются"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))==(r1-r2)) printf("Окружности касаются внутренне"); } if (r1<r2) { if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))<(r2-r1)) printf("Одна окружность внутри второй, не пересекаются"); if (sqrt(((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))<(r2+r1))&&((sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>(r2-r1)))) printf("Окружности пересекаются в 2 точках"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))==(r2+r1)) printf("Окружности касаются внешне"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>(r2+r1)) printf("Окружности не пересекаются"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))==(r2-r1)) printf("Окружности касаются внутренне"); } if (r1==r2) { if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))<(r2+r1)&&(sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>(r1-r2))) printf("Окружности пересекаются в 2 точках"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))==(r2+r1)) printf("Окружности касаются внешне"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))>(r2+r1)) printf("Окружности не пересекаются"); if (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))==(r2-r1)) printf("Окружности совпадают"); } }<file_sep>#include <iostream> #include <fstream> #include "stars.h" using namespace std; Constellation_library::Constellation_library(string& path) { ifstream in; int st_cnt; string name; in.open(path); if (in.is_open()) { in >> count; cns = new Constellation[count]; for (int i = 0; i < count; i++) { in >> name >> st_cnt; Constellation tmp(name, st_cnt); in >> &tmp; cns[i] = tmp; } in.close(); } } Constellation_library:: ~Constellation_library() { delete[] cns; cns = nullptr; count = 0; } Constellation::Constellation(std::string Cname, int n) { count = n; name = Cname; stars = new Star[n]; } Constellation:: ~Constellation() { delete[] stars; stars = nullptr; count = 0; name = ""; } string read_path() { ifstream in; string path; cout << endl << "Enter the path: "; cin >> path; return path; } ostream& operator<<(ostream& out, const Constellation_library& lib) { for (int i = 0; i < lib.getCount() / 2; i++) { out << i + 1 << "." << lib.getCns(i)->getName() << " \t\t " << i + 6 << "." << lib.getCns(i + 5)->getName() << endl; } out << "\nOutput format:\n\n name distance magnitude coordinates(deg, min, sec)\n\n"; return out; } ostream& operator<< (ostream& out, const Constellation* cns) { cout << endl << cns->name << endl; for (int i = 0; i < cns->count; i++) { cout << " " << cns->stars[i].name << " " << cns->stars[i].dist << " " << cns->stars[i].magnitude << " "; cout << cns->stars[i].deg << "° " << cns->stars[i].min << "' " << cns->stars[i].sec << "\"" << endl; } return out; } istream& operator>> (istream& in, const Constellation* cns) { for (int j = 0; j < cns->count; j++) { in >> cns->stars[j].name; in >> cns->stars[j].dist >> cns->stars[j].magnitude >> cns->stars[j].deg >> cns->stars[j].min >> cns->stars[j].sec; } return in; } Constellation& Constellation::operator=(const Constellation& obj) { this->count = obj.count; this->name = obj.name; this->stars = new Star[count]; for (int i = 0; i < this->count; i++) { this->stars[i] = obj.stars[i]; } return *this; } Star& Star::operator=(const Star& obj) { deg = obj.deg; dist = obj.dist; magnitude = obj.magnitude; min = obj.min; name = obj.name; sec = obj.sec; return *this; } void choice(Constellation_library& lib) { string con; cout << lib; cout << "Choice a constellation" << endl; do { int flag = 0; cout << endl << ">> "; cin >> con; if (con == "stop") flag = 1; for (int i = 0; i < lib.getCount() && flag == 0; i++) { if (lib.getCns(i)->getName() == con) { cout << lib.getCns(i); flag = 1; } } if (!flag) cout << "Not found. Please, choose constellation from table" << endl; } while (con != "stop"); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); int number, user_number; int min = 1, max = 1000, try = 0; char mode, answer; number = 1 + rand() % (1000); printf("Select operating mode 1 or 2: "); scanf("%c", &mode); switch (mode) { case '1': printf("The program guessed a number from 1 to 1000. Try to guess it)) : "); do { scanf("%d", &user_number); if (user_number == number) printf("You guessed the number!\n"); else if (user_number < number) printf("The hidden number is greater.Try again : "); else printf("The hidden number is less. Try again: "); try++; } while (user_number != number); printf("You guessed the number %i in %i tries!", number, try); break; case '2': printf("Think of a number from 1 to 1000 and enter it. The program will try to guess it: "); do { scanf("%d", &user_number); if (user_number > 1000 || user_number < 0) { printf("Invalid number entered\n"); } } while (user_number > 1000 || user_number < 0); while (user_number != number) { number = min + rand() % (max - min + 1); printf("Is it number %d ? ", number); scanf("%c", &answer); if (scanf("%c", &answer) != 1) { while ((answer = getchar()) != '\n' && answer != EOF) { ; } } try++; if (answer == '=') printf("The program guessed the number %i in %i tries!", number, try); else if (answer == '>') min = 1 + number; else if (answer == '<') max = number - 1; } break; } return 0; }<file_sep>#ifndef _FUNC_H #define _FUNC_H typedef struct { int size; double** num; } SMatrix; void alloc_matrix(SMatrix** matrix, int n); void free_matrix (SMatrix** matrix); void create_matrix (SMatrix* matrix); SMatrix* sum_matrix(SMatrix* m1, SMatrix* m2); void print_matrix (SMatrix* matrix); SMatrix* multiply_matrix(SMatrix* m1, SMatrix* m2); SMatrix* multiply_matrix_n_scalar(SMatrix* m1, double n); SMatrix* sum_matrix_n_scalar(SMatrix* m1, double n); #endif // !_FUNC_H<file_sep>#include <iostream> #include <fstream> #include <string> #include "person.h" using namespace std; int main() { int n, a; string f; cout << "Enter filename or path: "; cin >> f; n = cntStruct(f); Person** p = new Person*[n]; read(p, n, f); for (int i = 0; i < n; i++) cout << *(p[i]); Sort(p, n); do { cout << "\nHow do you want to display the sorted list?\n1. In alphabetical ascending order\n2. In alphabetical descending order\nEnter a number: "; cin >> a; if (a == 1) { cout << "\n"; for (int i = 0; i < n; i++) cout << *(p[i]); } if (a == 2) { cout << "\n"; for (int i = n - 1; i >= 0; i--) cout << *(p[i]); } } while ((a <= 0) || (a > 2)); for (int i = 0; i < n; i++) delete p[i]; delete[]p; return 0; }<file_sep>#include <stdio.h> #include <time.h> #include <stdlib.h> int main() { int an[5] = { -1, -1, -1, -1, -1 }, n = 0, len, i, gN, cDi = 0, endOfGame = 1; srand(time(NULL)); printf("Let's play in Bull-n-cow game!\nChoose length of number (from 2 to 5) [2, 5]:\n"); // ask the user the length of number do { scanf_s("%d", &len); if (len < 2 || len >5) { printf("Your choice is incorrect! Try again choose length only in [2, 5]\n"); } } while (len < 2 || len >5); // generation random number i = 0; while (i < len) { int newN, flag = 1, j; newN = 1 + rand() % 9; // first digit can't be 0 for (j = 0; j < len; j++) { // check that there are no repeat of digits if (an[j] == newN) flag = 0; } if (flag) { // if everything is OK -- save digit an[i] = newN; i++; } } printf("I choose some number with length %d\nTry to guess:\n", len); // основной цикл игры while (endOfGame) { int c_Bull = 0, c_Cow = 0, copy, cDi, gNarr[5], i, j, flag = 1; do { int c_of_dig[10] = { 0 }, i; cDi = 0; scanf_s("%d", &gN); copy = gN; while (copy > 0) { c_of_dig[copy % 10] += 1; // accumulating count of all digits cDi++; copy /= 10; } for (i = 0; i < 10; i++) { if (c_of_dig[i] > 1) { flag = 0; } } if (!flag) { printf("there are some repeating digits in your number! \n"); } if (cDi != len) { printf("I have chosen some number, which length is %d!!! You have entered number with some other length!\n", len); } } while (cDi != len || !flag); copy = gN; for (i = len - 1; i >= 0; i--) { gNarr[i] = copy % 10; copy /= 10; } //подсчёт коров for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { if (gNarr[j] == an[i] && i != j) { c_Cow++; } } } //подсчёт быков: for (i = 0; i < len; i++) { if (an[i] == gNarr[i]) { c_Bull++; }; } if (c_Bull == len) { endOfGame = 0; printf("You're WINNER! Congratulation!"); break; } printf("Count of Bull: %d\nCount of Cow: %d\n", c_Bull, c_Cow); } return 0; }<file_sep>#include <stdlib.h> #include <stdio.h> #include "func.h" void alloc_matrix(SMatrix** matrix, int n) { *matrix = (SMatrix*)malloc(sizeof(SMatrix) * 1); (*matrix)->size = n; (*matrix)->num = (double**)malloc(sizeof(double*) * n); for (int i = 0; i < n; i++) { (*matrix)->num[i] = (double*)malloc(sizeof(double) * n); } } void free_matrix (SMatrix** matrix) { for (int i = 0; i < (*matrix)->size; i++) { free((*matrix)->num[i]); } free((*matrix)->num); free(*matrix); } void create_matrix (SMatrix* matrix) { for (int i = 0; i < matrix->size; i++){ for (int j = 0; j < matrix->size; j++) { scanf("%lf", &(matrix->num[i][j])); } } } SMatrix* sum_matrix(SMatrix* m1, SMatrix* m2) { SMatrix* res; alloc_matrix (&res, m1->size); for (int i = 0; i < m1->size; i++){ for (int j = 0; j < m1->size; j++){ res->num[i][j] = m1->num[i][j] + m2->num[i][j]; } } return res; } void print_matrix (SMatrix* matrix) { for (int i = 0; i < matrix->size; i++){ for (int j = 0; j < matrix->size; j++){ printf("%.2lf ", matrix->num[i][j]); } printf("\n"); } printf("\n"); } SMatrix* multiply_matrix(SMatrix* m1, SMatrix* m2) { SMatrix* res; alloc_matrix (&res, m1->size); for(int i = 0; i < m1->size; i++) { for(int j = 0; j < m1->size; j++) { res->num[i][j] = 0; for(int g = 0; g < m1->size; g++) { res->num[i][j] += m1->num[i][g] * m2->num[g][j]; } } } return res; } SMatrix* multiply_matrix_n_scalar(SMatrix* m1, double n) { SMatrix* res; alloc_matrix (&res, m1->size); for(int i = 0; i < m1->size; i++) { for(int j = 0; j < m1->size; j++) { res->num[i][j] = m1->num[i][j] * n; } } return res; } SMatrix* sum_matrix_n_scalar(SMatrix* m1, double n) { SMatrix* res; alloc_matrix (&res, m1->size); for(int i = 0; i < m1->size; i++) { for(int j = 0; j < m1->size; j++) { res->num[i][j] = m1->num[i][j] + n; } } return res; } <file_sep>#include <stdio.h> #include "matrix.h" #include <stdlib.h>; void alloc_matrix(TMatrix** matrix, int n) { *matrix = (TMatrix*)malloc(sizeof(TMatrix) * 1); (*matrix)->n = n; (*matrix)->element = (float*)malloc(sizeof(float) * n*n); } void fill_matrix(TMatrix* matrix) { int i = 0, j = 0; for (; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { scanf("%f", &(matrix->element[i * matrix->n + j])); } } } void print_matrix(TMatrix* matrix) { int i = 0, j = 0; for (; i < matrix->n; i++) { for (j = 0; j < matrix->n; j++) { printf("%0.3f ", matrix->element[i * matrix->n + j]); } printf("\n"); } } void free_matrix(TMatrix** matrix) { free((*matrix)->element); free(*matrix); } TMatrix* sum_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; int i = 0, size = 0; if (matrix1->n != matrix2->n) { printf("ERROR: Matrix should have the same lenght.\n"); return NULL; } alloc_matrix(&res, matrix1->n); size = res->n * res->n; for (; i < size; i++) { res->element[i] = matrix1->element[i] + matrix2->element[i]; } return res; } TMatrix* add_const(TMatrix* matrix, float c) { TMatrix* res; int i = 0, size = 0; alloc_matrix(&res, matrix->n); size = res->n * res->n; for (; i < size; i++) { res->element[i] = matrix->element[i] + c; } return res; } TMatrix* multi_const(TMatrix* matrix, float c) { TMatrix* res; int i = 0; alloc_matrix(&res, matrix->n); int size = res->n * res->n; for (; i < size; i++) { res->element[i] = matrix->element[i] * c; } return res; } TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2) { TMatrix* res; alloc_matrix(&res, matrix1->n); int i = 0, j = 0, k = 0; if (matrix1->n != matrix2->n) { printf("ERROR: Matrix should have the same lenght.\n"); return 1; } for (; i < matrix1->n; i++) { for (j = 0; j < matrix1->n; j++) { res->element[i * matrix1->n + j] = 0; for (k = 0; k < matrix1->n; k++) { res->element[i * matrix1->n + j] += matrix1->element[i * matrix1->n + k] * matrix2->element[k * matrix2->n + j]; } } } return res; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> int isUnique(int number, int n) { int tmp[10], i = 0; while (number > 0) { tmp[i] = number % 10; number /= 10; i++; } for (i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (tmp[i] == tmp[j]) { return 1; } } } return 0; } int len(int number) { int l = 0; while (number > 0) { number /= 10; l++; } return l; } int main() { int a[] = { 0,1,2,3,4,5,6,7,8,9 }, r, n, i = 0, t, sup = 9; int mass[] = { 0,0,0,0,0,0,0 }, bulls = 0, cows = 0, userInput, userMass[] = { 0,0,0,0,0 }; srand(time(NULL)); do { printf("Enter the length of the number from 2 to 5\n"); if (scanf("%d", &n) != 1) { printf("Enter only numbers..."); return 1; } } while (n < 2 || n > 5); for (i; i < n; i++) { r = rand() % (sup + 1); t = rand() % 10; mass[i] = a[r]; if (mass[0] == 0) { while (mass[0] == 0) { mass[0] = t; } for (int e = t; e < 10; ++e) { a[e] = a[e + 1]; } --sup; continue; } for (int e = r; e < 10; ++e) { a[e] = a[e + 1]; } --sup; } for (int g = 0; g < n; g++) { printf("%d", mass[g]); } printf(" ***A computer-generated number***\n"); while (bulls != n) { bulls = cows = 0; do { printf("Enter your guess\n"); if (scanf("%d", &userInput) != 1) { printf("Enter only numbers..."); return 1; } } while ((isUnique(userInput, n) != 0) || len(userInput) != n); for (i = 1; n - i >= 0; i++) { userMass[n - i] = userInput % 10; userInput /= 10; } for (i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((userMass[i] == mass[j]) && (i != j)) { cows++; } } } for (i = 0; i < n; i++) { if (userMass[i] == mass[i]) { bulls++; } } printf("Cows: %d\n", cows); printf("Bulls: %d\n", bulls); } printf("Congratulations, you win!"); return 0; }<file_sep>#include <stdio.h> #include <math.h> int main() { float r1, r2, x1, x2, y1, y2,CircleCenterDistance,dl1; printf("Enter the coordinates of the first circle and its radius\n"); scanf_s("%f%f%f", &x1, &y1, &r1); printf("Enter the coordinates of the second circle and its radius\n"); scanf_s("%f%f%f", &x2, &y2, &r2); CircleCenterDistance = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); dl1=r1>r2?r1-r2:r2-r1; if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("Circle coincide\n"); //Окружности совпадают } else if (CircleCenterDistance > (r1 + r2)) { printf("Circles do not intersect (one does not lie in the other)\n"); //Окружности не пересекаются (одна не лежит в другой) } else if (CircleCenterDistance == dl1) { printf("The circles touch internally\n"); //Окружности касаются внутренним образом } else if( (CircleCenterDistance == (r1 + r2)) ) { printf("The circles touch externally\n"); //Окружности касаются внешним образом } else if (CircleCenterDistance < dl1) { printf("Circles do not intersect (one lies in the other)\n");//Окружности не пересекаются (одна лежит в другой) } else { printf("Overlapping circles\n");//Окружности пересекаюстя } return 0; }<file_sep>#include <stdio.h> #include <stdio.h> #include <time.h> #define N 5 int main() { srand((unsigned int)time(NULL)); int i, x, k, j, numb_int, st = 1, input, p_numb[N]; do { printf("enter number of digits N="); scanf_s("%d", &x); } while (x < 2 || x>5); int numb[N]; do { for (i = 0; i < N - (5 - x); i++) { numb[i] = rand() % 10; } k = 0; for (i = 0; i < N - (5 - x); i++) for (j = i + 1; j < N - (5 - x); j++) if (numb[i] == numb[j]) k++; } while (k > 0 || numb[0] == 0); numb_int = 0; for (i = N - (5 - x) - 1; i >= 0; i--) { numb_int += numb[i] * st; st *= 10; } for (i = 0; i < N - (5 - x); i++) { printf("%d", numb[i]); } printf("\n"); do { int check_p, z; do { printf("enter the number\n"); scanf_s("%d", &input); check_p = input; z = 0; while (check_p > 0) { z++; check_p /= 10; } } while (z != x); check_p = input; for (i = N - (5 - x) - 1; i >= 0; i--) { p_numb[i] = check_p % 10; check_p /= 10; } int bulls = 0, cows = 0; for (i = 0; i < N - (5 - x); i++) { if (numb[i] == p_numb[i]) bulls++; } int digit_comp[10] = { 0 }, digit_p[10] = { 0 }, index, temp = 0; for (i = 0; i < N - (5 - x); i++) { index = numb[i]; digit_comp[index] = 1; index = p_numb[i]; digit_p[index] = 1; } for (i = 0; i < 10; i++) { if (digit_comp[i] == digit_p[i] && digit_comp[i] != 0) temp++; } cows = temp - bulls; printf("bulls=%d, cows=%d", bulls, cows); printf("\n"); } while (input != numb_int); printf("number guessed\n"); return 0; system("pause>nul"); } <file_sep>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include "Header.h" using namespace std; int n; void token_size(string const& str, const char delim, vector<string>& out) { stringstream ss(str); string s; while (getline(ss, s, delim)) { out.push_back(s); } } Owner* read_inf(int& n) { string path; cout << "enter path" << endl; cin >> path; ifstream infile(path); if (!infile) { throw "file not finde"; } infile >> n; Owner* o = new Owner[n]; string data; for (int i = 0; i < n; i++) { infile >> o[i]; } infile.close(); return o; } void print_inf(Owner* o, int n) { for (int i = 0; i < n; i++) { cout << o[i]; } } Owner* search_owner(Owner* o, int& n, int& k) { Owner* o1 = new Owner[n]; int flag = 0, g; while (flag == 0) { cout << "input number of gibdd = "; cin >> g; cout << endl; for (int i = 0; i < n; i++) { if (o[i].getGibdd() == g) { o1[flag] = o[i]; flag++; } } if (flag == 0) { cout << "incorrect number of gibdd" << endl; } } k = flag; return o1; } istream& operator>>(istream& in, Owner& o) { string day; in >> o.surname >> o.name >> o.patronymic >> day >> o.carnum >> o.gibdd >> o.phnum >> o.tehpas; const char delim = '.'; string* razdel = new string[3]; vector<string> out; token_size(day, delim, out); int j = 0; for (auto& data : out) { razdel[j++] = data; } try { int k = 0; o.setData(stoi(razdel[k]), stoi(razdel[k + 1]), stoi(razdel[k + 2])); } catch (const invalid_argument& e) { cout << "caught invalid argiment in date" << e.what(); } delete[] razdel; return in; } ostream& operator<<(ostream& out, const Owner& o) { out << o.surname << " " << o.name << " " << o.patronymic << endl << o.date.getDay() << "." << o.date.getMonth() << "." << o.date.getYear() << endl << o.carnum << endl << o.gibdd << endl << o.phnum << endl << o.tehpas << endl << endl; return out; }<file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { int n; float* x; }Matrix; void allocate_matrix(Matrix** matr, int n); void free_matrix(Matrix** matr); void fill_matrix(Matrix* matr, int n); void print_matrix(Matrix* matr, int n); Matrix* add_dot(Matrix* matr, float a); Matrix* multiple_dot(Matrix* matr, float a); Matrix* add_matrix(Matrix* matr1, Matrix* matr2); Matrix* multiple_matrix(Matrix* matr1, Matrix* matr2); #endif<file_sep>#include "Header.h" bool isDigit(const std::string& s) { for (int i = 0; i < s.size(); i++) { if (std::isdigit(s[i]) == 0) return false; } return true; } // TProductsDatabase: TProductsDatabase::TProductsDatabase(const std::string& filename) { get_correct_file_name(filename); std::ifstream file(filename); std::string line; while (getline(file, line)) { std::stringstream f_line(line); std::string info_unit; TInfoProduct tmp; TProduct curr_prod; getline(f_line, info_unit, ';'); curr_prod.code = stol(info_unit); getline(f_line, info_unit, ';'); curr_prod.name = info_unit; getline(f_line, info_unit, ';'); curr_prod.cost = stod(info_unit); tmp.product = curr_prod; getline(f_line, info_unit, ';'); tmp.count = stoi(info_unit); productsInStock.insert(tmp); /*file.get();*/ } file.close(); } void TProductsDatabase::get_correct_file_name(const std::string& fname) const { bool file_exist; do { getline(std::cin, const_cast<std::string&>(fname)); file_exist = check_file_name(fname); if (!file_exist) std::cout << "Such file doesn't exist" << std::endl; } while (!file_exist); } bool TProductsDatabase::check_file_name(const std::string& fname) const { std::ifstream fin(fname); return !fin.fail(); } TInfoProduct& TProductsDatabase::operator[](int ind) { return productsInStock[ind]; } int TProductsDatabase::Get_num_prods() const { return productsInStock.Get_size(); } int TProductsDatabase::barcode_search(const long barcode) { for (int i = 0; i < productsInStock.Get_size(); i++) { if (productsInStock[i].product.code == barcode) { return i; } } return -1; } void TProductsDatabase::Updating_data_remove(const TProduct& prod) { int ind_such_prod = this->barcode_search(prod.code); (*this)[ind_such_prod].count -= 1; } void TProductsDatabase::Updating_data_add(const TProduct& prod) { int ind_such_prod = this->barcode_search(prod.code); (*this)[ind_such_prod].count += 1; } void TProductsDatabase::create_updating_db() { std::remove("DB.csv"); std::ofstream file("DB.csv"); for (int i = 0; i < this->Get_num_prods(); i++) { file << (*this)[i].product.code << ";"; file << (*this)[i].product.name << ";"; file << (*this)[i].product.cost << ";"; file << (*this)[i].count << ";"; file << "\n"; } file.close(); } // TInfoProduct: bool TInfoProduct::operator==(const TInfoProduct& p) const { return (product == p.product and count == p.count); } // TProduct: bool TProduct::operator==(const TProduct& p) const { return (code == p.code and name == p.name and cost == p.cost); } std::ostream& operator<<(std::ostream& out, const TProduct& p) { out << "Product code: " << p.code << " "; out << "Product name: " << p.name << " "; out << "Cost per unit: " << p.cost << "\n"; return out; } //TReceiptLine: TReceiptLine::TReceiptLine() { count = 0; sum_cost = 0; } TReceiptLine::TReceiptLine(TProduct& product, int count, double sum_cost) { this->product = product; this->count = count; this->sum_cost = sum_cost; } TReceiptLine::TReceiptLine(const TReceiptLine& rec_line) { this->product = rec_line.product; this->count = rec_line.count; this->sum_cost = rec_line.sum_cost; } const TProduct& TReceiptLine::Get_product() const { return product; } int TReceiptLine::Get_count() const { return count; } double TReceiptLine::Get_sum_cost() const { return sum_cost; } void TReceiptLine::Set_count(int c) { count = c; } void TReceiptLine::Set_sum_cost(double s) { sum_cost = s; } const TReceiptLine& TReceiptLine::operator=(const TReceiptLine& rec_line) { this->product = rec_line.product; this->count = rec_line.count; this->sum_cost = rec_line.sum_cost; return (*this); } bool TReceiptLine::operator==(const TReceiptLine& rec_line) const { return (this->product == rec_line.product); } std::ostream& operator<<(std::ostream& out, const TReceiptLine& rec_line) { out << rec_line.product << "\n"; out << rec_line.count << " pieces\n"; out << "total cost:" << rec_line.sum_cost << "rubles\n\n"; return out; } // Time & Data TTime::TTime() { hour = 0; minute = 0; second = 0; } TDate::TDate() { year = 0; month = 0; day = 0; } // TReceipt: long TReceipt::code = -1; void TReceipt::Code_increase() { code++; } TReceipt::TReceipt() {} TReceipt::TReceipt(const TReceipt& rec) { this->code = rec.code; this->time = rec.time; this->date = rec.date; this->products = rec.products; } TReceiptLine& TReceipt::operator[](int ind) { return products[ind]; } const TReceipt& TReceipt::operator= (const TReceipt& rec) { if (this == &rec) return (*this); this->code = rec.code; this->time = rec.time; this->date = rec.date; this->products = rec.products; return (*this); } std::ostream& operator<<(std::ostream& out, TReceipt& rec) { rec.Code_increase(); out << "\n------------------------------------------\n"; out << "Receipt code: " << rec.code << "\n\n"; out << rec.date.day << "." << rec.date.month << "." << rec.date.year << " "; out << rec.time.hour << ":" << rec.time.minute << ":" << rec.time.second << "\n"; out << "Your products: \n"; out << rec.products; out << "TOTAL SUM: " << rec.Get_total_sum() << " rubles\n"; out << "------------------------------------------\n"; return out; } int TReceipt::get_barcode_add(TProductsDatabase& db) { std::string barcode; int search_result = 0; bool isAvaliable = true; getline(std::cin, barcode); if (isDigit(barcode)) { search_result = db.barcode_search(stol(barcode)); if (search_result == -1) { std::cout << "In our store there are not the product with this barcode. Try again!\n >>> "; } else if (db[search_result].count == 0) { isAvaliable = false; } } if (!isDigit(barcode)) { std::cout << "Barcodes consists only of digits! Try again!\n\n >>> "; } if (!isAvaliable) { std::cout << "Unfortunately, the product is out of stock. Take something else.\n\n >>> "; } if (search_result != -1 and isDigit(barcode) and isAvaliable) { return search_result; } else { return -1; } } int TReceipt::get_barcode_delete(TProductsDatabase& db) { std::string barcode; int search_result = 0; getline(std::cin, barcode); if (isDigit(barcode)) { search_result = this->Find_product(stol(barcode)); if (search_result == -1) { std::cout << "You did not add a product with this barcode to the receipt. Try again\n\n --- "; } } if (!isDigit(barcode)) { std::cout << "Barcodes consists only of digits! Try again\n\n --- "; } if (search_result != -1 and isDigit(barcode)) { return search_result; } else { return -1; } } int TReceipt::Get_num_products() const { return products.Get_size(); } void TReceipt::Add_new_prod(const TReceiptLine& rec_line) { products.insert(rec_line); } int TReceipt::Find_product(const long code) const { for (int i = 0; i < products.Get_size(); i++) { if (products[i].Get_product().code == code) { return i; } } return -1; } double TReceipt::Get_total_sum() const { double total_sum = 0; int count = this->Get_num_products(); for (int i = 0; i < count; i++) { total_sum += this->products[i].Get_sum_cost(); } return total_sum; } void TReceipt::Get_data_n_time() { std::time_t mil = std::time(0); std::tm* now = std::localtime(&mil); this->time.hour = now->tm_hour; this->time.minute = now->tm_min; this->time.second = now->tm_sec; this->date.day = now->tm_mday; this->date.month = now->tm_mon + 1; this->date.year = now->tm_year + 1900; } void TReceipt::Delete_prod(const int ind) { std::cout << "This product was deleted: " << this->products[ind].Get_product() << "\n"; if (this->products[ind].Get_count() == 1) { this->products.remove(ind); } else { this->products[ind].Set_count(this->products[ind].Get_count() - 1); } } void TReceipt::Delete(TProductsDatabase& db) { if (this->Get_num_products() == 0) { std::cout << "The receipt is empty, there is nothing to delete!\n"; \ } else { std::cout << "Enter product barcode that you want to delete:\n\n --- "; int search_result = this->get_barcode_delete(db); if (search_result != -1) { db.Updating_data_add((*this)[search_result].Get_product()); this->Delete_prod(search_result); } } } void TReceipt::Add(TProductsDatabase& db) { std::cout << "Enter barcode you want to add\n\n >>> "; int search_result = this->get_barcode_add(db); if (search_result != -1) { TProduct curr_p = db[search_result].product; std::cout << "\n" << curr_p << "\n"; // Search such prod in receipt int idx_prod_in_receipt = this->Find_product(curr_p.code); if (idx_prod_in_receipt != -1) { ((*this)[idx_prod_in_receipt]).Set_count( ((*this)[idx_prod_in_receipt]).Get_count() + 1 ); ((*this)[idx_prod_in_receipt]).Set_sum_cost( ((*this)[idx_prod_in_receipt]).Get_sum_cost() + curr_p.cost ); } else { TReceiptLine curr_rec_line(curr_p, 1, curr_p.cost); this->Add_new_prod(curr_rec_line); } db.Updating_data_remove(curr_p); } }<file_sep>#include <iostream> #include <clocale> #include <cstdlib> #include "display.h" #include "polynom.h" using namespace std; void choose() { cout << "1. Сложить полиномы." << endl; cout << "2. Вычесть из одного полинома второй полином." << endl; cout << "3. Умножение полиномов." << endl; cout << "4. Вычислить значение по заданному аргументу." << endl; cout << "5. Найти производную полинома." << endl; cout << "0. Выход\n" << endl; } void answer(int& ans) { do { cin >> ans; } while (ans > 5 || ans < 0); } void retry(int& ans) { cout << "\nПродолжить? (1/0)" << endl; answer(ans); } void print_p(TPolynom*& p, const int n) { for (int i = 0; i < n; i++) { cout << "f" << i << " = "; cout << p[i]; } cout << endl; } void index(int* ind, int n) { cout << "Выберите 2 полинома:\n"; cout << "Полином 1: "; do { cin >> ind[0]; } while (ind[0] < 0 || ind[0] >= n); cout << "Полином 2: "; do { cin >> ind[1]; } while (ind[1] < 0 || ind[1] >= n); cout << endl; } void print_2p(TPolynom& p1, TPolynom& p2, int* ind) { cout << "f" << ind[0] << " = "; cout << p1; cout << "f" << ind[1] << " = "; cout << p2; cout << endl; }<file_sep>#include <stdio.h> #include <locale.h> #include <stdlib.h> #include "display.h" #include "polynom.h" void choose() { printf("1. Сложить полиномы.\n"); printf("2. Вычесть из одного полинома второй полином.\n"); printf("3. Умножение полиномов.\n"); printf("4. Вычислить значение по заданному аргументу.\n"); printf("5. Найти производную полинома.\n"); printf("0. Выход\n\n"); } void answer(int* ans) { do { scanf("%d", ans); } while (*ans > 5 || *ans < 0); } void retry(int* ans) { printf("\nПродолжить? (1/0)\n"); answer(ans); } void print_p(TPolynom** p, int n) { int i = 0; for (i = 0; i < n; i++) { printf("f%d = ", i); print_polynom(p[i]); } printf("\n"); } void print_2p(TPolynom* p1, TPolynom* p2, int* ind) { printf("f%d = ", ind[0]); print_polynom(p1); printf("f%d = ", ind[1]); print_polynom(p2); printf("\n"); } void index(int* ind, int n) { printf("Выберите 2 полинома:\n"); printf("Полином 1: "); do { scanf("%d", &ind[0]); } while (ind[0] < 0 || ind[0] >= n); printf("Полином 2: "); do { scanf("%d", &ind[1]); } while (ind[1] < 0 || ind[1] >= n); printf("\n"); }<file_sep>#ifndef _FILEPROCESSING_H #define _FILEPROCESSING_H #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_NAME 100 #define MAX_LINE_LEN 5000 typedef enum { DNEV, VECHER, ZAOCH } EducationalForm; typedef struct { char name[MAX_NAME]; int n_form; EducationalForm* forms; int* examScores; int* costs; } Spec_t; typedef struct { char name[MAX_NAME]; int n_spec; Spec_t* specs; } University_t; int find_num_univ(char fname[]); University_t* fill_univ(char fname[], int c); void free_memory(University_t* uns, int c); #endif<file_sep>#include<stdio.h> #include<conio.h> #include<math.h> #include<time.h> int main() { int a, number, attempt, b, i, res; char zn; srand(time(NULL)); printf("Select game mode: 1-number guesses computer, 2 - the number is guessed by the person\n"); do { scanf_s("%d", &a); } while ((a < 1) || (a > 2)); switch (a) { case 1: { number = 1 + rand() % 1000; printf("Enter the number"); i = 0; do { scanf_s("%d", &b); if (b < number) printf("less\n"); if (b > number) printf("greater\n"); i++; } while ((b != number)); printf("you found the number - %d\n", b); printf("number of attempts - %d", i); break; } case 2: { int res = 0, x = 1, y = 1000, num = 0; char zn; b = 1 + rand() % 1000; printf("number=%d\n", b); printf("Enter the zn\n"); do { zn = getc(stdin); switch (zn) { case '>': printf("I will try again\n"); y = b; b = x + rand() % (y - x + 1); printf("number=%d\n", b); break; case '<': printf("I will try again\n"); x = b; b = x + rand() % (y - x + 1); printf("number=%d\n", b); break; case '=': printf("number is found\n"); res = 1; break; //default: printf("error"); } num++; } while (res != 1); printf("i found the number - %d\n", b); printf("number of attempts - %d", num/2); } } return 0; } <file_sep>#ifndef _WORKERS_H #define _WORKERS_H typedef struct { char* id; char* profession; char* education; char* last_job; char* rsn_dismiss; char* family_status; int contact_info; }worker; char* get_Path(); void allocate_workers(worker** w, int n); int amount(char* path); void adding(worker* w, char* path); void higher_education(worker* w, int count); void free_workers(worker** w, int number); #endif <file_sep>#pragma once #ifndef _TAGENCY_H #define _TAGENCY_H #include "TService.h" #include <string> struct TAgency // Tourist agency { string name; int num_services; TService* services; TAgency(void); TAgency(int num_services);//initialisation of TAgency objects TAgency(const TAgency& object);//copy object ~TAgency(); }; #endif<file_sep>#define _CRT_SECURE_NO_WARNINGS #include "matrix.h" void allocate_matrix(TMatrix** matrix, int dimension) { (*matrix) = (TMatrix*) malloc(sizeof(TMatrix) * 1); (*matrix) -> d = dimension * dimension; (*matrix) -> x = (float*) malloc(sizeof(float) * dimension * dimension); } void build_matrix(TMatrix* matrix) { int k = 0; for (int i = 0; i < matrix->d; i++) scanf("%f", &(matrix->x[i])); } void print_matrix(TMatrix* matrix, int dimension) { int k = 0; for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { printf("\t %f", matrix->x[k]); k++; } printf("\n"); } printf("\n"); } TMatrix* addition(TMatrix* matrix1, TMatrix* matrix2, int dimension) { TMatrix* result; if (matrix1->d != matrix2->d) return NULL; allocate_matrix(&result, (matrix1->d) / dimension); for (int i = 0; i < result->d; i++) result->x[i] = matrix1->x[i] + matrix2->x[i]; return result; } TMatrix* multiplication(TMatrix* matrix1, TMatrix* matrix2, int dimension) { TMatrix* result; int k = 0, i = 0, j = 0; if (matrix1->d != matrix2->d) return NULL; allocate_matrix(&result, (matrix1->d) / dimension); for (i = 0; i < dimension; i++) { for (j = 0; j < dimension; j++) { result->x[i * dimension + j] = 0; for (k = 0; k < dimension; k++) { result->x[i * dimension + j] += matrix1->x[i * dimension + k] * matrix2->x[k * dimension + j]; } } } return result; } TMatrix* multiplication_const(TMatrix* matrix1, int consta, int dimension) { TMatrix* result; allocate_matrix(&result, (matrix1->d) / dimension); for (int i = 0; i < matrix1->d; i++) result->x[i] = matrix1->x[i]*consta; return result; } void free_m(TMatrix** matrix) { free((*matrix)->x); free(*matrix); } <file_sep>#include <iostream> #include <string> #include <vector> #include "Header_banks.h" #include <fstream> using namespace std; int read(BanksData*& data, int* p, const string& path) { ifstream infile(path); if (!infile) { cout << "This file isn`t exist" << endl; return 1; } else { infile >> (*p); int n = *p; data = new BanksData[n]; for (int i = 0; i < n; i++) { infile >> data[i].name >> data[i].ownership >> data[i].count; data[i].deposits.resize(data[i].count); for (int j = 0; j < data[i].count; j++) { infile >> data[i].deposits[j].name >> data[i].deposits[j].period >> data[i].deposits[j].conditions; } } infile.close(); return 0; } } void input_path(string& path) { cout << "Input a path with file type: " << endl; cin >> path; cout << "Your path : \n" << path << " \n" << endl; } void print_data(BanksData* data, int n) { cout << "Yours data: " << "\n \n"; for (int i = 0; i < n; i++) { cout << data[i].name << " " << data[i].ownership << " " << data[i].count << endl; for (int j = 0; j < data[i].count; j++) { cout << data[i].deposits[j].name << " " << data[i].deposits[j].period << " " << data[i].deposits[j].conditions << endl; } cout << "\n \n"; } } void input_user_data(int* user_year, float* user_money) { do { cout << "For how long would you like to open a deposit?" << endl; cin >> (*user_year); if ((*user_year) <= 0 || (*user_year) >= 100) { cout << "Wrong period, try again" << endl; } } while ((*user_year) <= 0 || (*user_year) >= 100); do { cout << "How much would you like to open a deposit for (rubles)? " << endl; cin >> (*user_money); if ((*user_money) <= 0) { cout << "Wrong period, try again" << endl; } } while ((*user_money) <= 0); } pair<int, float> BanksData::best_deposit(int user_year, float user_money) { float profit = 0; int id = -1; for (int j = 0; j < count; j++) { if (user_year % deposits[j].period == 0) { float tmp_profit = user_money * (pow(1 + (deposits[j].conditions * 0.01), user_year));// formule if (profit < tmp_profit) { profit = tmp_profit; id = j; } } } pair<int, float> q; q.first = id; q.second = profit; return q; } triple comparing(BanksData* data, int user_year, float user_money, int n) { triple ans; BanksData best_data = data[0]; best_data.best_suggestion = best_data.best_deposit(user_year, user_money); ans.id1 = 0; ans.id2 = best_data.best_suggestion.first; ans.profit = best_data.best_suggestion.second; for (int i = 1; i < n; i++) { data[i].best_suggestion = data[i].best_deposit(user_year, user_money); if (best_data < data[i]) { best_data = data[i]; ans.id1 = i; ans.id2 = data[i].best_suggestion.first; ans.profit = data[i].best_suggestion.second; } } return ans; } <file_sep>#ifndef _FUNCTIONS_H #define _FUNCTIONS_H struct Dates_t { int day; int month; int year; }; struct EmployeesInfo_t { char* name; char* edu; char* spec; char* unit; char* appnt; struct Dates_t dateofappnt; struct Dates_t lastdate; }; struct Pasports_t{ int series; int number; char* auth; char* issue; struct Dates_t birth; struct Dates_t reg; }; void* get_target(void* base, int size, int index); void set_data_char(void* base, int size, int index, char* value); void set_data_int(void* base, int size, int index, int value); void read_str(FILE* file, int n, void* target, size_t struct_size); void read_int(FILE* file, int n, void* target, size_t struct_size); void scanstring(char** tmpstr, FILE* file); void set_data(char** data, const char* value); void struct_free(struct EmployeesInfo_t* g_empls, struct Pasports_t* g_pspts); void allocstructmem(int n, char* filename, struct EmployeesInfo_t** g_empls, struct Pasports_t** g_pspts); void age_scan(int n, struct EmployeesInfo_t* g_empls, struct Pasports_t* g_pspts); #endif // !_FUNCTIONS_H <file_sep>#include <stdio.h> #include <Windows.h> #include <profileapi.h> #include "Sorts.h" char name[MAX_PATH][MAX_PATH]; int size[MAX_PATH]; int size_copy[MAX_PATH]; int nums[MAX_PATH]; CHAR path[MAX_PATH]; int t = 0; void fancy_print(const char* text) { static int c = 0; for (int i = 0; i < strlen(text); i++) { printf("%c", text[i]); if (++c % 4 == 0) Sleep(1); } } void result(char* text, int a) { fancy_print(text); for (int j = 0; j < a; j++) { fancy_print(name[nums[j]]); fancy_print(", "); printf("%d", size[nums[j]]); fancy_print(" bytes\n"); } } int FindFiles(LPCSTR directory) { int i = 0; WIN32_FIND_DATAA found_files; HANDLE end_found = FindFirstFileA(directory, &found_files); FindNextFileA(end_found, &found_files); if (end_found != INVALID_HANDLE_VALUE) { fancy_print("look what I found:\n"); while (FindNextFileA(end_found, &found_files) != NULL) { strcpy(name[i], found_files.cFileName); size[i] = found_files.nFileSizeLow; fancy_print(name[i]); fancy_print(", "); printf("%d", size[i]); fancy_print(" bytes\n"); i++; } FindClose(end_found); } else { FindClose(end_found); fancy_print("*wrong destination*\n"); scanf("%s", &path); FindFiles(path); } return i; } void work_it_Willis(a) { LARGE_INTEGER time, freq; double frq; char str; long long int ms = 0; for (int j = 0; j < a; j++) size_copy[j] = size[j]; if (t == 0) { t++; QuickSort(size_copy, 0, a, nums); work_it_Willis(a); } for (int j = 0; j < a; j++) nums[j] = j; str = getc(stdin); fseek(stdin, 0, SEEK_END); QueryPerformanceFrequency(&freq); frq = (double)(freq.QuadPart) / 1000000; QueryPerformanceCounter(&time); ms = time.QuadPart; switch (str) { case 'Q': case 'q': QuickSort(size_copy, 0, a, nums); QueryPerformanceCounter(&time); result("QuickSort did this:\n", a); fancy_print("and spent "); printf("%.02lf ", ((double)((time.QuadPart - ms) * 10.0) / frq)); fancy_print("nanoseconds\n"); work_it_Willis(a); case 'C': case 'c': ChooseSort(size_copy, a, nums); QueryPerformanceCounter(&time); result("ChooseSort did this:\n",a); fancy_print("and spent "); printf("%.02lf ", ((double)((time.QuadPart - ms) * 10.0) / frq)); fancy_print("nanoseconds\n"); work_it_Willis(a); case 'm': case 'M': mergeSort(size_copy, 0, a - 1, a, nums); QueryPerformanceCounter(&time); result("MergeSort did this:\n", a); fancy_print("and spent "); printf("%.02lf ", ((double)((time.QuadPart - ms)) / frq)); fancy_print("nanoseconds\n"); work_it_Willis(a); case 'e': case 'E': return; } work_it_Willis(a); } void main() { int a; fancy_print("choose a directory:\n"); scanf("%s", &path); a = FindFiles(path); fancy_print("Choose, how you want these files to be sorted or exit file manager\n"); fancy_print("QuickSort, MergeSort, ChooseSort, exit: \n"); work_it_Willis(a); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <conio.h> #include <math.h> int main() { float h, w, d, d_dvp = 800, d_dsp = 450, d_tree = 900; float m, m1, m2, m3, m4, m5; float tn1 = 5, tn2 = 15, tn3 = 10; int n; printf("Input values h,w,d "); /*dlina, shirina, glubina*/ scanf("%f %f %f", &h, &w, &d); if (h < 180 || h > 220 || w > 120 | w < 80 || d < 50 || d > 90) { printf("Incorrect data"); return 1; } else { /*perevod v sistemu CI*/ n = h / 40; h = h / 100; w = w / 100; d = d / 100; tn1 = tn1 / 1000; /*tolshina1*/ tn2 = tn2 / 1000; /*tolshina2*/ tn3 = tn3 / 1000; /*tolshina3*/ /*PODSCHOT CHASTEY*/ m1 = h * w * tn1 * d_dvp; /*Nakladnaya stenka*/ m2 = 2 * (h * d * tn2 * d_dsp); /*Dve bokovini*/ m3 = 2 * (tn2 * (w - 2*tn2) * d * d_dsp); /*Nakladnie krishki*/ m4 = h * w * tn3 * d_tree; /*dve nakladnie dveri*/ m5 = n * (d * (w - 2*tn2) * tn2 * d_dsp); /*<NAME>*/ /*RESULTAT*/ m = m1 + m2 + m3 + m4 + m5; printf("Mass of wardrobe= %f", m); getchar(); return 0; } }<file_sep>#include "func.h" #include <stdio.h> #include <stdlib.h> void main() { SMatrix* matrix1, *matrix2, *resMatrix; int size; double scalar; scanf("%d", &size); scanf("%lf", &scalar); alloc_matrix(&matrix1, size); alloc_matrix(&matrix2, size); create_matrix (matrix1); create_matrix (matrix2); resMatrix = sum_matrix(matrix1, matrix2); print_matrix(resMatrix); free_matrix(&resMatrix); resMatrix = multiply_matrix(matrix1, matrix2); print_matrix(resMatrix); free_matrix(&resMatrix); resMatrix = sum_matrix_n_scalar(matrix1, scalar); print_matrix(resMatrix); free_matrix(&resMatrix); resMatrix = multiply_matrix_n_scalar(matrix1, scalar); print_matrix(resMatrix); free_matrix(&resMatrix); free_matrix(&matrix1); free_matrix(&matrix2); }<file_sep>#include "receipt.h" #include "container.h" #include "interface.h" int main() {//C:\Users\nikit\Desktop\1.txt string path = start(); dataBase data(path); Container<Receipt> receipts; menu(data, receipts); return 0; }<file_sep>#include <iostream> #include <fstream> #include <sstream> #include "lib.h" string CardIndex::getSection() const { return this->section; } string CardIndex::getTitle() const { return this->title; } vector <CardIndex> Library::getCards() const { return this->cards; } bool CardIndex::operator==(const string& otherTitle) const { return (title == otherTitle); } bool CardIndex::operator!=(const string& otherTitle) const { return !(title == otherTitle); } ostream& operator<<(ostream& os, const CardIndex& card) { os << "Title: " << card.title << endl; os << "Authors: "; for (int i = 0; i < card.authors.size(); i++) { os << card.authors[i]; if (i < card.authors.size() - 1) { os << ", "; } } os << endl; os << "Publisher: " << card.publisher << endl; os << "Section: " << card.section << endl; os << "Availability: " << (card.avb == availability::available ? "Available" : "Not available") << endl; os << "Evaluation: " << card.evaluation << endl; os << "-----------------------" << endl; return os; } string menu() { string path; while (true) { cout << "Enter the file path..." << endl; getline(cin, path); ifstream file(path); if (file.good()) { file.close(); return path; } cout << "ERROR: Could not open file!\n" << endl; } } CardIndex::CardIndex(const vector <string>& authors, const string& title, const string& publisher, const string& section, const availability avb, const float evaluation) : authors(authors), title(title), publisher(publisher), section(section), avb(avb), evaluation(evaluation) {} Library::Library(const string& path) { int j = 0; ifstream file(path); string line; float evaluation; while (getline(file, line)) { if (line.empty()) { continue; } stringstream ss(line); string item; getline(ss, item, ';'); stringstream authorsStream(item); string author; stringstream authorsStream2(item); int i = 0; vector <string> authors; string title; string publisher; string section; availability avb; while (getline(authorsStream2, author, ',')) { authors.push_back(author); i++; } getline(ss, title, ';'); getline(ss, publisher, ';'); getline(ss, section, ';'); string availabilityStr; getline(ss, availabilityStr, ';'); if (availabilityStr == "Available") { avb = available; } else { avb = not_available; } string evaluationStr; getline(ss, evaluationStr, ';'); evaluation = stof(evaluationStr); CardIndex card(authors, title, publisher, section, avb, evaluation); this->cards.push_back(card); j++; } file.close(); } CardIndex::~CardIndex() { this->authors.clear(); } Library::~Library() { this->cards.clear(); } set <string> Library::booksBySection() { int count = this->cards.size(); set <string> sections; vector <CardIndex> crd = this->getCards(); for (int i = 0; i < count; i++) { sections.insert(this->getCards()[i].getSection()); } for (string s : sections) { cout << "\nBooks from " << s << endl; for (int j = 0; j < count; j++) { if (this->getCards()[j].getSection() == s) { cout << this->cards[j]; } } } return sections; } vector <CardIndex> Library::findBooks(const set <string>& sections) { vector <CardIndex> books; cout << "Available sections:" << endl; for (auto it = sections.begin(); it != sections.end(); it++) { cout << *it << endl; } string requestedSection; do { cout << "Enter the section you are interested in: "; getline(cin, requestedSection); auto it = sections.find(requestedSection); if (it != sections.end()) { break; } } while (true); cout << "Books in section \"" << requestedSection << "\":" << endl; int count = this->cards.size(); for (int i = 0; i < count; i++) { if (this->cards[i].getSection() == requestedSection) { books.push_back(this->cards[i]); cout << "- " << this->cards[i].getTitle() << endl; } } return books; } void Library::getBook(const vector <CardIndex>& books) { string requestedTitle; do { cout << "Enter the title of the book you are interested in: "; getline(cin, requestedTitle); for (int i = 0; i < books.size(); i++) { if (books[i] == requestedTitle) { cout << books[i]; return; } } } while (true); } <file_sep>#include <iostream> #include <cstring> #include <fstream> #include <string> #include "header.h" using namespace std; int main() { Product* p; int size = cntLines("sklad.txt"); cout << size << endl; allocate_stock(p, size); fill_sklad(p,size, "sklad.txt"); find_NULL(p, size); free_stock(p); } <file_sep>#include <stdio.h> #include <time.h> #include <stdlib.h> #define n 5 int main() { int ox=0, cow=0, i, j, size=0, zifr, tmp, chisl, ch[n], ch1[n]; srand((unsigned int)time(NULL)); printf("Write a number of zifr\n"); do { scanf("%d", &size); } while ((size<2)||(size>5)); ch[0]=1+(rand()%9); for (i=1; i<size; i++){ tmp=0; while(tmp==0) { zifr = rand() % 10; for (j = 0; j < i; j++) { if (ch[j] == zifr) { tmp = 1; break; } } if (tmp == 0) { ch[i] = zifr; break; } } } printf("Write a number with %d zifr\n", size); while (ox!=size){ scanf("%d",&chisl); tmp=0; ox=0; cow=0; for (i=size-1; i>=0; i--){ ch1[i]=chisl%10; chisl/=10; } for (i=1; i<size; i++) { for (j = 0; j < i; j++) { if (ch1[i] == ch1[j]) { tmp++; ox = 0; break; } } } if (tmp>0||chisl != 0 || ch1[0] == 0) { printf("Wrong number\n"); ox = 0; } else { for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { if (ch[i] == ch1[j]) { if (i == j) { ox++; } else { cow++; } } } } printf("Number of cow = %d, number of ox = %d\n", cow, ox); } } printf("Correct! It's number: "); for (i=0; i<size; i++){ printf("%d",ch[i]); } return 0; } <file_sep>#ifndef _BASE_H_ #define _BASE_H_ #include "Product.h" #include <iostream> #include <fstream> using namespace std; class Base { private: Product product; int count; public: Base() { count = 0; } friend ifstream& operator>>(ifstream& buf, Base& Date); friend ostream& operator<<(ostream& buf, const Base& Date); friend istream& operator>>(istream& buf, Base& Date); bool operator == (const string& str) const; bool operator == (const Base& base) const; bool operator != (const Base& base) const; Base& operator += (const int& ucount); Product get_product() const; int get_count() const; void set_count(const int ucount); }; #endif <file_sep>#include <iostream> #include <fstream> #include <string> #include "Product.h" using namespace std; Product::Product() { code = '*'; name = '*'; cost = 0; } Product::Product(const string& ncode, const string& nname, const double& ncost) { code = ncode; name = nname; cost = ncost; } Product::Product(const Product& new_product) { code = new_product.code; name = new_product.name; cost = new_product.cost; } //overloaded operations ifstream& operator>>(ifstream& buf, Product& Date) { buf >> Date.code >> Date.name >> Date.cost; return buf; } ostream& operator<<(ostream& buf, const Product& Date) { buf << Date.code << " " << Date.name << " " << Date.cost << " "; return buf; } istream& operator>>(istream& buf, Product& Date) { buf >> Date.code >> Date.name >> Date.cost; return buf; } const Product& Product::operator=(const Product& new_product) { if (*this == new_product) return *this; code = new_product.code; name = new_product.name; cost = new_product.cost; return *this; } bool Product::operator==(const string& str) const { return (code == str || name == str); } bool Product::operator==(const Product& prod) const { return (code == prod.code && name == prod.name && cost == prod.cost); } string Product::get_name() const { if (this == nullptr) return ""; return name; } string Product::get_code() const { return code; } double Product::get_cost() const { return cost; } <file_sep>#include <stdio.h> #include <math.h> int main() { float r1, r2, x1, x2, y1, y2, s = 0, a, b; int ymax, ymin, xmax, rmax, rmin, xmin; printf("Vvedite koordinats x, y b radius pervoy okruzhosti"); scanf("%f %f %f", &x1, &y1, &r1); printf("Vvedite koordinats x, y b radius vtoroy okruzhosti"); scanf("%f %f %f", &x2, &y2, &r2); rmin = fmin(r1, r2); rmax = fmax(r1, r2); if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("okruzhosti sovpadayut"); return 0; } s = sqrt((x1 -x2)* (x1 - x2) + (y1 - y2)*(y1 - y2)); if (s == (r1 + r2)) { printf("okruzhnosti kasautsya snaruzhi"); return 0; } if (s > (r1 + r2)) { printf("okruzhnosti ne peresekautsya"); return 0; } if (s < (r1 + r2)) { if ((s == rmin) || (rmax - s == rmin)) { printf("okruzhnosti kasautsya vnutri"); return 0; } if (rmax - s > rmin) { printf("okruzhnost soderzhitsya v drugoi"); return 0; } printf("okruzhnosti peresekayutsya v dvuh tochkah"); } return 0; }<file_sep>#ifndef _HEAD #define _HEAD using namespace std; struct Data { string day; string month; string year; }; struct Owner { string name; string surname; string patronymic; Data date; string carnum; unsigned long gibdd; string phnum; unsigned long tehpas; friend istream& operator>>(istream& in, Owner& o); friend ostream& operator<<(ostream& out, const Owner& o); }; Owner* read_inf(int& n); void print_inf(Owner* o, int n); Owner* search_owner(Owner* o, int& n, int& k); #endif<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #define N 12 char* barcodes[N] = { "0231", "4051", "8950", "2456", "4789", "7890", "1234", "8907", "1236", "7890","2457", "0200" }; char* products[N] = { "Bread", "Milk", "Cheese", "Sausage", "Fish", "Egg", "Lemon", "Water", "Jam", "Onion","Porridge", "Rice" }; double price[N] = { 39.00, 80.00, 300.00, 5000.00, 75.00, 100.0, 2300.00, 25.00, 22229.99, 122131.00 }; double discount[N] = { 20, 40, 5, 15, 5, 5, 10, 30, 10, 20,20,12 }; char* description[N] = { "Wonderful\n","natural\n","yellow, no holes\n","Natural meat (not from dogs), honestly\n","from in the oceans, lakes and rivers, bred on special farms.\n","round, chicken\n","Sour, Russian\n","Liquid\n","Berry\n","Vampires are afraid of it\n","potato\n","made in China\n" }; int scan(int* amount) { int flag = 0; char barcode[6] = " "; printf("Enter a 4-digit code (or exit if you want to generate a final check):"); while (strcmp(barcode, "0")) { gets(barcode); flag = 0; if (strcmp(barcode, "0")) { for (int i = 0; i < N; i++) { if (strcmp(barcodes[i], barcode) == 0) { printf("name:%s\nprice:%.2f rubles\ndiccount:%.2fpercent\ndescription :%s\n", products[i], price[i], discount[i], description[i]); amount[i] += 1; flag = 1; } if (strcmp(barcode, "exit") == 0) { return 0; } } if (flag == 0) { printf("This product code does not exist, please try another one\n"); return 1; } printf("barcode:"); } } } void finalcheck(int* amount) { float check = 0; printf("Total check\n"); for (int i = 0; i < N; i++) { if (amount[i] != 0) { printf(("%s, price(with discount) - %.2f\n%d(amount).\n"), products[i], (price[i] * (1 - (discount[i] / 100))), amount[i]); } check += (price[i] * (1 - (discount[i] / 100))) * amount[i]; } printf("Total cost - %.2f", check); } int main() { int count[N] = { 0 }; int scan(count); if (scan(count) == 0) { finalcheck(count); } } <file_sep>/* * фирма умелые ручки выпускает двудверные одежные шкафы * состав шкафа: * 1) Накладная задняя стенка из двп: * Высотой h от 180 до 220 см * Шириной w от 80 до 120 см * Толщиной 5 мм * 2) Две боковины из дсп: * Высота h * Глубиной d от 50 до 90 см * Толщиной 15 мм * 3) Накладные верхняя и нижняя крышки из дсп: * Шириной w * Глубиной d * Толщиной 15 мм * 4) Две накладные двери из дерева: * Высотой h * Общей шириной w * Толщиной 1 см * 5) Внутренние полки через каждые 40 см из дсп: * Толщина 15 мм * !Найти массу если известна плотность дсп и двп! */ #include <stdio.h> #include <string.h> int main() { double h, w, d, mass=0, ch_polka=0, height; printf("Введите высоту шкафа\n"); scanf("%lf", &h); printf("Введите ширину шкафа\n"); scanf("%lf", &w); printf("Введите глубину шкафа\n"); scanf("%lf", &d); if ((h<180)||(h>220)||(w<80)||(w>120)||(d<50)||(d>90)) { printf ("Ошибка ввода данных\n"); return 1; } height=h-3; while (height>41.5) { height=height-40.0 - 1.5; //полка имеет толщину 15 мм и она будет занимать эту длину от общей высоты ch_polka=ch_polka+1; } printf("%.0lf\n",ch_polka); mass=mass+(h/100)*(w/100)*(5.0/1000)*800;//масса задней стенки mass=mass+2*(h/100)*(d/100)*(15.0/1000)*650;//+масса двух боковых стенок mass=mass+((w-2*(15.0/10))/100)*(d/100)*(15.0/1000)*650*(2+ch_polka); mass=mass+(h/100)*(w/100)*(1.0/100)*550; printf("Масса шкафа = %.2lf кг\n", mass); return 0; } <file_sep>#include <stdio.h> #include <Windows.h> #define GOODS_AMOUNT (sizeof(prod) / sizeof(prod[0])) struct goods_t { const char* name; const char* description; double price; const char* barcode; int discount; }; struct goods_t prod[] = { {"cabbage", "This is an average head of an average cabbage", 54.99, "1613", 46}, {"carrot", "A carrot. Just a carrot...", 9.99, "5144", 4}, {"candies", "Sweet! Some candies!",89.99 ,"3134", 28}, {"spaghetti", "Spaghetti italiani",79.99 ,"4114", 8}, {"zucchini", "Zucchini - schiacciare italiane",49.99 ,"6613", 5}, {"cheese", "CheeSe, not cheeZe",239.99 ,"1117", 21}, {"tomato", "Tomato is like an apple but better",14.99 ,"1335", 25}, {"bacon", "Bacon - cool part of a cool pig",149.99 ,"0552", 2}, {"lettuce", "Lettuce - when cabbage is not an option",29.99 ,"3333", 16}, {"chicken", "Chicken... KFC...",199.99 ,"2015", 17}, {"muffin", "Muffin - Delitious small piece of a cake",74.99 ,"4497", 16}, {"pickles", "Pickles are just forgotten cucumbers in a jar...",319.99 ,"2395", 14}, {"mushroom", "Mushroom - \"it's me, Mario!\"", 29.99, "0000", 38}, }; int products[GOODS_AMOUNT] = {0}; double cost = 0; double cost_without_discounts = 0; void fancy_print(const char* text) { static int c = 0; for (int j = 0; j < strlen(text); j++) { printf("%c", text[j]); if (++c % 2) Sleep(1); } } void introduction() { fancy_print("all items will be automatically scanned\n"); fancy_print("to print your current check enter 'c'\n"); fancy_print("to sum up and get final cost enter 'f'\n"); fancy_print("all barcodes:\n"); for (int i = 0; i < GOODS_AMOUNT; i++) { fancy_print(prod[i].name); fancy_print(": "); fancy_print(prod[i].barcode); printf("\n"); } printf("\n"); } void add_to_check( int index ) { fancy_print(prod[index].description); do { char confirm[2]; fancy_print("\nBuy one ([Y]es/No)? "); fgets(confirm, sizeof(confirm), stdin); fseek(stdin, 0, SEEK_END); switch(confirm[0]) { case '\n': printf("Yes\n"); case 'y': case 'Y': products[index]++; fancy_print("Added\n"); break; case 'n': case 'N': fancy_print("done\n"); return; } } while (1); } void make_check() { cost_without_discounts = 0; cost = 0; char buffer[80]; int i; printf("\n"); for (i = 0; i < 61; i++) { fancy_print("-"); }; snprintf(buffer, sizeof(buffer), "\n| %-20s | %8s | %5s | %9s |\n", "Name", "Price", "Count", "Total"); fancy_print(buffer); for (i = 0; i < 61; i++) { fancy_print("-"); }; fancy_print("\n"); for (int i = 0; i < GOODS_AMOUNT; i++) { if (products[i] > 0) { snprintf(buffer, sizeof(buffer), "| %-20s | %8.2lf | %4d | %9.2lf |\n", prod[i].name, prod[i].price, products[i], (double)products[i] * prod[i].price ); fancy_print(buffer); cost_without_discounts += (double)products[i] * prod[i].price; cost += (double)products[i] * prod[i].price * (1.0 - ((double)(prod[i].discount))/100); } } for (i = 0; i < 61; i++) { fancy_print("-"); } fancy_print("\noverall price without discounts: "); printf("%.2lf\n\n", cost_without_discounts); } void final_cost() { make_check(); fancy_print("Discount: "); printf("%.2lf", cost_without_discounts - cost); fancy_print("\nTotal price: "); printf("%.2lf", cost); } int find_barcode(char* barcode) { for ( int i = 0; i < GOODS_AMOUNT; ++i) if (!strcmp(barcode, prod[i].barcode)) return i; return -1; } int move() { char last_scan[5]; fancy_print("enter your barcode (4 digits)/ print check (c)/ final cost (f): "); fgets(last_scan, sizeof(last_scan), stdin); fseek(stdin, 0, SEEK_END); switch (last_scan[0]) { case 'f': final_cost(); return -1; case 'c': make_check(); break; default: { int index = find_barcode(last_scan); if (index < 0) fancy_print("couldn't find this barcode. Please, try again\n"); else { add_to_check(index); } } } return 0; } int main() { introduction(); while (!move()); } <file_sep>#ifndef _Header_bankh_ #define _Header_bankh_ #define MAX_PATH 100 // Max path length #define MAX_NAME 20 // Max name of banks length using namespace std; struct triple { int id1; int id2; float profit; //default constuctor and destructor }; struct Deposit { string name; int period; float conditions; //default contructor axnd destructor }; struct BanksData { string name; string ownership; int count; int user_year; float user_money; vector<Deposit> deposits; pair<int, float> best_suggestion; //Constructor BanksData() { name = ""; ownership = ""; count = -1; user_money = -1; user_year = -1; best_suggestion.first = -1; best_suggestion.second = -1; deposits.resize(0); } //Destructor ~BanksData() { deposits.resize(0); } pair<int, float> best_deposit(int user_year, float user_money); bool operator>(BanksData sd) { if (best_suggestion.second > sd.best_suggestion.second) return true; return false; } bool operator<(BanksData sd) { if (best_suggestion.second < sd.best_suggestion.second) return true; return false; } }; int read(BanksData*& data, int* n, const string& path); void input_path(string& path); void print_data(BanksData* data, int n); void input_user_data(int* user_year, float* user_money); triple comparing(BanksData* data, int user_year, float user_money, int n); #endif<file_sep>#ifndef _PERSON_H #define _PERSON_H typedef struct { char* country; char* region; char* city; char* district; char* street; char* house; char* apartament; }Address; typedef struct { char* surname; char* name; char* patronymic; char* gender; char* nation; char* date; char* height; char* weight; char* num_phone; char* postal_code; Address ad; }Person; int cntStruct(FILE* file); void allocate_person(Person** p); void fill_data(Person* p, FILE* file); void read(Person*** p, int* n); void print_persons(Person* p); void Sort(Person** p, int n); void free_person(Person** p); #endif // !_PERSON_H <file_sep>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <locale.h> #include <windows.h> #include <stdbool.h> #include "header.h" #define N 100 int counting() { FILE* file = fopen("C:\\Temp\\school.csv", "r"); char line[200]; int n = 0; if (file == NULL) { printf("File not defind\n"); return 1; } else { while (!feof(file)) { fgets(line, 200, file); n++; } } return n; fclose(file); } void allocation(TSchool** school, int n) { int i = 0; (*school) = (TSchool*)malloc(sizeof(TSchool) * n); for (; i < n; i++) { (*school + i)->FIO = (char*)malloc(sizeof(char) * N); (*school + i)->Gender = (char*)malloc(sizeof(char) * N); (*school + i)->Date = (char*)malloc(sizeof(char) * N); (*school + i)->Address = (char*)malloc(sizeof(char) * N); } } void release(TSchool** school, int n) { int i = 0; for (; i < n; i++) { free((*school + i)->FIO); free((*school + i)->Gender); free((*school + i)->Date); free((*school + i)->Address); } free(*school); } void read_file(TSchool* school) { FILE* file = fopen("C:\\Temp\\school.csv", "r"); int i, j = 0; char line[200]; char* str; if (file == NULL) { printf("File not defind\n"); } else { while (1) { if (fgets(line, 200, file) != NULL) { i = 0; str = strtok(line, ";"); while (str != NULL) { switch (i) { case 0: strcpy(school[j].FIO, str); break; case 1: school[j].Class = atoi(str); break; case 2: strcpy(school[j].Gender, str); break; case 3: strcpy(school[j].Date, str); break; case 4: strcpy(school[j].Address, str); break; } i++; str = strtok(NULL, ";"); } j++; } else { break; } } } } void print_file(TSchool* school, int n) { int i = 0; printf("ФИО Класс Пол Дата рождения Домашний адрес\n"); printf("\n"); for (; i < n; i++) { printf("%s %d %s %s %s\n", school[i].FIO, school[i].Class, school[i].Gender, school[i].Date, school[i].Address); } } void sorting(TSchool* school, int n) { int i = 0, j, k = 1; TSchool tmp; for (; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (school[i].Class > school[j].Class) { tmp = school[i]; school[i] = school[j]; school[j] = tmp; } } } i = 0; while (i < n) { while (school[i].Class == k) { j = i + 1; while (school[j].Class == k) { if (strcmp(school[i].FIO, school[j].FIO) > 0) { tmp = school[i]; school[i] = school[j]; school[j] = tmp; } j++; } i++; } k++; } }<file_sep>#include <stdio.h> #include <windows.h> #include <profileapi.h> #include "sort.h" #include "utils.h" WIN32_FIND_DATA FindFileData; HANDLE hf; int main() { long long start, end; int Flag; int count; do{ Flag = 1; int i = 0; int j = 0; char* userStr = (char*)malloc(MAX_PATH * sizeof(char)); wchar_t* path = (wchar_t*)malloc(MAX_PATH * sizeof(wchar_t)); userInput(userStr, path, hf, FindFileData); count = filesAmount(path, hf, FindFileData); char** fileNames = (char**)malloc(count * sizeof(char*)); unsigned long* sizes = (unsigned long*)malloc(count * sizeof(unsigned long)); hf = FindFirstFile(path, &FindFileData); fill(hf, FindFileData, fileNames, sizes); info(count, fileNames, sizes); do { unsigned long* size_copy = (unsigned long*)malloc(count * sizeof(unsigned long)); unsigned long* index = (int*)malloc(count * sizeof(int)); unsigned long* tmp = (unsigned long*)malloc(count * sizeof(unsigned long)); unsigned long* itmp = (unsigned long*)malloc(count * sizeof(unsigned long)); add(size_copy, index, sizes, count); switch (choice()) { case 1: QueryPerformanceCounter(&start); msort(size_copy, tmp, 0, (count - 1), index, itmp); QueryPerformanceCounter(&end); output(fileNames, size_copy, index, count, (end - start)); memFree(tmp, itmp); break; case 2: QueryPerformanceCounter(&start); quicksort(size_copy, 0, (count - 1), index); QueryPerformanceCounter(&end); output(fileNames, size_copy, index, count, (end - start)); break; case 3: QueryPerformanceCounter(&start); bubbleSort(size_copy, count, index, fileNames); QueryPerformanceCounter(&end); output(fileNames, size_copy, index, count, (end - start)); break; case 4: Flag = 0; break; case 5: return 0; default: break; } memFree(size_copy, index); } while (Flag == 1); memFreeMulti(userStr, fileNames, path, sizes, count); } while (Flag == 0); FindClose(hf); return 0; } <file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { int n; float* element; }TMatrix; void alloc_matrix(TMatrix** matrix, int n); void fill_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix); void free_matrix(TMatrix** matrix); TMatrix*sum_matrix(TMatrix* matrix1, TMatrix* matrix2); TMatrix* add_const(TMatrix* matrix, float c); TMatrix* multi_const(TMatrix* matrix, float c); TMatrix* multi_matrix(TMatrix* matrix1, TMatrix* matrix2); #endif _MATRIX_H <file_sep>#include <iostream> #include <fstream> #include "stars.h" using namespace std; int main() { system("chcp 1251"); Constellation_library* lib; int count; read_data(lib, count); cnst_table(lib, count); choice(lib, count); return 0; } <file_sep>#ifndef _PERSON_H #define _PERSON_H #include <string> using namespace std; struct Address { string country; string region; string city; string district; string street; string house; string apartament; }; struct Person { string surname; string name; string patronymic; string gender; string nation; string date; string height; string weight; string num_phone; string postal_code; Address ad; friend ostream& operator<<(ostream& out, const Person& p); }; void read(Person*& p, int& n); int cntStruct(string& f); void fill_data(Person*& p, int n, string& f); void Sort(Person*& p, int n); void removeFirstN(string& str, int n); #endif // !_PERSON_H <file_sep>#include <string> #ifndef _BOOK_H #define _BOOK_H using namespace std; struct TBook { int Couaut; string* Author; string Name; string Publishing; string Section; bool Availability; int Score; TBook(); ~TBook(); TBook& operator=(const TBook&); }; struct TLib { TBook* books; int count; int CountUnic; string* unic_section; TLib(); TLib(const string& path); TLib(const TLib& lib); TLib& operator=(const TLib&); ~TLib(); int count_books(const string& path) const; int count_unic() const; void create_section(); void print_unique_sections(); TLib search_by_section(const string& section_name); }; string get_path(); ostream& operator << (ostream& out, TBook& book); ostream& operator << (ostream& out, TLib& lib); #endif _BOOK_H <file_sep> #ifndef _HEADER_H #define _HEADER_H #include <string> #include <cstring> using namespace std; struct Date { int day; int month; int year; }; struct Product { string name; string unit; double price; int number; Date data; }; int cntLines(const string& filename); void allocate_sklad(Product*& p, int size); void fill_sklad(Product*& p, int size, const string &filename); void find_null(Product*& p, int size); void free_sklad(Product*& p, int size); #endif<file_sep>#include <stdio.h> #include <stdlib.h> #include "Sorts.h" void ChooseSort(int* arr, int len, int* nums) { for (int st = 0; st < len - 1; st++) { int MinPos = st, buf, buf0; for (int j = st + 1; j < len; j++) { if (arr[j] < arr[MinPos]) { MinPos = j; } } buf = arr[MinPos]; buf0 = nums[MinPos]; arr[MinPos] = arr[st]; nums[MinPos] = nums[st]; arr[st] = buf; nums[st] = buf0; } } void merge(int* arr, int beg, int mid, int end, int i, int* nums) { int i0 = 0, i1 = 0, i2 = beg; int* b = (int*)malloc(sizeof(int) * i); int* c = (int*)malloc(sizeof(int) * i); while ((i0 < (mid - beg + 1)) && (i1 < (end - mid))) { if (arr[beg + i0] <= arr[mid + i1 + 1]) { b[i2] = arr[beg + i0]; c[i2] = nums[beg + i0]; i0++; } else { b[i2] = arr[mid + i1 + 1]; c[i2] = nums[mid + i1 + 1]; i1++; } i2++; } while (i0 < (mid - beg + 1)) { b[i2] = arr[beg + i0]; c[i2] = nums[beg + i0]; i0++; i2++; } while (i1 < (end - mid)) { b[i2] = arr[mid + i1 + 1]; c[i2] = nums[mid + i1 + 1]; i1++; i2++; } for (int j = beg; j < i2; j++) { arr[j] = b[j]; nums[j] = c[j]; } free(b); free(c); } void mergeSort(int* arr, int beg, int end, int i, int* nums) { if (beg < end) { int mid; mid = (beg + end) / 2; mergeSort(arr, beg, mid, i, nums); mergeSort(arr, mid + 1, end, i, nums); merge(arr, beg, mid, end, i, nums); } } void QuickSort(int* arr, int beg, int end, int* nums) { int tmp, tmp0, piv, j = end, g = beg; piv = arr[(beg + end) / 2]; do { while (arr[g] < piv) { g++; } while (arr[j] > piv) { j--; } if (g <= j) { if (arr[g] > arr[j]) { tmp = arr[g]; arr[g] = arr[j]; arr[j] = tmp; tmp0 = nums[g]; nums[g] = nums[j]; nums[j] = tmp0; } g++; if (j > 0) { j--; } } } while (g <= j); if (g < end) { QuickSort(arr, g, end, nums); } if (j > beg) { QuickSort(arr, beg, j, nums); } }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <string> #include <vector> #include "cars.h" using namespace std; int main() { // get path to file with cars string filepath = GetFilePath(); cout << filepath << endl; // read file and save info about cars to array vector <Car> cars = ReadCarFile(filepath); // find oldest car Car oldest_car = FindOldestCar(cars); // print answer cout << oldest_car; return 0; } //C:\Users\itmm-y23b\Desktop\directory\mp1-practice\RezantsevaAA\Practice2_2\Practice2_2\cars.txt<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 10 int main() { int b[N], c[5] = { 0 }, a[5] = { 0 }, i, n = 0, cow = 0, bull = 0, p = 0, s, j, k = 0, d = 1, x = 0, o; printf("Vvedite skolki znachnim budet ygadivaemoe chislo (ot 2 do 5)"); do { scanf("%d", &n); } while ((n < 2) || (n > 5)); srand(time(NULL)); while (k < n) { i = rand() % 10; if (b[i] != 1) { x += i * d; b[i] = 1; k++; d *= 10; } } for (i = 0; i < n; i++) { a[i] = x % 10; x /= 10; } do { p++; cow = 0; bull = 0; printf("\nVvedite vashu popitku"); scanf("%d", &j); for (i = 0; i < n; i++) { c[i] = j % 10; j /= 10; } for (i = 0; i < n; i++) { for (o = 0; o < n; o++) { if ((c[i] == a[o]) && (i != o)) { cow++; } if ((c[i] == a[o]) && (i == o)) { bull++; } } } if (bull == n) { printf("Vi otgadali, kolichestvo popitok - %d", p); s = 1; } else { printf("Kolichestvo bikov - %d ", bull); printf("Kolichestvo korov - %d ", cow); s = 0; } } while (s != 1); return 0; }<file_sep>#include <Windows.h> #ifndef _UTILS_H #define _UTILS_H void userInput(char** a, wchar_t** path, HANDLE hf, WIN32_FIND_DATA FindFileData); void output(char** filesName, unsigned long* filesSize, int* filesIndex, int count, long long time); int filesAmount(wchar_t** path, HANDLE hf, WIN32_FIND_DATA FindFileData); void add(unsigned long* copy, int* index, unsigned long* size, int count); int choice(); void fill(HANDLE hf, WIN32_FIND_DATA FindFileData, char** fileNames, unsigned long* sizes); void info(int count, char** fileNames, unsigned long* sizes); void memFree(unsigned long* a, unsigned long* b); void memFreeMulti(char* userStr, char** fileNames, wchar_t* path, unsigned long* sizes, int count); #endif // !_UTILS_H <file_sep>#ifndef _DISPLAY_H #define _DISPLAY_H #include <iostream> #include "receipt.h" using namespace std; namespace dsp { // Кол-во пунктов в меню ////// const int mainmenu = 4; const int menuscanproduct = 2; /////////////////////////////// void StartMenu(); void MainMenu(); void ScanAns(int& ans); void MenuScanAns(int& ans); void Line(string l = "=", int count = 60); void Press2Continue(); }; #endif // !_DISPLAY_H <file_sep>#pragma once #ifndef _BANKI_H #define _BANKI_H #define _CRT_SECURE_NO_WARNINGS typedef struct { char* vkladname; float rate; int times; }vkladstruct; typedef struct { int count; char* bankname; char* banktype; vkladstruct* our_vklad; }bankstruct; char* getfile(); int strcount(char* path); bankstruct** allocbanki(int stringcount); void workfile(bankstruct** banki, char* path, int stringcount); void data_input(int* sumvkl, int* your_month, char* your_type); void choosebest(int sumvkl, int your_month, bankstruct** banki, int stringcount, char* your_type); void freebanki(bankstruct** banki, int stringciunt); #endif<file_sep>#include <iostream> #include <fstream> #include "stars.h" using namespace std; int main() { system("chcp 1251"); string path = read_path(); Constellation_library lib(path); choice(lib); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include "header.h" int cntLines(const char* filename) { int lines = 0; int any; //any типа int, потому что EOF имеет тип int! FILE* f = fopen(filename, "r"); if (f == NULL) { return -1; } do { any = fgetc(f); //printf("%c", any);//debug if (any == '\n') { lines++; } } while (any != EOF); fclose(f); return lines; } void allocate_stock(product** shipment, date** data, int number) { (*shipment) = (product*)malloc(sizeof(product) * number); (*data) = (product*)malloc(sizeof(product) * number); // for(int i = 0; i < number; i++) // shipment->name = (char*)malloc(sizeof(char) * 200); for (int i = 0; i < number; i++) { (*shipment + i)->name = (char*)malloc(sizeof(char) * 200); // printf("addr: %x\n", (*shipment + i)); } for (int i = 0; i < number; i++) { (*shipment + i)->unit = (char*)malloc(sizeof(char) * 200); // printf("addr: %x\n", (*shipment + i)); } } void fill_shipment(product* shipment, date* data, int number) { int flag = 0, j = 0; char str[200], sep[10] = ";"; char* istr; int r; FILE* file; file = fopen("sklad.txt", "r"); while (j != number) { fgets(str, 200, file); istr = strtok(str, ";/"); flag++; if (flag == 1) { strcpy(shipment[j].name, istr); } while (istr != NULL) { istr = strtok(NULL, ";/"); flag++; if (flag == 2) { strcpy(shipment[j].unit, istr); } if (flag == 3) { shipment[j].price = atoi(istr); } if (flag == 4) { shipment[j].number = atoi(istr); } if (flag == 5) { data[j].day = atoi(istr); } if (flag == 6) { data[j].month = atoi(istr); } if (flag == 7) { data[j].year = atoi(istr); } } flag = 0; j++; } } void find_null(product* shipment, date* data, int number) { for (int i = 0; i < number; i++) { if (shipment[i].number == 0) { printf("%s\t", shipment[i].name); printf("%s\t", shipment[i].unit); printf("%.2f\t", shipment[i].price); printf("%d\t", shipment[i].number); printf("%d.%d.%d\n", data[i].day, data[i].month, data[i].year); } } } void free_stock(product** shipment, date** data, int number) { for (int i = 0; i < number; i++) { free((*shipment + i)->name); free((*shipment + i)->unit); } free(*shipment); free(*data); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { char mode; do { printf("Choose game mode: \n1 - you guess number\n2 - you choose number \n"); scanf("%c", &mode); } while (mode != '1' && mode != '2'); if (mode == '1') { short try_count = 1, answer, cur_ans; srand((unsigned int)time(NULL)); answer = rand() % 1000; printf("I chose the number. Try to guess it! (type '1001' for answer) \n"); while (1) { do { printf("What's your guess? \n"); scanf("%hd", &cur_ans); } while (cur_ans < 0 || cur_ans > 1001); if (cur_ans == 1001) { printf("%hd \n", answer); } else if (cur_ans < answer) { printf("This number < than my number. Try again. (Tries: %hd) \n", try_count); try_count++; } else if (cur_ans > answer) { printf("This number > than my number. Try again. (Tries: %hd) \n", try_count); try_count++; } else if (cur_ans == answer) { printf("You're right! You've guessed my number in %hd tries. \n", try_count); return 0; } } } if (mode == '2') { short try_count = 1, cur_ans = 500, step = 250; char reply; printf("I'm going to guess your number. \n"); while (1) { do { printf("Is it %hd? \n", cur_ans); scanf("%c", &reply); } while (reply != '<' && reply != '=' && reply != '>'); if (reply == '=') { printf("Woohoo! I've guessed your number in %hd tries \n", try_count); return 0; } else if (reply == '<') { cur_ans += step; } else if (reply == '>') { cur_ans -= step; } step = (step + 1) / 2; if (step == 0) step = 1; try_count++; } } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> void A2() //computer is guessing (2 digits) { int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, b[2] = { 0 }; int i = 1, n, k = 0, c, d; while ((b[0] == 0) || (b[1] == 0)) { k++; printf("%d%d", (a[i]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); if ((c == 1) && (d == 0)) { b[0] = a[i]; c = 0; d = 0; } else { b[1] = a[i]; c = 0; d = 0; } i++; } printf("%d%d %d", b[0], b[1], k); return 0; } void A3() //3 digits { int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, b[3] = { 0 }; int i = 1, n, k = 0, c, d; while ((b[0] == 0) || (b[1] == 0) || (b[2] == 0)) { k++; printf("%d%d%d", (a[i]), (a[0]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); if ((c == 1) && (d == 0)) { b[0] = a[i]; c = 0; d = 0; } else if ((c == 0) && (d == 1)) { printf("%d%d%d", (a[0]), (a[i]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); k++; if ((c == 1) && (d == 0)) { b[1] = a[i]; c = 0; d = 0; } else { b[2] = a[i]; c = 0; d = 0; } } i++; } printf("%d%d%d %d", b[0], b[1], b[2], k); return 0; } void A4() //4 digits { int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, b[4] = { 0 }; int i = 1, n, k = 0, c, d; while ((b[0] == 0) || (b[1] == 0) || (b[2] == 0) || (b[3] == 0)) { k++; printf("%d%d%d%d", (a[i]), (a[i]), (a[0]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); if ((c == 1) && (d == 0)) { printf("%d%d%d%d", (a[i]), (a[0]), (a[0]), (a[0])); printf("?\n"); k++; scanf("%d%d", &c, &d); if ((c == 1) && (d == 0)) { b[0] = a[i]; c = 0; d = 0; } else { b[1] = a[i]; c = 0; d = 0; } } if ((c == 0) && (d == 1)) { printf("%d%d%d%d", (a[0]), (a[0]), (a[i]), (a[0])); printf("?\n"); k++; scanf("%d%d", &c, &d); if ((c == 1) && (d == 0)) { b[2] = a[i]; c = 0; d = 0; } else { b[3] = a[i]; c = 0; d = 0; } } i++; } printf("%d%d%d%d %d", b[0], b[1], b[2], b[3], k); return 0; } void A5() //5 digits { int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, b[5] = { 0 }; int i = 1, n, k = 0, c, d; while ((b[0] == 0) || (b[1] == 0) || (b[2] == 0) || (b[3] == 0) || (b[4] == 0)) { k++; printf("%d%d%d%d%d", (a[i]), (a[0]), (a[0]), (a[0]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); if ((c == 1) && (d == 0)) { b[0] = a[i]; c = 0; d = 0; } else if ((c == 0) && (d == 1)) { printf("%d%d%d%d%d", (a[0]), (a[i]), (a[0]), (a[0]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); k++; if ((c == 1) && (d == 0)) { b[1] = a[i]; c = 0; d = 0; } else if ((c == 0) && (d == 1)) { printf("%d%d%d%d%d", (a[0]), (a[0]), (a[i]), (a[0]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); k++; if ((c == 1) && (d == 0)) { b[2] = a[i]; c = 0; d = 0; } else if ((c == 0) && (d == 1)) { printf("%d%d%d%d%d", (a[0]), (a[0]), (a[0]), (a[i]), (a[0])); printf("?\n"); scanf("%d%d", &c, &d); k++; if ((c == 1) && (d == 0)) { b[3] = a[i]; c = 0; d = 0; } else if ((c == 0) && (d == 1)) { b[4] = a[i]; c = 0; d = 0; } } } } i++; } printf("%d%d%d%d%d %d", b[0], b[1], b[2], b[3], b[4], k); return 0; } void B(n) //human is guessing { { int a[5] = { 0 }, b[5] = { 0 }, i = 0, ii = 0, k, l, f = 1, n1, n2, bull = 0, cow = 0, tmp = 0; time_t t; srand((unsigned)time(&t)); for (i = 0; i < n; i++) { //generating a number with unique digits do { k = (rand() % 9) + 1; if ((a[0] != k) && (a[1] != k) && (a[2] != k) && (a[3] != k) && (a[4] != k)) { a[i] = k; } } while (a[i] == 0); } for (i = 0; i < n; i++) { //printing that number in case there is a mistake printf("%d", a[i]); } for (i = 0; i < n; i++) { f *= 10; } do { printf("\nenter your guess: "); do { //player is guessing scanf("%d", &l); for (i = n - 1; i >= 0; i--) { b[i] = l % 10; l /= 10; } tmp = 0; for (i = 0; i < n; i++) { for (int kk = i + 1; kk < n; kk++) { if ((b[i] == b[kk]) || (b[kk] == 0)){ tmp = 1; break; } } } if (tmp == 1) { printf("you've entered a wrong number"); } } while (tmp == 1); ii++; for (n1 = 0; n1 < n; n1++) { //checking if there are any bulls or cows for (n2 = 0; n2 < n; n2++) { if ((n1 == n2) && (a[n1] == b[n2])) { bull++; } else if ((n1 != n2) && (a[n1] == b[n2])) { cow++; } } } printf("bulls: %d", bull); printf(", cows: %d\n", cow); if (bull == n) { printf("Bingo! Total attemts count: %d", ii); return 0; } cow = 0; bull = 0; } while (1); } } int main() //player is choosing a game mode { int n, i; printf("chhose a game, 1 or 2: "); do { scanf("%d", &i); } while ((i != 1) && (i != 2)); printf("enter your number's length (2-5): "); do { scanf("%d", &n); } while ((n < 2) && (n > 5)); if (i == 1) { switch (n) { case 2: A2(); return 0; case 3: A3(); return 0; case 4: A4(); return 0; case 5: A5(); return 0; } } else { B(n); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h>; #include "matrix.h" int main() { TMatrix* matrix_dynamic, * m1, * m2, * res; int n; float add; float multi; printf("n = "); scanf("%d", &n); printf("add = "); scanf("%f", &add); printf("multi = "); scanf("%f", &multi); allocate_matrix(&m1, n); allocate_matrix(&m2, n); printf("Enter 1st matrix:\n"); fill_matrix(m1); // 1 2 3 4 5 6 7 8 9 printf("Enter 2nd matrix:\n"); fill_matrix(m2); // 9 8 7 6 5 4 3 2 1 print_matrix(m1); print_matrix(m2); printf("add_matrix:\n"); res = add_matrix(m1, m2); print_matrix(res); free_matrix(&res); printf("add_const:\n"); res = add_const(m1, add); print_matrix(res); free_matrix(&res); printf("multi_matrix:\n"); res = multi_matrix(m1, m2); print_matrix(res); free_matrix(&res); printf("multi_const:\n"); res = multi_const(m1, multi); print_matrix(res); free_matrix(&res); free_matrix(&m1); free_matrix(&m2); return 0; }<file_sep>#include <stdlib.h> //Подключение Библиотек #include <stdio.h> #include <time.h> #define MIN_DIGITS_NUM 2 //Задание размером массива #define MAX_DIGITS_NUM 5 #define NUM_OF_DIGITS 10 void reverse(int n, int* array) { // реверсирование массива int temp; for (int i = 0; i < n / 2; i++) { temp = array[i]; array[i] = array[n - i - 1]; array[n - i - 1] = temp; } } int is_win(int n, int* needed, int* cur) { // проверка, совпадает ли загаданное число с введенным for (int i = 0; i < n; i++) if (needed[i] != cur[i]) return 1; return 0; } int process(int n, int* needed, int cur, int playing) { // выделяем память под введенное число int* recieved = (int*)malloc(n * sizeof(int)); // преобразование числа int в массив for (int i = 0; i < n; i++) { recieved[i] = cur % 10; cur /= 10; } // реверсируем полученный массив reverse(n, recieved); int cows = 0, bulls = 0, i, j; // инициализируем счетчики и итераторы for (i = 0; i < n; i++) // подсчет быков if (needed[i] == recieved[i]) bulls++; else for (j = 0; j < n; j++) // подсчет корова if (needed[i] == recieved[j]) cows++; // Проверка не победили ли if (!is_win(n, needed, recieved)) { printf(" You won!"); return 0; } // Вывод количества быков и коров printf(" There're %d bulls and %d cows\n", bulls, cows); } int read(int n) {//функция считывания числа и проверка на то подходит ли введенное число под критерии n-значного числа. int temp = 0; int c = 0; char ch = 'a'; while (c < n) { ch = getchar(); switch (ch) { case'0': case'1': case'2': case'3': case'4': case'5': case'6': case'7': case'8': case'9': { temp = temp * 10 + atoi(&ch); c++; break; } } } return temp; } void shuffle(int* array) { // перемешивает массив // устанавливаем текущее время в качестве семени для генератора псевдослучайных чисел srand(time(NULL)); int j, temp; for (int i = NUM_OF_DIGITS - 1; i >= 1; i--) { // выбираем случайной индекс, не превосходящий i j = rand() % (i + 1); // меняем значения в массиве местами temp = array[j]; array[j] = array[i]; array[i] = temp; } } void check(int* array) { // перемешивает массив // устанавливаем текущее время в качестве семени для генератора псевдослучайных чисел int j, temp; for (int i = NUM_OF_DIGITS - 1; i >= 1; i--) { // выбираем случайной индекс, не превосходящий i j = rand() % (i + 1); // меняем значения в массиве местами temp = array[j]; array[j] = array[i]; array[i] = temp; } } int* gen(int n) { // генерирует случайное число-массив заданной длинны int digits[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // перемешиваем созданный выше массив до тех пор, пока первая цифра не будет отлична от нуля do shuffle(digits); while (digits[0] == 0); // чтобы вернуть результат, создаем указатель на массив, выделяем под него память int* result = (int*)malloc(n * sizeof(int)); // переписываем в result полученный перемешанный массив for (int i = 0; i < n; i++) result[i] = digits[i]; return result; } int introduction() {//Вступление int n = 0; printf(" ==================== BULLS & COWS ====================\n\n"); printf(" You have to quess the num I've made. You should tell\n"); printf(" me how many digits there'll be in the made num (2 - 5)\n"); printf(" Number length: "); while (1) { //Бесконечный цикл // считываем длину числа scanf("%d", &n); // проверяем на корректность if (n >= 2 && n <= 5) { printf("\n"); printf(" I've made the num with length of %d. Try to quess it!\n", n); return n; } printf("\n Something went wrong, try again!"); } } void main() { int n = introduction(); int* num = gen(n); int playing = 1, cur; while (playing) { // цикл игры cur = read(n); // считываем пользовательское число playing = process(n, num, cur, playing); // обрабатываем if (!playing) { // предлагаем сыграть снова, обрабатываем ответ printf("\n\n Do you want to play again?\n 1 - play again\n 0 - exit\n\n "); scanf("%d", &playing); if (playing) { system("cls");//чистка визуала n = introduction(); num = gen(n); } } } printf("\n\n\n"); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include "stars.h" int main() { system("chcp 1251"); Constellation* constellations; int cns_count; read_data(&constellations, &cns_count); cnst_table(constellations, cns_count); choice(constellations, cns_count); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h>; #include "matrix.h" #define _CRT_SECURE_NO_WARNINGS int main() { main_action(); return 0; }<file_sep>#include <stdio.h> #include <math.h> #include <locale.h> int main() { setlocale(LC_ALL, "Russian"); int x1, y1, r1, x2, y2, r2; double distance; printf("Введите координаты центра и радиус первой окружности: "); scanf_s("%i%i%i", &x1, &y1, &r1); printf("Введите координаты центра и радиус второй окружности: "); scanf_s("%i%i%i", &x2, &y2, &r2); distance = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); if (x1 == x2 && y1 == y2 && r1 == r2) printf("Совпадают полностью"); else if (distance < r1 - r2 || distance < r2 - r1) printf("Не пересекаются"); else if (distance == r1 + r2) printf("Внешнее касание"); else if (distance == r1 - r2 || distance == r2 - r1) printf("Внутреннее касание"); else if (distance > r1 + r2) printf("Не пересекаются"); else if (distance < r1 + r2) printf("Пересекаются в 2 точках"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> int main() { int a[5] = { 0 }, b[5] = { 0 }, i = 0, ii = 0, n = 0, k, tmp, l, f = 1, n1, n2, bull = 0, cow = 0; time_t t; srand((unsigned)time(&t)); printf("vvedite dlinu chisla: "); do { scanf("%d", &n); } while ((n < 2) && (n > 5)); for (i = 0; i < n; i++) { do { k = (rand() % 9) + 1; if ((a[0] != k) && (a[1] != k) && (a[2] != k) && (a[3] != k) && (a[4] != k)) { a[i] = k; } } while (a[i] == 0); } for (i = 0; i < n; i++) { printf("%d", a[i]); } for (i = 0; i < n; i++) { f *= 10; } do { do { printf("\nvvedite svou dogadky: "); do { scanf("%d", &l); } while ((l < f) && (l > 10 * f - 1)); for (i = n - 1; i >= 0; i--) { b[i] = l % 10; l /= 10; } tmp = 0; for (i = 0; i < n; i++) { for (int k1 = i + 1; k1 < n; k1++) { if ((b[i] == b[k1]) || (b[k1] == 0)) { tmp = 1; break; } } } if (tmp == 1) { printf("wrong number"); } } while (tmp == 1); ii++; for (n1 = 0; n1 < n; n1++) { for (n2 = 0; n2 < n; n2++) { if ((n1 == n2) && (a[n1] == b[n2])) { bull++; } else if ((n1 != n2) && (a[n1] == b[n2])) { cow++; } } } printf("bulls: %d", bull); printf(", cows: %d\n", cow); if (bull == n) { printf("ugadal! kol-vo popytok: %d", ii); return 0; } cow = 0; bull = 0; } while (1); } <file_sep>#ifndef _WORKERS_H #define _WORKERS_H #include <string> using namespace std; class worker { private: string id; string profession; string education; string last_job; string rsn_dismiss; string family_status; int contact_info; public: worker(); worker(const string id,const string profession,const string education,const string last_job,const string rsn_dismiss,const string family_status,int contact_info); friend ostream& operator<<(ostream& out, const worker& w); void adding(string _id, string _profession, string _education, string last_job, string _rsn_dismiss, string _family_status, int contact_info); string get_education(); }; class labor { private: worker* w; int n; int amount(const string& path); public: labor(const string& path); float higher_education(); ~labor(); }; string get_path(); #endif <file_sep>#include "lib.h" int main() { string path = menu(); lib library(path); set <string> sections = library.booksBySection(); vector <cardIndex> books = library.findBooks(sections); library.getBook(books); return 0; } <file_sep>#ifndef _Star #define _Star struct Star { std::string name; float dist; float magnitude; float deg; float min; float sec; Star& operator=(const Star& obj); }; class Constellation { public: Constellation(std::string Cname, int n); Constellation() { count = 0; name = ""; stars = nullptr; }; ~Constellation(); int getCount() const { return count; } std::string getName() { return name; } friend std::ostream& operator<< (std::ostream& out, const Constellation* cns); friend std::istream& operator>> (std::istream& in, const Constellation* cns); Constellation& operator=(const Constellation& obj); private: int count; std::string name; Star* stars; }; class Constellation_library { public: Constellation_library(std::string& path); ~Constellation_library(); int getCount() const { return count; } Constellation* getCns(int n) const { return &cns[n]; } friend std::ostream& operator<< (std::ostream& out, const Constellation_library& lib); private: Constellation* cns; int count; }; std::string read_path(); void choice(Constellation_library* lib); #endif <file_sep>#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <locale.h> #include <stdlib.h> #include <time.h> #define N 5 #define K 10 int main() { int len, i, tmp, number, d, j, f, k, TryNumber, bulls, cows, LIMIT, AR[N] = { 0 }, arr[N] = { 0 }, chekar[K] = { 0 }; srand((unsigned int)time(NULL)); printf("Choose the length of the number (from 2 to 5): \n"); do { scanf("%d", &len); if ((len > 5) || (len < 2)) { printf("Incorrect number entered. Try again: \n"); } } while ((len > 5) || (len < 2)); arr[0] = 1 + (rand() % 9); for (i = 1; i < len; i++) { f = 1; while (1) { d = rand() % 10; f = 1; for (j = 0; j < i; j++) { if (arr[j] == d) { f = 0; break; } } if (f == 1) { arr[i] = d; break; } } } d = 1; number = 0; for (i = len - 1; i >= 0; i--) { number = number + arr[i] * d; d = d * 10; } bulls = 0; while ( bulls != len ) { printf("Try to guess the number: \n"); do { scanf("%d", &TryNumber); f = 1; LIMIT = 0; tmp = TryNumber; while (tmp > 0) { tmp /= 10; LIMIT++; } if (LIMIT!=len) { printf("Incorrect number entered. Try again: \n"); } tmp = TryNumber; for (i = 0; i < len; i++) { k = tmp % 10; chekar[k]++; tmp /= 10; } for (i = 0; i < K; i++) { if (chekar[i] > 1) { f = 0; break; } } if (f == 0) { printf("Enter a number with different digits \n"); } for (i = 0; i < K; i++) { chekar[i] = 0; } } while ((LIMIT!=len) || (f == 0)); i = len - 1; while (TryNumber > 0) { AR[i] = TryNumber % 10; TryNumber = TryNumber / 10; i--; } bulls = 0; cows = 0; for (i = 0; i < len; i++) { if (arr[i] == AR[i]) { bulls++; } } for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { if ( ( arr[i] == AR[j] ) && (i != j) ) { cows++; } } } printf("Number of bulls: %d. Number of cows: %d\n", bulls, cows); } printf("Congratulations!"); return 0; }<file_sep>#ifndef _HEADER_H #define _HEADER_H using namespace std; struct date { int day; int month; int year; void create_data(string str); const date& operator= (const date& e); }; struct pasport { int series; int number; string auth; string reg; date issue; date birth; bool isElderly(); void create_data(string* str); const pasport& operator= (const pasport& e); }; struct employee { pasport pspt; string name; string edu; string spec; string unit; string appnt; date dateofappnt; date lastdate; void create_data(string str); const employee& operator= (const employee& e); }; struct lib { int emp_amount; employee* empls; lib(int n); lib(const lib& l); lib(const string& filename); ~lib(); employee& operator[](int ind); friend ostream& operator<<(ostream& out, const lib& l) { for (int i = 0; i < l.emp_amount; i++) out << l.empls[i].name << " - " << l.empls[i].pspt.birth.day << "." << l.empls[i].pspt.birth.month << ".19" << l.empls[i].pspt.birth.year << endl; return out; } lib output(); }; string get_string(ifstream& file); #endif //!_HEADER_H<file_sep>#ifndef _MATRIX_H #define _MATRIX_H typedef struct { int n; double** x; } TMatrix; void alloc_matrix(TMatrix** matrix, int n); void free_matrix(TMatrix** matrix); void fill_matrix(TMatrix* matrix); void print_matrix(TMatrix* matrix); TMatrix* add_scalar(TMatrix* matrix, double c); TMatrix* multi_scalar(TMatrix* matrix, double c); TMatrix* add_matrix(TMatrix* v1, TMatrix* v2); TMatrix* multi_matrix(TMatrix* m1, TMatrix* m2); #endif <file_sep>#pragma once //#ifndef _actionh_ //#define _actionh_ #include <string> #include <ostream> #include <istream> using namespace std; void output(); struct team { string Name; string City; int Games; int Points; int Players; team(string Name, string City, int Games, int Points, int Players) { this->Name = Name; this->City = City; this->Games = Games; this->Points = Points; this->Players = Players; } team() : team("", "", 0, 0, 0) { } }; ostream& operator<< (ostream& stream, const team& team) { stream << team.Name << endl << team.City << endl << team.Games << endl << team.Points << endl << team.Players << endl; return stream; } istream& operator>> (istream& stream, team& team) { stream >> team.Name >> team.City >> team.Games >> team.Points >> team.Players; return stream; } struct teamarray { team* teams; size_t length; ~teamarray() { if (teams != nullptr) { delete[] teams; } } }; //#endif<file_sep>#include "Container.h" #include "Receipt.h" #ifndef _CLIENTSIDE_H #define _CLIENTSIDE_H void work_with_client(TProductsDatabase& db); void create_updating_db(TProductsDatabase& db); #endif
dd72771d19f884584ef75e24e9f3ed4142abf10c
[ "Markdown", "C", "CMake", "C++" ]
381
C
valentina-kustikova/mp1-practice
f2032199f7d6008067843d50cd65af5a880967b6
a62f5e5eb9bbfd739c320d9049a00031ee426c9c
refs/heads/gh-pages
<repo_name>PulseTile/PulseTile-Docs<file_sep>/images/ui-patterns/readme.md For images on articles about UI patterns <file_sep>/pages/react-admin/plugin-tiles/react-admin-events.html --- title: Events module keywords: sample summary: "Events module" sidebar: react_admin_sidebar permalink: react-admin-events.html folder: react-admin/plugin-tiles filename: react-admin-events.html --- <h4>General information</h4> <p> Events is a non-core plugin of PulseTile-RA. It is used to create, edit and review information about Events of the current patient. Actions, Reducer and Sagas required for the Events plugin are created automatically by React-Admin framework, because all operations are typical. </p> <h4> <a href="https://github.com/PulseTile/PulseTile-RA/blob/showcase/src/version/plugins/Events/EventsList.js" target="_blank">Events List</a> </h4> {% include image.html file="react-admin/events/eventsgeneral.png" url="#" alt="Events List" caption="Events List" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events </pre> <h5>GET response</h5> <pre> { dateCreated: 1454669420000, dateTime: 1452595820958, description: "Complications following surgery", name: "Transfer from ward to ICU", source: "ethercis", sourceId: "ethercis-be7d9647-3c6e-41dd-a1c9-4aaa0c60c81b", type: "Transfer", } </pre> <h5>Component structure</h5> <pre> import React from "react"; import { DateField, TextField } from "react-admin"; import ListTemplate from "../../../core/common/ResourseTemplates/ListTemplate"; import EventsCreate from "./EventsCreate"; import EventsEdit from "./EventsEdit"; import EventsShow from "./EventsShow"; import EventsTimeline from "./EventsTimeline"; import DatagridRow from "./fragments/DatagridRow"; const EventsList = ({ classes, ...rest }) => ( &lt;ListTemplate create={EventsCreate} edit={EventsEdit} show={EventsShow} resourceUrl="events" title="Events" hasTimetable={true} timelineBlock={EventsTimeline} CustomRow={DatagridRow} isCustomDatagrid={true} {...rest} > &lt;TextField label="Event Name" source="noteType" /> &lt;TextField label="Event Type" source="author" /> &lt;DateField label="Date" source="dateCreated" /> &lt;/ListTemplate> ); export default EventsList; </pre> <h4><a href="https://github.com/PulseTile/PulseTile-RA/blob/showcase/src/version/plugins/Events/EventsShow.js" target="_blank">Event Detail</a></h4> {% include image.html file="react-admin/events/eventsdetail.png" url="#" alt="Event Detail" caption="Event Detail" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events/{sourceId} </pre> <h5>GET response</h5> <pre> { author: "Dr. Smith", dateCreated: 1563464410000, dateTime: 1563447600000, description: "Needs nursing and supervisory care", name: "Discharge to care home", source: "ethercis", sourceId: "ethercis-bec0e163-6a1f-4f7a-bb13-1e1d5110b62e", type: "Discharge", } </pre> <h5>Component structure</h5> <pre> import React from "react"; import { TextField, DateField } from "react-admin"; import { withStyles } from '@material-ui/core/styles'; import ShowTemplate from "../../../core/common/ResourseTemplates/ShowTemplate"; const EventsShow = ({ classes, ...rest }) => ( &lt;ShowTemplate pageTitle="Event" {...rest}> &lt;TextField source="name" label="Event Name" /> &lt;TextField source="type" label="Event Type" /> &lt;TextField source="description" label="Notes" /> &lt;DateField source="dateTime" label="Event Date" showTime /> &lt;/ShowTemplate> ); export default withStyles(styles)(EventsShow); </pre> <h4><a href="https://github.com/PulseTile/PulseTile-RA/blob/showcase/src/version/plugins/Events/EventsEdit.js" target="_blank">Event Edit Page</a></h4> {% include image.html file="react-admin/events/eventsedit.png" url="#" alt="Event Edit" caption="Event Edit" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events/{sourceId} </pre> <h5>PUT data</h5> <pre> { author: "Dr. Smith", dateCreated: 1563464410000, dateTime: "2019-07-18T11:00:00.000Z", description: "Needs nursing and supervisory care", id: "ethercis-bec0e163-6a1f-4f7a-bb13-1e1d5110b62e", name: "Discharge to care home", source: "ethercis", type: "Discharge", userId: "9999999801", } </pre> <h5>Component structure</h5> <pre> import React from "react"; import EditTemplate from "../../../core/common/ResourseTemplates/EditTemplate"; import Form from "./fragments/Form"; const EventsEdit = props => ( &lt;EditTemplate isCustom={true} blockTitle="Event" {...props}> &lt;Form {...props} /> &lt;/EditTemplate> ); export default EventsEdit; </pre> <h4><a href="https://github.com/PulseTile/PulseTile-RA/blob/showcase/src/version/plugins/Events/EventsCreate.js" target="_blank">Event Create Page</a></h4> {% include image.html file="react-admin/events/eventscreate.png" url="#" alt="Event Create" caption="Event Create" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events </pre> <h5>POST data</h5> <pre> { author: "<NAME>", dateCreated: 1563966657000, dateTime: "2019-07-02T10:45:00.000Z", description: "Test", name: "Test", type: "Appointment", userId: "9999999801", } </pre> <h5>Component structure</h5> <pre> import React from "react"; import CreateTemplate from "../../../core/common/ResourseTemplates/CreateTemplate"; import Form from "./fragments/Form"; const EventsCreate = props => ( &lt;CreateTemplate isCustom={true} blockTitle="Event" {...props}> &lt;Form isCreate={true} {...props} /> &lt;/CreateTemplate> ); export default EventsCreate; </pre> <h4><a href="https://github.com/PulseTile/PulseTile-RA/blob/showcase/src/version/plugins/Events/EventsTimeline.js" target="_blank">Events Timeline</a></h4> <p> Events timeline presents a list of events for current patient, displayed as timeline. It can be open by selecting "Event Timeline" in the right corner of the Events list block. Events timeline use the same GET-request, which is used in Events table. </p> {% include image.html file="react-admin/events/eventswitcher.png" url="#" alt="Event Timeline Switcher" caption="Event Timeline Switcher" %} {% include image.html file="react-admin/events/eventstimeline.png" url="#" alt="Event Create" Timeline="Event Timeline" %} <pre> import React from "react"; import _ from "lodash"; import get from "lodash/get"; import moment from "moment"; import { connect } from 'react-redux'; import { Toolbar } from "react-admin"; import { Timeline, Content, ContentYear, ContentBody, } from 'vertical-timeline-component-react'; import { withStyles } from "@material-ui/core/styles"; import Typography from "@material-ui/core/Typography"; import CreateButton from "../../../core/common/Buttons/CreateButton"; const styles = theme => ({ ... ... ... }); const CustomHeader = ({ classes, items, history }) => { const dateAndTime = items[0]; const events = items[1]; const dateForPoint = moment.unix(dateAndTime).format('Do MMM') return ( &lt;Content> &lt;ContentYear year={&lt;EventDate classes={classes} label={dateForPoint} />} /> &lt;ContentBody> { events.map(item => { let eventRoute = '/events/' + get(item, 'sourceId', null); let dateTime = moment(get(item, 'dateTime', null)).format('DD-MM-YYYY HH:mm'); return ( &lt;div className={classes.eventBlock} onClick={() => history.push(eventRoute)}> &lt;Typography variant="body1" className={classes.eventType}>{get(item, 'type', null)}&lt;/Typography> &lt;div className={classes.eventDescription}> &lt;Typography className={classes.eventTitle} variant="h1">{get(item, 'name', null)}&lt;/Typography> <&lt;Typography variant="caption">{dateTime}&lt;/Typography> &lt;/div> &lt;/div> ) }) } &lt;/ContentBody> &lt;/Content> ); }; const EventDate = ({ classes, label }) => { const dateArray = label.split(' '); return ( &lt;div className={classes.eventDate}> &lt;Typography variant="body1">{dateArray[0]}&lt;/Typography> &lt;Typography variant="body1">{dateArray[1]}&lt;/Typography> &lt;/div> ) } const EventsTimeline = ({ classes, eventsList, history, createUrl }) => { const eventsGroupByDate = _.mapValues(_.groupBy(eventsList, 'dateCreated'), clist => clist.map(event => _.omit(event, 'date'))); const eventsGroupByDateArray = Object.entries(eventsGroupByDate); return ( &lt;React.Fragment> &lt;div className={classes.timeline}> &lt;Timeline> { eventsGroupByDateArray.map(item => { return ( &lt;CustomHeader classes={classes} items={item} history={history} /> ) })} &lt;Content> &lt;ContentYear /> &lt;/Content> &lt;/Timeline> &lt;/div> { createUrl && &lt;Toolbar className={classes.toolbar}> &lt;CreateButton history={history} redirectPath={createUrl} /> &lt;/Toolbar> } &lt;/React.Fragment> ); }; const mapStateToProps = state => { return { eventsList: get(state, 'admin.resources.events.data', []), }; }; export default connect(mapStateToProps, null)(withStyles(styles)(EventsTimeline)); </pre><file_sep>/pages/angular/plugin-tiles/angular-mdt-JSON.md --- title: JSON Array MDT keywords: MDT summary: "JSON for MDT module" sidebar: angular_sidebar permalink: angular-mdt-JSON.html folder: angular/plugin-tiles filename: angular-mdt-JSON.html --- Sample JSON data array for MDT (MultiDisciplinaryTeams) module. ``` { sourceId: "5836b208-160f-4925-b2b1-a26626432940", source: "marand", serviceTeam: "TEAM", dateOfRequest: 1455062400000, dateOfMeeting: 1454979600000 }, { sourceId: "712ca27b-e051-46d3-ba92-0670e65cc790", source: "marand", serviceTeam: "skin cancer", dateOfRequest: 1448755200000, dateOfMeeting: 1447427700000 }, ``` <file_sep>/pages/angular/plugin-tiles/angular-personal-notes-JSON.md --- title: JSON Array Personal Notes keywords: Personal Notes summary: "JSON for Personal Notes module" sidebar: angular_sidebar permalink: angular-personal-notes-JSON.html folder: angular/plugin-tiles filename: angular-personal-notes-JSON.md --- Sample data source for Personal Notes module as a JSON array. ``` { sourceId: "23dbda9d-7688-426c-8cb8-312a4f351071", source: "ethercis", noteType: "Personal Notes", author: "Dr <NAME>", dateCreated: 1456287062000 }, { sourceId: "b6c198be-2c37-4494-89c3-4fc5a7a92eff", source: "ethercis", noteType: "Personal Note", author: "Dr <NAME>", dateCreated: 1482196404000 }, ``` <file_sep>/pages/react/plugin-tiles/react-vitals-JSON.md --- title: JSON array Vitals NEWS keywords: MDT summary: "JSON for Vitals module" sidebar: react_sidebar permalink: react-vitals-JSON.html folder: react/plugin-tiles filename: react-vitals-JSON.md --- The example JSON object used to dummy the data within Vitals module ``` vitals = [ { sourceId: '1', seriesNumber: 1, source: 'Marand', author: 'ripple_osi', dateCreate: Date.parse(new Date()), vitalsSigns: { respirationRate: { value: 25, status: 'warning' }, oxygenSaturation: { value: 97, status: 'danger' }, oxygenSupplemental: { value: 'N' }, systolicBP: { value: 90, status: 'danger' }, distolicBP: { value: 60, status: 'danger' }, heartRate: { value: 45, status: 'success' }, temperature: { value: 35.4, status: 'success' }, levelOfConsciousness: { value: 'A' }, newsScore: { value: 3, status: 'danger' } } }, { sourceId: '2', seriesNumber: 2, source: 'EtherCIS', author: 'ripple_osi', dateCreate: Date.parse(new Date(date.setDate(date.getDate()-1))), vitalsSigns: { respirationRate: { value: 29, status: 'warning' }, oxygenSaturation: { value: 115, status: 'success' }, oxygenSupplemental: { value: 'N' }, systolicBP: { value: 60, status: 'warning' }, distolicBP: { value: 78, status: 'warning' }, heartRate: { value: 99, status: 'danger' }, temperature: { value: 36.6, status: 'success' }, levelOfConsciousness: { value: 'B' }, newsScore: { value: 3 } } }, { sourceId: '3', seriesNumber: 3, source: 'Marand', author: 'ripple_osi', dateCreate: Date.parse(new Date(date.setDate(date.getDate()-4))), vitalsSigns: { respirationRate: { value: 35, status: 'danger' }, oxygenSaturation: { value: 69, status: 'warning' }, oxygenSupplemental: { value: 'N' }, systolicBP: { value: 92, status: 'warning' }, distolicBP: { value: 69, status: 'warning' }, heartRate: { value: 74, status: 'danger' }, temperature: { value: 39.9, status: 'success' }, levelOfConsciousness: { value: 'C' }, newsScore: { value: 2, status: 'warning' } } }, { sourceId: '4', seriesNumber: 4, source: 'EtherCIS', author: 'ripple_osi', dateCreate: Date.parse(new Date(date.setDate(date.getDate()-5))), vitalsSigns: { respirationRate: { value: 25, status: 'success' }, oxygenSaturation: { value: 97, status: 'success' }, oxygenSupplemental: { value: 'N' }, systolicBP: { value: 93, status: 'success' }, distolicBP: { value: 63, status: 'success' }, heartRate: { value: 45, status: 'success' }, temperature: { value: 40.0, status: 'success' }, levelOfConsciousness: { value: 'D' }, newsScore: { value: 1, status: 'success' } } }, ]; ``` <file_sep>/pages/angular/plugin-tiles/angular-vitals.html --- title: Vitals module keywords: sample summary: "Vitals module" sidebar: angular_sidebar permalink: angular-vitals.html folder: angular/plugin-tiles filename: angular-vitals.html --- <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/vitals/vitals-list.component.js">Vitals List</a></h4> {% include image.html file="vitals/vitalslist.png" url="#" alt="Vitals list view" caption="Vitals List" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/vitalsigns </pre> <h5>GET response</h5> <pre> { author:"Dr <NAME>" dateCreate:1438572182000 diastolicBP:"64.0" heartRate:"45.0" levelOfConsciousness:"Alert" newsScore:12 oxygenSaturation:"97.0" oxygenSupplemental:"true" respirationRate:"23.0" source:"ethercis" sourceId:"27ee5e25-4c32-46d2-b45a-f74149d72030" systolicBP:"92.0" temperature:35.4 } </pre> <h5>Component structure</h5> <pre> //component template let templateVitalsList = require('./vitals-list.html'); //controller init class VitalsListController { constructor($scope, $state, $stateParams, $ngRedux, vitalsActions, serviceRequests, usSpinnerService, $window, $timeout, serviceVitalsSigns, serviceFormatted) { } //component init const VitalsListComponent = { template: templateVitalsList, controller: VitalsListController }; //inject services/modules to controller VitalsListController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'vitalsActions', 'serviceRequests', 'usSpinnerService', '$window', '$timeout', 'serviceVitalsSigns', 'serviceFormatted']; //es6 export for component export default VitalsListComponent; </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/vitals/vitals-detail.component.js">Vitals Detail</a></h4> {% include image.html file="vitals/vitalsdetail.png" url="#" alt="Vitals Detail" caption="Vitals Detail" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/vitalsigns/{sourceId} </pre> <h5>GET response</h5> <pre> { author:"Dr <NAME>" dateCreate:1438553462518 diastolicBP:60 heartRate:45 levelOfConsciousness:"Alert" newsScore:12 oxygenSaturation:97 oxygenSupplemental:"false" respirationRate:25 source:"Marand" sourceId:"2f4dff89-a41b-465b-85b6-b81d8a59e7a0" systolicBP:90 temperature:35.4 } </pre> <h5>Component structure</h5> <pre> //component template let templateVitalsDetail = require('./vitals-detail.html'); //controller init class VitalsDetailController { constructor($scope, $state, $stateParams, $ngRedux, patientsActions, vitalsActions, serviceRequests, usSpinnerService, serviceVitalsSigns) { } //component init const VitalsDetailComponent = { template: templateVitalsDetail, controller: VitalsDetailController }; //inject services/modules to controller VitalsDetailController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'patientsActions', 'vitalsActions', 'serviceRequests', 'usSpinnerService', 'serviceVitalsSigns']; //es6 export for component export default VitalsDetailComponent; </pre> {% include image.html file="vitals/vitalsedit.png" url="#" alt="Vitals Edit" caption="Vitals Edit" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/vitalsigns </pre> <h5>GET response</h5> <pre> { author:"Dr <NAME>" dateCreate:1491571062000 diastolicBP:60 heartRate:45 levelOfConsciousness:"Pain" newsScore:11 oxygenSaturation:97 oxygenSupplemental:false respirationRate:25 source:"Marand" sourceId:"2f4dff89-a41b-465b-85b6-b81d8a59e7a0" systolicBP:90 temperature:35.4 } </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/vitals/vitals-create.component.js">Vitals Create</a></h4> {% include image.html file="vitals/vitalscreate.png" url="#" alt="Vitals Create" caption="Vitals Create" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/vitalsigns </pre> <h5>POST response</h5> <pre> { author:"ripple_osi" dateCreate:1491571176000 diastolicBP:"77" heartRate:"55" levelOfConsciousness:"Verbal" newsScore:16 oxygenSaturation:"33" oxygenSupplemental:true respirationRate:"33" systolicBP:"88" temperature:"88" } </pre> <h5>Component structure</h5> <pre> //component template let templateVitalsCreate = require('./vitals-create.html'); //controller init class VitalsCreateController { constructor($scope, $state, $stateParams, $ngRedux, patientsActions, vitalsActions, serviceRequests, serviceVitalsSigns) { } //component init const VitalsCreateComponent = { template: templateVitalsCreate, controller: VitalsCreateController }; //inject services/modules to controller VitalsCreateController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'patientsActions', 'vitalsActions', 'serviceRequests', 'serviceVitalsSigns']; //es6 export for component export default VitalsCreateComponent; </pre> {% include image.html file="vitals/vitalscharts.png" url="#" alt="Vitals Create" caption="Vitals Chart" %} {% include image.html file="vitals/vitalschartdetail.png" url="#" alt="Vitals Create" caption="Vitals Chart Detail" %} <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/vitals/vitals-actions.js">Vitals Actions</a></h4> <h5>Component structure</h5> <pre> //es6 import modules import {bindActionCreators} from 'redux'; import * as types from '../../../constants/ActionTypes'; //es6 export function export function all(patientId) { return { types: [types.VITALS, types.VITALS_SUCCESS, types.VITALS_ERROR], shouldCallAPI: (state) => !state.vitals.response, config: { method: 'get', url: '/api/patients/' + patientId + '/vitalsigns' }, meta: { timestamp: Date.now() } }; } </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/vitals/vitals-reducer-all.js">Vitals Reducer</a></h4> <h5>Component structure</h5> <pre> //es6 import modules import * as types from '../../../constants/ActionTypes'; const INITIAL_STATE = { isFetching: false, error: false, data: null, dataGet: null, dataCreate: null, dataUpdate: null }; //es6 export function export default function vitals(state = INITIAL_STATE, action) { const {payload} = action; //redux action for Vitals requests var actions = { [[types.VITALS]: (state) => { return Object.assign({}, state, { isFetching: true, error: false }); } </pre> <file_sep>/pages/react/core-tiles/react-patient-lists-JSON.md --- title: JSON Array Patient list keywords: Patient Lists summary: "JSON for Patient Lists" sidebar: react_sidebar permalink: react-patient-lists-JSON.html folder: core-tiles filename: react-patient-lists-JSON.md --- Sample JSON array for an element of patient's list (MPV) - single patient. ``` 9999999000: { address: "6948 Et St., Halesowen, Worcestershire, VX27 5DV", dateOfBirth: -806976000000, department: "Neighbourhood", gender: "Male", gpAddress: "Hamilton Practice, 5544 Ante Street, Hamilton, Lanarkshire, N06 5LP", gpName: "<NAME>.", id: "9999999000", name: "<NAME>", nhsNumber: "9999999000", pasNo: "352541", phone: "(011981) 32362" }, ``` <file_sep>/pages/react/plugin-tiles/react-pluginsQA.md --- title: Plugins keywords: plugins summary: "Approach being taken with Plugins" sidebar: react_sidebar permalink: react-pluginsQA.html folder: react/plugin-tiles filename: react-pluginsQA.md --- ### Contract **Q: What is a plugin expected to provide?** **A:** The plugins expected will fall into 3 main categories: - Single Patient View (SPV) - Multi-Patient View (MPV) - Charts There are no specifications for other, more complex plugins that could be created, except to follow the Ripple UI style guide. *** **Q: What does a plugin expect the core code to provide for it (if anything)? E.g. UserService** **A:** All of the basic frontend functionality and API access that will serve as a data source for plugin to work with. *** **Q: How will versioning work if a plugin relies on core functionality, such as the UserService?** **A:** t seems that right now, versioning isn't a main concern. However, thought should be given to how to: - Update a local version of a plugin to a new version (is the plugin code separate from localisations) - Store a plugin version (separate GitHub repo for v1, v2, etc) - How to handle breaking changes for adopters of the plugin who want the latest minor version (e.g. update from v1.2.3 to v1.3.0) *** **Q: What are the guidelines for the scope of what a plugin can achieve? For example, must they follow the core guideline of list view and details view? Are they allowed to interfere with any code relating to the core UI (e.g. sidebar or header bar)?** **A:** Plugins should follow the guidelines for list and details views in order to keep every developed module with the same structure. If it's a simple module (like Allergies) – no, but if it's more complex (global) module it definitely can affect the core UI ### Loading _This relates to exactly how a plugin is taken from an external repository and actually plugged into the system. Anything from the current architecture of a plugin, to how they are loaded, to how they can be extended should be discussed here._ **Q: It looks as though there are placeholders for plugins which do not have any functionality in core, for example Transfer of Care has a sidebar location even when the plugin hasn’t been loaded, so it doesn’t work until the plugin is imported. Is this the intended extension mechanism - i.e. a placeholder in the sidebar that can be plugged into as opposed to a more dynamic solution where plugins are discovered?** **A:** This does provide a technical challenge, and it's uncertain how this will be achieved. What's clear is that we shouldn't be introducing another "home made" utility that becomes another aspect of the solution that requires support, so long as there is a useful alternative already available. *** **Q: How are the localisations stored?** **A:** This comes back to the "separation of concerns" point raised in the contracts section. If a plugin functionality is separate from localisations, then updates of a plugin become easier, and wouldn't require deleting/moving edits to a module to the newly copied version. Perhaps more thought is required here to determine how much of a hindrance it would be to have this separation. *** **Q: Is a plugin downloaded in raw form and changed locally to fit the local system, and then committed in its entirety? If so, it is a manual effort to upgrade a plugin to a new version.** **A:** At the moment we are importing the plugins from the plugins GitHub repository. This is fine for now, but we should be moving towards a centralized store of versioned plugins you can import a particular historic version/revision of a plugin that has been lost in the GitHub commit history. This is covered further in the Build section. ### Build _This part of the discussion is based on questions regarding the build of the UI. This is separate from a local build using npm start or npm run build. Instead, this relates to automated build processes and being able to ensure the build quality._ **Q: How will the project be tested to ensure that plugins work with the core code? For example, how can we ensure that Component A works with Core UI, and also how could we ensure that Component B works with Component A?** **A:** Adding a good deal of unit tests will help to alleviate this concern. However, it will be difficult to automate the importing of plugins and testing how they interact with the core UI. A possible workaround is to have a big Ripple-based child project with all the plugins imported, allowing for automated tools to carry out rigorous testing of the whole suite of components. *** **Q: How can this testing be transferred to an automated build system? For example, how can a system like Bamboo determine that plugins work with the core UI codebase? This is related to concepts of versioning and expected contracts between plugins and core.** **A:** Excellent. We currently use Bamboo, so we'd like to be able to make use of that system. This is so that we can keep all the build statistics in one place, and not have separate environments trying to achieve the same thing but in different places. ### Release _Here we shall discuss the publishing of developed plugins. We should be discussing topics such as where to store the built version of a Ripple plugin, how it should be built, and the management of it._ **Q: What is the plan for publishing plugins?** **A:** The SliceArt team and Tony are to discuss this further in order to try to come up with a useful way to publish artifacts to a centralised repository. *** **Q: Where will they be stored?** **A:** Unclear at the moment, but the conversation has begun. *** **Q: How will versioning of the code and published plugin(s) be managed?** **A:** First of all, we should verify that module works with the core application functionality and only after this we notify users in some way that this can be used. *** **Q: How will versions of plugins align with the version of the core UI?** **A:** If the core module is updated significantly, everything that could be overwritten is index files, where the other modules are included. So, if someone is working directly with some module (not core module) the local additions will not be affected. If the core module update will affect the 'includes-containing' files (`plugins.config.js`), the locally edited modules probably should be re-included into the application. ### Configuration _This relates to external configuration of a plugin. This configuration may come in the form of parameters that can be read from an external file which relate to functionality of the plugin itself. For instance, a core plugin may be generic enough to work for all instances of the UI, but may require some configuration so that each instance can have the functionality vary slightly to suit their needs._ **Q: Is configuration of components possible? For example, configuration of behaviour of a component, such as the header search bar.** **A:** It was discussed that configuration of components should be only for display purposes and the like, for example the patient dashboard and the header tables that are displayed. Core functionality shouldn't be configurable in the way that is described here. If an organisation doesn't like functionality, they can change it themselves, meaning that Ripple is not responsible for those changes or coming up with these types of configuration options for others to use. *** **Q: If not currently possible, how could this be achieved?** **A:** We can store settings for plugins In a separate file, for example `pluginname.conf` where we describe the settings for particular module <file_sep>/pages/angular/technology/angular-PT1-technologies.md --- title: Technologies keywords: Technologies summary: "Brief rationale behind some of the technology choices" sidebar: angular_sidebar permalink: angular-technologies.html folder: angular/technology filename: angular-PT1-technologies.md --- ### Redux **Q: Why was Redux chosen?** **A:** - An acceptable choice, with equal benefits to Angular's state management system - Not really gaining benefits at this stage, but as the system grows it could prove very useful *** **Q: What benefits are gained from using Redux** **A:** There are a couple of them, and the main ones: - Scalability when state becomes complex - A robust platform for future development *** **Q: Do we know what the driver to choose Redux? It seems we are tied to that technology now, so although it may be a great fit we are still unclear what drove that decision and whether it was the right one.** **A:** It seems the Redux code is clearly delineated from the PulseTile code, meaning that we aren't completely tied to the technology choice if it proves to be more of a hindrance than a benefit. ### WebPack **Q: Why was webpack chosen?** **A:** Why? - Useful for a modular architecture, because it has the concept of a dependency tree, unlike Grunt/Gulp - Performs better than Grunt (the previous choice of build system) - Gets rid of the need for RequireJS and tools like Browserify *** **Q: Why is webpack better than using npm or bower to import PulseTile plugins?** **A:** Webpack is a build tool and its purpose is to transpile the code (like in case with Babel and ES6) and compile bundles for production usage and it does it really well and fast as it has a clear syntax and good documentation *** **Q: Webpack takes care of a lot of configuration for you, which of course makes things easier, but it means that changing configuration may not be as flexible as desired. Could this present problems if configuration becomes more complex?** **A:** Related to this point, we discussed whether there are any problems that could be faced from having a complex dependency tree that Webpack may struggle to digest. In our experience, they have never gotten to a point where webpack will struggle in this scenario, even with applications that become much more complex. *** **Q: Are there any performance figures that you’ve recorded that show the difference in loading times using webpack?** **A:** Webpack performs much faster than Grunt, and is about equal to Gulp, so that is a perfectly reasonable performance gain *** **Q: Currently all modules seem to be very standalone, so it looks as though webpack is not being used to its full potential. Is this just part of a step-by-step implementation process, or has it been by design?** **A:** Related to this point - we discussed how at present Webpack isn't being used in the standard way to send up module bundles to the client, instead of sending the vendor and PulseTile bundles in two large files. We have already noticed this and are planning to send separate, smaller bundles to the client in this way, which will mean less network traffic and higher performance. ### Bower **Q: What are the long term plans for Bower?** **A:** Bower will stay, because it serves a very particular purpose. Bower isn't being replaced by npm, and nor should it be. The 3rd party web components that the system needs should be provided by Bower, even if npm can provide them. *** **Q: Will all Bower components be removed and replaced by npm modules?** **A:** We mentioned the dependency tree of imported 3rd part components, and whether the PulseTile UI is importing transient dependencies (dependencies of dependencies), and whether these should be defined within the package.json or bower.json files. SliceArt are keen to analyse the dependency tree to try to determine whether there are any problems that may be encountered by transient dependencies. <file_sep>/pages/react/plugin-tiles/react-plugin-process.md --- title: Plugin development brief keywords: plugins process structure summary: "Guide to plugins development process" sidebar: react_sidebar permalink: react-plugin-process.html folder: react/plugin-tiles filename: react-plugin-process.md --- ## Plugin's development: To get started, copy the core project (https://github.com/PulseTile/PulseTile-React) for creating your functional environment. ### Structure of ExamplePlugins To create a new heading, you can create a new folder by the following path ```src/components/pages``` To implement a simple heading (e.g. 'ExamplePlugins'), you can use the structure mentioned below. For example, you can also look at the implementation of the simple heading in the repository PulseTile-React - [GenericPlugin](https://github.com/PulseTile/PulseTile-React/tree/master/src/components/pages/GenericPlugin) ``` src/components/pages /ExamplePlugins /ducks - fetch-example-plugins.duck.js - fetch-example-plugins-create.duck.js - fetch-example-plugins-detail.duck.js - fetch-example-plugins-detail-edit.duck.js /ExamplePluginsCreate - default-values.config.js - ExamplePluginsCreateForm.js /ExamplePluginsDetail - ExamplePluginsDetail.js - ExamplePluginsDetailForm.js - ExamplePlugins.js - forms.config.js - forms.validation.js - index.js - selectors.js - table-columns.config.js ``` Below you can find the information with the description of each file and its role. #### ExamplePlugins.js This is the main component of the plugin. It includes all internal components and implements the business logic of your plug-in. ##### Component structure ``` // to import main packages import React, { PureComponent } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { lifecycle, compose } from 'recompose'; // to import auxiliary components for the implementation of panels import PluginListHeader from '../../plugin-page-component/PluginListHeader'; import PluginCreate from '../../plugin-page-component/PluginCreate'; import PluginMainPanel from '../../plugin-page-component/PluginMainPanel'; // to import internal components import ExamplePluginsDetail from './ExamplePluginsDetail/ExamplePluginsDetail'; import ExamplePluginsCreateForm from './ExamplePluginsCreate/ExamplePluginsCreateForm'; // to import actions for fetching the requests to server import { fetchExamplePluginsRequest } from './ducks/fetch-example-plugins.duck'; import { fetchExamplePluginsCreateRequest } from './ducks/fetch-example-plugins-create.duck'; import { fetchExamplePluginsDetailRequest } from './ducks/fetch-example-plugins-detail.duck'; import { fetchExamplePluginsDetailEditRequest } from './ducks/fetch-example-plugins-detail-edit.duck'; // to import selectors for retrieving data from the main storage import { patientExamplePluginsSelector, patientExamplePluginsDetailSelector, personalNotePanelFormSelector, personalCreateFormStateSelector } from './selectors'; // to import additional functions for the simple handling of data collections import { checkIsValidateForm, operationsOnCollection } from '../../../utils/plugin-helpers.utils'; // to map dispatch to Properties const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ fetchExamplePluginsRequest, fetchExamplePluginsDetailRequest, fetchExamplePluginsDetailEditRequest, fetchExamplePluginsCreateRequest }, dispatch) }); // Higher-Order Components (HOC) for getting some data @connect(patientExamplePluginsSelector, mapDispatchToProps) @connect(patientExamplePluginsDetailSelector, mapDispatchToProps) @connect(personalNotePanelFormSelector) @connect(personalCreateFormStateSelector) // Higher-Order Components (HOC) for realizing call requests in the life cycle of a component @compose(lifecycle(fetchExamplePluginsOnMount), lifecycle(fetchExamplePluginsDetailOnMount)) // React component export default class ExamplePlugins extends PureComponent { // implementing the functionality of a Component // component template render() { return () } } ``` #### ExamplePluginsDetail.js This component is needed to display more information about one record from the list of incoming records to the main component ##### Component structure ``` // to import packages import React, { PureComponent } from 'react'; // to import auxiliary components for the implementation of panels import PluginDetailPanel from '../../../plugin-page-component/PluginDetailPanel' // to import internal components import ExamplePluginsDetailForm from './ExamplePluginsDetailForm' // React component export default class ExamplePluginsDetail extends PureComponent { // Implementing the Functional of a Component // component template render() { return () } } ``` #### ExamplePluginsDetailForm.js This component contains a form for editing information about one record from the list of incoming records to the main component ##### Component structure ``` // to import the main packages import React, { PureComponent } from 'react'; import { Field, reduxForm } from 'redux-form' // to import the Fields components import ValidatedInput from '../../../form-fields/ValidatedInputFormGroup'; import ValidatedTextareaFormGroup from '../../../form-fields/ValidatedTextareaFormGroup'; import DateInput from '../../../form-fields/DateInput'; // to import the constants containing the names of fields and their labels import { valuesNames, valuesLabels } from '../forms.config'; // to import the function to validate form import { validateForm } from '../forms.validation'; // decorator to connect this component form to Redux @reduxForm({ form: 'examplePluginPanelFormSelector', validate: validateForm, }) export default class ExamplePluginsDetailForm extends PureComponent { // React component // component template render() { return () } } ``` #### ExamplePluginsCreateForm.js This component contains a form for editing information about one record from the list of incoming records to the main component ##### Component structure ``` // to import the main packages import React, { PureComponent } from 'react'; import { Field, reduxForm } from 'redux-form' // to import the Fields components import ValidatedInput from '../../../form-fields/ValidatedInputFormGroup'; import ValidatedTextareaFormGroup from '../../../form-fields/ValidatedTextareaFormGroup'; import DateInput from '../../../form-fields/DateInput'; // to import the constants containing the names of fields and their labels import { valuesNames, valuesLabels } from '../forms.config'; // to import the function for validate of form import { validateForm } from '../forms.validation'; // to import of object contains default values of fields import { defaultFormValues } from './default-values.config'; // decorator to connect its form component to Redux @reduxForm({ form: 'examplePluginCreateFormSelector', validate: validateForm, }) export default class ExamplePluginsCreateForm extends PureComponent { // React component // component template render() { return () } } ``` #### default-values.config.js It's just an object containing the default values of the fields for pre-populating before editing the fields by users. It is used in component ExamplePluginsCreateForm ##### File structure ``` export const defaultFormValues = { key: value, }; ``` #### forms.config.js This file contains 2 basic configuration objects for working with the fields in forms and for displaying detailed information about the record. You can also add additional configuration objects here to use it in forms ##### File structure ``` export const valuesNames = { NAME_OF_FIELD: 'name', }; export const valuesLabels = { NAME_OF_FIELD: 'label', }; ``` #### forms.validation.js This file exports a function for form validation. The parameter of the function is an object containing form fields with values. The function must return an error object, where the key is the field name, the value is the error text. If the field does not pass the validation it must be included in the resulting object error. ##### File structure ``` const validateForm = (values) => { const errors = {}; errors[valuesNames.NAME_OF_FIELD] = !values[valuesNames.NAME_OF_FIELD] ? 'Error text' : null; return errors; }; export { validateForm } ``` #### table-columns.config.js This file contains 2 configuration objects for configuring the main record table. ##### File structure ``` // The object contains the setting of possible columns in the table // transformer - it is a function, which is called before the displaying of the field and is necessary for the modification of the field itself export const columnsConfig = [ { key: 'nameOfField', title: 'Title of Field', transformer: transformerFunction, width: '30%' }, { key: 'sourceId', title: 'SourceID', display: 'none' }, ]; // The object allows you to enable or disable columns in a table export const defaultColumnsSelected = { type: true, sourceId: true, }; ``` #### Ducks - fetch-example-plugins.duck.js - fetch-example-plugins-create.duck.js - fetch-example-plugins-detail.duck.js - fetch-example-plugins-detail-edit.duck.js Each of these files contains all of its related constants, actions/action creators, epic, and its reducer for work with requests to server ##### File structure ``` // to import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; // Actions names export const FETCH_EXAMPLE_PLUGINS_CREATE_REQUEST = 'FETCH_EXAMPLE_PLUGINS_CREATE_REQUEST'; export const FETCH_EXAMPLE_PLUGINS_CREATE_SUCCESS = 'FETCH_EXAMPLE_PLUGINS_CREATE_SUCCESS'; export const FETCH_EXAMPLE_PLUGINS_CREATE_FAILURE = 'FETCH_EXAMPLE_PLUGINS_CREATE_FAILURE'; // Actions export const fetchExamplePluginsCreateRequest = createAction(FETCH_EXAMPLE_PLUGINS_CREATE_REQUEST); export const fetchExamplePluginsCreateSuccess = createAction(FETCH_EXAMPLE_PLUGINS_CREATE_SUCCESS); export const fetchExamplePluginsCreateFailure = createAction(FETCH_EXAMPLE_PLUGINS_CREATE_FAILURE); // Epics for async actions export const fetchExamplePluginsCreateEpic = (action$, store) => {}; // reducer export default function reducer(patientExamplePluginsCreate = {}, action) { switch (action.type) { case FETCH_EXAMPLE_PLUGINS_CREATE_SUCCESS: return action.payload; default: return patientExamplePluginsCreate } } ``` #### selectors.js This file exports the object of selectors. Selector - this is a function that extracts the necessary data from a centralized store. ##### File structure ``` // to import packages import { createSelector } from 'reselect'; import _ from 'lodash/fp'; const patientExamplePluginsSelector = createSelector( ({ patientsExamplePlugins }) => patientsExamplePlugins, (state, props) => _.getOr(null, 'match.params.userId', props), (patientsExamplePlugins, userId) => { const allExamplePlugins = patientsExamplePlugins[userId]; return ({ allExamplePlugins, userId }); } ); export { patientExamplePluginsSelector, } ``` #### index.js This is the main file of the new heading, which exports all the resources of this plugin to the application core and configuration objects. ``` // to import all resources import { combineEpics } from 'redux-observable'; import ExamplePlugins from './ExamplePlugins'; import { clientUrls } from '../../../config/client-urls.constants'; import { fetchExamplePluginsEpic } from './ducks/fetch-example-plugins.duck'; import { fetchExamplePluginsUpdateEpic } from './ducks/fetch-example-plugins.duck'; import { fetchExamplePluginsDetailEpic } from './ducks/fetch-example-plugins-detail.duck'; import { fetchExamplePluginsDetailEditEpic } from './ducks/fetch-example-plugins-detail-edit.duck'; import { fetchExamplePluginsCreateEpic } from './ducks/fetch-example-plugins-create.duck'; import patientsExamplePlugins from './ducks/fetch-example-plugins.duck'; import examplePluginsDetail from './ducks/fetch-example-plugins-detail.duck'; import examplePluginsDetailEdit from './ducks/fetch-example-plugins-detail-edit.duck'; import examplePluginsCreate from './ducks/fetch-example-plugins-create.duck'; const epics = combineEpics(fetchExamplePluginsEpic, fetchExamplePluginsDetailEpic, fetchExamplePluginsDetailEditEpic, fetchExamplePluginsCreateEpic, fetchExamplePluginsUpdateEpic); const reducers = { patientsExamplePlugins, examplePluginsDetail, examplePluginsDetailEdit, examplePluginsCreate, }; const sidebarConfig = { key: 'examplePlugins', pathToTransition: '/examplePlugins', name: 'Example Plugins', isVisible: true }; const routers = [ { key: 'examplePlugins', component: ExamplePlugins, path: `${clientUrls.PATIENTS}/:userId/${clientUrls.EXAMPLE_PLUGINS}` }, { key: 'examplePluginsCreate', component: ExamplePlugins, path: `${clientUrls.PATIENTS}/:userId/${clientUrls.EXAMPLE_PLUGINS}/create` }, { key: 'examplePluginsDetail', component: ExamplePlugins, path: `${clientUrls.PATIENTS}/:userId/${clientUrls.EXAMPLE_PLUGINS}/:sourceId` }, ]; export default { component: ExamplePlugins, epics, reducers, sidebarConfig, routers, } ``` ### Steps how to connect the Plugin to the apps core #### 1. Connection index.js 1. Go to ```src/plugins.config.js``` 2. Make the import of your index.js into object 3. Add your object to plugins Array ##### Example code ``` ... import examplePlugins from './components/pages/ExamplePlugins/index'; export const plugins = [ ... examplePlugins, ]; ... ``` #### 2. Configuration of breadcrumbs 1. Go to ```src/configs/client-urls.constants.js``` 2. Create new constant into clientUrls object 3. Add your configuration of breadcrumbs to pluginsPages object ##### Example code ``` ... export const clientUrls = { ... EXAMPLE_PLUGINS: 'examplePlugins', }; const pluginsPages = { ... 'examplePlugins': { breadcrumbs: [{ title: 'Example Plugins', state: '/examplePlugins', }], }, ... }; ... ``` #### 3. Generating a component subscription to requests from the server 1. Please, go to ```src/utils/HOCs/fetch-patients.utils.js``` 2. Create a new Higher-Order Component (HOC) for realizing call requests in the life cycle of a component. ##### Example code ``` ... export const fetchExamplePluginsOnMount = (generateFetchListOnMount('fetchExamplePluginsRequest')); export const fetchExamplePluginsDetailOnMount = (generateFetchDetailOnMount('fetchExamplePluginsDetailRequest')); ... ``` <file_sep>/pages/landing/licensing.md --- title: Licensing keywords: licensing copyright documentation summary: "licensing copyright documentation" sidebar: home_sidebar permalink: licensing.html folder: landing filename: licensing.md --- ### Licensing **Q: What license is PulseTile available under?** **A:** PulseTile is available for widespread use under an [Apache 2.0 licence.](https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)) <file_sep>/pages/angular/core-tiles/angular-contacts-JSON.md --- title: JSON Array Contacts information keywords: Contacts summary: "JSON for Contacts module" sidebar: angular_sidebar permalink: angular-contacts-JSON.html folder: angular/core-tiles filename: angular-contacts-JSON.md --- Sample JSON for Contacts module displaying sample contacts: first example - without 'Next of Kin' checkmark, second - with the 'Next of Kin' checkmark. ``` { sourceId: "c4b08f6b-c45c-4bcd-a8b9-4cc53385c881", source: "marand", name: "<NAME>", relationship: "friend", nextOfKin: "" }, { sourceId: "8f8d258c-9c6d-4b94-94f9-c38c58363bbb", source: "ethercis", name: "Name", relationship: "Name", nextOfKin: true }, ``` <file_sep>/pages/landing/installing.md --- title: Installing PulseTile sidebar: home_sidebar keywords: Frontpage permalink: install.html toc: false folder: landing showlogo: false filename: installing.md --- Basic instructions to get PulseTile installed on your local machine to explore is available here in [https://github.com/PulseTile/PulseTile/blob/master/README.md](https://github.com/PulseTile/PulseTile/blob/master/README.md) **NB** Note that the PulseTile Framework is easiest to understand/experiment with in the context of a wider healthcare stack. Please check out the [Ripple Foundation Showcase Stack Documentation](http://docs-showcase.ripple.foundation/) for a better understanding of PulseTile in that context. One of the features available is an install script that gets PulseTile up and running with a set of API provided test data ready to explore. We recommend that newcomers to PulseTile quickly install PulseTile as part of this showcase stack. Please let us know if/how we can help make the install process easier for you. <file_sep>/pages/angular/core-tiles/angular-problems-diagnosis.html --- title: Diagnosis module keywords: sample summary: "Diagnosis module" sidebar: angular_sidebar permalink: angular-problems-diagnosis.html folder: angular/core-tiles filename: angular-problems_diagnosis.html --- <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/diagnoses/diagnoses-list.component.js">Diagnosis List</a></h4> {% include image.html file="diagnosis/diagnoseslist.png" url="#" alt="Diagnosis list view" caption="Diagnosis List" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/problems </pre> <h5>GET response</h5> <pre> { problem:"asthma" source:"ethercis" sourceId:"08fd487b-765a-41b4-9501-334d48dc2b00" } </pre> <h5>Component structure</h5> <pre> //component template let templateDiagnosesList = require('./diagnoses-list.html'); //controller init class DiagnosesListController { constructor($scope, $state, $stateParams, $ngRedux, diagnosesActions, serviceRequests, usSpinnerService, serviceFormatted) { } //component init const DiagnosesListComponent = { template: templateDiagnosesList, controller: DiagnosesListController }; //inject services/modules to controller DiagnosesListController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'diagnosesActions', 'serviceRequests', 'usSpinnerService', 'serviceFormatted']; //es6 export for component export default DiagnosesListComponent; </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/diagnoses/diagnoses-detail.component.js">Diagnosis Detail</a></h4> {% include image.html file="diagnosis/diagnosesdetail.jpg" url="#" alt="Diagnosis Detail" caption="Diagnosis Detail" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/problems/{sourceId} </pre> <h5>GET response</h5> <pre> { author:"Dr <NAME>" code:299757012 dateCreated:1445458262000 dateOfOnset:963833437553 description:"" problem:"angina pectoris" source:"EtherCIS" sourceId:"12f02a05-a14f-4b35-be45-9e52bbe535ed" terminology:"SNOMED-CT" } </pre> <h5>Component structure</h5> <pre> //component template let templateDiagnosesDetail = require('./diagnoses-detail.html'); //controller init class DiagnosesDetailController { constructor($scope, $state, $stateParams, $ngRedux, patientsActions, diagnosesActions, serviceRequests, usSpinnerService) { } //component init const DiagnosesDetailComponent = { template: templateDiagnosesDetail, controller: DiagnosesDetailController }; //inject services/modules to controller DiagnosesDetailController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'patientsActions', 'diagnosesActions', 'serviceRequests', 'usSpinnerService']; //es6 export for component export default DiagnosesDetailComponent; </pre> {% include image.html file="diagnosis/diagnosesedit.png" url="#" alt="Diagnosis Edit" caption="Diagnosis Edit" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/problems </pre> <h5>PUT data</h5> <pre> { author:"Dr <NAME>" code:299757012 dateCreated:1445458262000 dateOfOnset:963833437553 description:"" problem:"angina pectoris" source:"EtherCIS" sourceId:"12f02a05-a14f-4b35-be45-9e52bbe535ed" terminology:"SNOMED-CT" } </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/diagnoses/diagnoses-create.component.js">Diagnosis Create</a></h4> {% include image.html file="diagnosis/diagnosescreate.png" url="#" alt="Diagnosis Create" caption="Diagnosis Create" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/problems </pre> <h5>POST data</h5> <pre> { code:"12393890" dateOfOnset:"2017-04-07" description:"qwww" problem:"angina pectoris t" sourceId:"" terminology:"qwer" } </pre> <h5>Component structure</h5> <pre> //component template let templateDiagnosesCreate = require('./diagnoses-create.html'); //controller init class DiagnosesCreateController { constructor($scope, $state, $stateParams, $ngRedux, patientsActions, diagnosesActions, serviceRequests) { } //component init const DiagnosesCreateComponent = { template: templateDiagnosesCreate, controller: DiagnosesCreateController }; //inject services/modules to controller DiagnosesCreateController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'patientsActions', 'diagnosesActions', 'serviceRequests']; //es6 export for component export default DiagnosesCreateComponent; </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/diagnoses/diagnoses-actions.js">Diagnosis Actions</a></h4> <h5>Component structure</h5> <pre> //es6 import modules import {bindActionCreators} from 'redux'; import * as types from '../../../constants/ActionTypes'; //es6 export function export function all(patientId) { return { types: [types.DIAGNOSES, types.DIAGNOSES_SUCCESS, types.DIAGNOSES_ERROR], shouldCallAPI: (state) => !state.diagnoses.response, config: { method: 'get', url: '/api/patients/' + patientId + '/problems' }, meta: { timestamp: Date.now() } }; } </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/diagnoses/diagnoses-reducer-all.js">Diagnosis Reducer</a></h4> <h5>Component structure</h5> <pre> //es6 import modules import * as types from '../../../constants/ActionTypes'; const INITIAL_STATE = { isFetching: false, error: false, data: null, dataGet: null, dataCreate: null, dataUpdate: null }; //es6 export function export default function diagnoses(state = INITIAL_STATE, action) { const {payload} = action; //redux action for Diagnosis requests var actions = { [types.DIAGNOSES]: (state) => { return Object.assign({}, state, { isFetching: true, error: false }); } </pre> <file_sep>/pages/react/core-tiles/react-allergies-JSON.md --- title: JSON Array Allergies data keywords: Allergies summary: "JSON for Allergies module" sidebar: react_sidebar permalink: react-allergies-JSON.html folder: react/core-tiles filename: react-allergies-JSON.md --- Sample JSON for Allergies data simulation. ``` { sourceId: "d2bb63a9-7871-4981-9daa-e82081aad515", source: "ethercis", cause: "Peanuts 100", reaction: "test" }, { sourceId: "99704fac-afb3-4753-9db4-95441f8d7f45", source: "ethercis", cause: "Tree pollen", reaction: "Urticaria" }, ``` <file_sep>/pages/landing/index.html --- title: Documentation - Getting Started sidebar: home_sidebar keywords: Frontpage permalink: index.html #could be landing html etc, by using index.html we bump the index page which is still the tomjohnson theme index toc: false folder: landing showlogo: true filename: index.html --- <p>Here you can find various documentation topics of the PulseTile general UI & codebase; Please, refer to the sidebar / header menu to switch to the topic you need. </p> <p>You can find the information on the following topics:</p> <ul> <li>Where PulseTile came from</li> <li>The Patterns and Principles that underpin PulseTile</li> <li>UX/UI kit of the project including various elements etc</li> <li>Technical choices and choosing.. </li> <li>Tiles- Core and Plugins including code examples</li> <li>Samples of JSON API data- ie links to the wider world</li> </ul> <div class="row"> <div class="col-lg-12"> <h2 class="page-header">PulseTile Angular Subjects</h2> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Technologies Stack</h4> <ul> <li><a href="/angular-technology.html">Angular</a></li> <li><a href="/angular-redux-technology.html">Redux</a></li> <li><a href="/angular-webpack-technology.html">WebPack</a></li> <li><a href="/angular-bower-technology.html">Bower</a></li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Core UI Framework</h4> <ul> <li><a href="/ui-kit-page.html">UI Kit</a></li> <li><a href="/angular-background.html">Background</a></li> <li><a href="/angular-initial-QA.html">Initial Q&A</a></li> <li><a href="/angular-plugin-process.html">Guide to plugins development process</a></li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Core Tiles</h4> <ul> <li><a href="/angular-patient-summary.html">Patient Summary</a></li> <li><a href="/angular-search.html">Search</a></li> <li><a href="/angular-multipatients.html">MPV</a></li> <li><a href="/angular-charts.html">Charts</a></li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Plugin Tiles</h4> <ul> <li><a href="/angular-clinical-notes.html">Clinical Notes</a></li> <li><a href="/angular-problems-diagnosis.html">Problems Diagnosis</a></li> <li><a href="/angular-images.html">Images</a></li> <li><a href="/angular-documents.html">Documents</a></li> </ul> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <h2 class="page-header">PulseTile React Subjects</h2> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Technologies Stack</h4> <ul> <li><a href="/react-technology.html">React</a></li> <li><a href="/react-redux-technology.html">Redux</a></li> <li><a href="/react-rxjs-technology.html">RxJS</a></li> <li><a href="/react-webpack-technology.html">WebPack</a></li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Core UI Framework</h4> <ul> <!--<li><a href="/ui-kit-page.html">UI Kit</a></li>--> <li><span class="link">UI Kit</span></li> <li><a href="/react-background.html">Background</a></li> <li><a href="/react-tech-intro.html">Technical Background</a></li> <li><a href="/react-plugin-process.html">Guide to plugins development process</a></li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Core Tiles</h4> <ul> <li><a href="/react-patient-summary.html">Patient Summary</a></li> <li><a href="/react-search.html">Search</a></li> <li><a href="/react-multipatients.html">MPV</a></li> <li><a href="/react-charts.html">Charts</a></li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="panel panel-default"> <div class="panel-body"> <h4>Plugin Tiles</h4> <ul> <li><a href="/react-clinical-notes.html">Clinical Notes</a></li> <li><a href="/react-problems-diagnosis.html">Problems Diagnosis</a></li> <li><a href="/react-images.html">Images</a></li> <li><a href="/react-documents.html">Documents</a></li> </ul> </div> </div> </div> </div><file_sep>/pages/react/plugin-tiles/react-test-results-JSON.md --- title: JSON Array Test Results keywords: Test Results summary: "JSON for Test Results module" sidebar: react_sidebar permalink: react-test-results-JSON.html folder: react/plugin-tiles filename: react-test-results-JSON.md --- Sample JSON data for Test Results module. ``` { sourceId: "810272ac-28e8-4928-b61b-79dcef4b4170", source: "ethercis", testName: "", sampleTaken: 1426889462518, dateCreated: 1426975862000 }, { sourceId: "a601a3df-cfea-4cb8-9b82-5737522b52c4", source: "ethercis", testName: "", sampleTaken: 1428613862518, dateCreated: 1429045862000 }, ``` <file_sep>/pages/angular/technology/angular-tech-intro.md --- title: Technologies Stack sidebar: angular_sidebar permalink: angular-tech-intro.html folder: angular/technology toc: false filename: angular-tech-intro.md --- ## PulseTile - Making Technical Choices in the fast world of frontend JS So one of the most difficult choices to make when crafting a frontend framework is which tools to use. We have been over this many times and gone for a mix that makes sense for now. We'll be keeping our eyes open as the trends develop, will React/Angular/Vue/Aurelia/other win the day? We'll follow them closely and follow the leader from the pack. ## PulseTile uses the following technology stack: * Angular 1.5 * Redux * Webpack * Bower * CodeCov * Karma ## Angular AngularJS is a toolset for building the framework most suited to your application development. It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs. Read on to find out how. ## Redux Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger. We use redux module for Angular - https://github.com/angular-redux/ng-redux ## WebPack WebPack is a module bundler. Existing module bundlers are not well suited for big projects (big single page applications). The most pressing reason for developing another module bundler was Code Splitting and that static assets should fit seamlessly together through modularization. I tried to extend existing module bundlers, but it wasn’t possible to achieve all goals. Goals: * Split the dependency tree into chunks loaded on demand * Keep initial loading time low * Every static asset should be able to be a module * Ability to integrate 3rd-party libraries as modules * Ability to customize nearly every part of the module bundler * Suited for big projects ## Bower Web sites are made of lots of things — frameworks, libraries, assets, and utilities. Bower manages all these things for you. Keeping track of all these packages and making sure they are up to date (or set to the specific versions you need) is tricky. Bower to the rescue! Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies. <file_sep>/pages/angular/plugin-tiles/angular-orders.html --- title: Orders module keywords: sample summary: "Orders module" sidebar: angular_sidebar permalink: angular-orders.html folder: angular/plugin-tiles filename: angular-orders.html --- <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/orders/orders-list.component.js">Orders List</a></h4> {% include image.html file="orders/orderslist.png" url="#" alt="Orders list view" caption="Orders List" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/laborders </pre> <h5>GET response</h5> <pre> { name:"Cardiac-ECG" orderDate:1458738936944 source:"ethercis" sourceId:"4c4df65d-98d4-4f62-998f-fe0d9eeca9a0" } </pre> <h5>Component structure</h5> <pre> //component template let templateOrdersList = require('./orders-list.html'); //controller init class OrdersListController { constructor($scope, $state, $stateParams, $ngRedux, ordersActions, serviceRequests, usSpinnerService, serviceFormatted) { } //component init const OrdersListComponent = { template: templateOrdersList, controller: OrdersListController }; //inject services/modules to controller OrdersListController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'ordersActions', 'serviceRequests', 'usSpinnerService', 'serviceFormatted']; //es6 export for component export default OrdersListComponent; </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/orders/orders-detail.component.js">Orders Detail</a></h4> {% include image.html file="orders/ordersdetail.png" url="#" alt="Orders Detail" caption="Orders Detail" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/laborders/{sourceId} </pre> <h5>GET response</h5> <pre> { author:"Dr <NAME>" code:"order4" dateCreated:1458738026000 name:"Physio-crutches" orderDate:1458738023504 source:"EtherCIS" sourceId:"cc690d51-223f-4f54-afb5-c4ede9f781aa" terminology:"SNOMED-CT" } </pre> <h5>Component structure</h5> <pre> //component template let templateOrdersDetail = require('./orders-detail.html'); //controller init class OrdersDetailController { constructor($scope, $state, $stateParams, $ngRedux, ordersActions, usSpinnerService, serviceRequests) {} } //component init const OrdersDetailComponent = { template: templateOrdersDetail, controller: OrdersDetailController }; //inject services/modules to controller OrdersDetailController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'ordersActions', 'usSpinnerService', 'serviceRequests']; //es6 export for component export default OrdersDetailComponent; </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/orders/orders-create.component.js">Orders Create</a></h4> {% include image.html file="orders/orderscreate.png" url="#" alt="Orders Edit" caption="Orders Create" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/laborders </pre> <h5>POST data</h5> <pre> [{code: "order1", text: "Xray Chest X-ray"}] </pre> <h5>Component structure</h5> <pre> //component template let templateOrdersCreate= require('./orders-create.html'); //controller init class OrdersCreateController { constructor($scope, $state, $stateParams, $ngRedux, ordersActions, serviceRequests) { } //component init const OrdersCreateComponent = { template: templateOrdersCreate, controller: OrdersCreateController }; //inject services/modules to controller OrdersCreateController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'ordersActions', 'serviceRequests']; //es6 export for component export default OrdersCreateComponent; </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/orders/orders-actions.js">Orders Actions</a></h4> <h5>Component structure</h5> <pre> //es6 import modules import {bindActionCreators} from 'redux'; import * as types from '../../../constants/ActionTypes'; //es6 export function export function all(patientId) { return { types: [types.ORDERS, types.ORDERS_SUCCESS, types.ORDERS_ERROR], shouldCallAPI: (state) => !state.orders.response, config: { method: 'get', url: '/api/patients/' + patientId + '/laborders' }, meta: { timestamp: Date.now() } }; } </pre> <h4><a href="https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/orders/orders-reducer-all.js">Orders Reducer</a></h4> <h5>Component structure</h5> <pre> //es6 import modules import * as types from '../../../constants/ActionTypes'; const INITIAL_STATE = { isFetching: false, error: false, data: null, dataGet: null, dataCreate: null, dataUpdate: null }; //es6 export function export default function orders(state = INITIAL_STATE, action) { const {payload} = action; //redux action for Orders requests var actions = { [[types.ORDERS]: (state) => { state.dataCreate = null; state.dataUpdate = null; return Object.assign({}, state, { isFetching: true, error: false }); } </pre> <file_sep>/pages/angular/technology/angular-initial-QA.md --- title: Initial Q & A session keywords: Q&A summary: "Initial Q&A Session" sidebar: angular_sidebar permalink: angular-initial-QA.html folder: angular/technology filename: angular-Initial-QA.md --- [//]: # (Question-answer session dated 27.10.2016) *** **Q: How does webpack work with Angular to modularise the project? (i.e. is it working against the standard Angular modular architecture and adding complexity where it’s not necessary?)** **A:** We use export and import directives to manage project modules and they are processed by Webpack to handle different files dependencies. If we were using Gulp, for example, we would have need an additional package like Browserify to achieve the same. *** **Q: The readme doesn’t mention Bower, but there is a bower.json. Are we still using the Bower components, and it’s just been missed in the readme?** **A:** As we were playing around with different ways of connecting a plugin, Bower was most likely missed out from read.me file. Eventually, there are two active plugins left in Bower now, others are moved to its modules *** **Q: If we are building individual components, how to we ensure overall build quality of the project? (e.g. does component 1 work with component 2, and what about when we add component 3)** **A:** At this point modules are independent, however, if there is an error in a particular module, it can be a typo or a wrong function usage, resulting build will fail. We should verify that module works with the core application functionality and only after this we notify users in some way that this can be used. *** **Q: Will components be versioned outside the core UI components?** **A:** As long as the module follows the core styleguide and instructions it can be updated and versioned in the way developer feels it should be *** **Q: Is using Redux outside of its normal use-case (with Angular rather than React) bending the way it’s used? i.e. are we configuring it to work with Angular, as opposed to allowing it to “do its own thing.”** **A:** We agree that using Redux with React in terms of the normal use-case of Redux architecture is a more common practice, but, as this stack (Angular and Redux) was initial choice at the start of the project, we have adapted them to work together. *** **Q: To what extent is the build configurable when using webpack over Grunt/Gulp?** **A:** As mentioned in point #1 the biggest benefit is the import/export components system *** **Q: Does using webpack to import modules allow for the extension/editing of source files? This is important if an organisation wants to use a core module but wishes to change functionality.** **A:** Yes, Webpack can build the project– either it is modified or not. *** **Q: If modules are edited, how are they stored so that local additions to code aren’t overwritten when the project is updated with a new version of the core module?** **A:** If the core module is updated significantly, everything that could be overwritten is index files, where the other modules are included. So, if someone is working directly with some module (not core module) the local additions will not be affected. If the core module update will affect the 'includes-containing' files (`index.js`, `index.routes.js`, `actions/index.js` and `redux/reducer.js`), the locally edited modules probably should be re-included into the application. <file_sep>/pages/react/plugin-tiles/react-referrals.html --- title: Referrals module keywords: sample summary: "Referrals module" sidebar: react_sidebar permalink: react-referrals.html folder: react/plugin-tiles filename: react-referrals.html --- <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/Referrals.js">Referrals</a></h4> {% include image.html file="referrals/referralslist.png" url="#" alt="Referrals view" caption="Referrals" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/referrals </pre> <h5>GET response</h5> <pre> { dateOfReferral:1458792662000 referralFrom:"<NAME>" referralTo:"Ripplefields Optometry service" source:"ethercis" sourceId:"94133578-f505-4e76-b4ed-762462508801" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { lifecycle, compose } from 'recompose'; import PluginListHeader from '../../plugin-page-component/PluginListHeader'; import PluginMainPanel from '../../plugin-page-component/PluginMainPanel'; import { fetchPatientReferralsRequest } from './ducks/fetch-patient-referrals.duck'; import { fetchPatientReferralsCreateRequest } from './ducks/fetch-patient-referrals-create.duck'; import { fetchPatientReferralsDetailRequest } from './ducks/fetch-patient-referrals-detail.duck'; import { fetchPatientReferralsDetailEditRequest } from './ducks/fetch-patient-referrals-detail-edit.duck'; import { fetchPatientReferralsOnMount, fetchPatientReferralsDetailOnMount } from '../../../utils/HOCs/fetch-patients.utils'; import { patientReferralsSelector, referralsDetailFormStateSelector, referralsCreateFormStateSelector, metaPanelFormStateSelector, patientReferralsDetailSelector } from './selectors'; import { checkIsValidateForm, operationsOnCollection } from '../../../utils/plugin-helpers.utils'; import ReferralsDetail from './ReferralsDetail/ReferralsDetail'; import PluginCreate from '../../plugin-page-component/PluginCreate'; import ReferralsCreateForm from './ReferralsCreate/ReferralsCreateForm' // map dispatch to Properties const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ fetchPatientReferralsRequest, fetchPatientReferralsCreateRequest, fetchPatientReferralsDetailRequest, fetchPatientReferralsDetailEditRequest }, dispatch) }); // Higher-Order Components (HOC) for get some data @connect(patientReferralsSelector, mapDispatchToProps) @connect(patientReferralsDetailSelector, mapDispatchToProps) @connect(referralsDetailFormStateSelector) @connect(referralsCreateFormStateSelector) @compose(lifecycle(fetchPatientReferralsOnMount), lifecycle(fetchPatientReferralsDetailOnMount)) export default class Referrals extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ReferralsDetail/ReferralsDetail.js">Referrals Detail</a></h4> {% include image.html file="referrals/referralsdetail.png" url="#" alt="Referrals Detail" caption="Referrals Detail" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/referrals/{sourceId} </pre> <h5>GET response</h5> <pre> { author:"c4h_ripple_osi" dateOfReferral:1477994812035 referralCareFlow:"Service request sent" referralFrom:"<NAME>" referralOutcome:"" referralRef:"816d8873-ccae-4e2c-bf42-4aee7ffcb802" referralServiceName:"Refer to Thoracic Surgeon" referralState:"planned" referralStateCode:526 referralStateDate:1477526400000 referralTo:"Royal Brompton" referralType:"Refer to Thoracic Surgeon" source:"Marand" sourceId:"aef53554-8e59-4c26-b4c3-b82ae1d2ddc4" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import PluginDetailPanel from '../../../plugin-page-component/PluginDetailPanel' import ReferralsDetailForm from './ReferralsDetailForm' import { getDDMMMYYYY } from '../../../../utils/time-helpers.utils'; import { valuesNames, valuesLabels } from '../forms.config'; export default class ReferralsDetail extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ReferralsDetail/ReferralsDetailForm.js">Referrals Detail Edit Form</a></h4> {% include image.html file="referrals/referralsedit.png" url="#" alt="Referrals Edit" caption="Referrals Edit" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/referrals/{sourceId} </pre> <h5>PUT data</h5> <pre> { author:"<NAME>" dateCreated:"2017-12-22T11:45:09.583Z" dateOfReferral:"2017-11-22T09:33:01.690Z" referralFrom:"<NAME>" referralReason:"General frailty" referralSummary:"test" referralTo:"Calderdale" source:"ethercis" sourceId:"cf1125e7-4399-4c19-a72c-9f59fc5a9033" userId:"9999999000" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import { Field, reduxForm } from 'redux-form' import ValidatedInput from '../../../form-fields/ValidatedInputFormGroup'; import ValidatedTextareaFormGroup from '../../../form-fields/ValidatedTextareaFormGroup'; import DateInput from '../../../form-fields/DateInput'; import { validateForm } from '../forms.validation'; import { valuesNames, valuesLabels } from '../forms.config'; // decorator to connect its form component to Redux @reduxForm({ form: 'referralsDetailFormSelector', validate: validateForm, }) export default class ReferralDetailForm extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ReferralsCreate/ReferralsCreateForm.js">Referrals Create Form</a></h4> {% include image.html file="referrals/referralscreate.png" url="#" alt="Referrals Create" caption="Referrals Create" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/referrals </pre> <h5>POST data</h5> <pre> { author:"<EMAIL>" dateCreated:"2017-12-22T11:46:23.413Z" dateOfReferral:"2017-12-11T22:00:00.000Z" referralFrom:"<NAME>" referralReason:"test" referralSummary:"test" referralTo:"test" source:"ethercis" userId:"9999999000" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import { Field, reduxForm } from 'redux-form' import ValidatedInput from '../../../form-fields/ValidatedInputFormGroup'; import ValidatedTextareaFormGroup from '../../../form-fields/ValidatedTextareaFormGroup'; import DateInput from '../../../form-fields/DateInput'; import { validateForm } from '../forms.validation'; import { valuesNames, valuesLabels } from '../forms.config'; import { defaultFormValues } from './default-values.config'; // decorator to connect its form component to Redux @reduxForm({ form: 'referralsCreateFormSelector', validate: validateForm, }) export default class ReferralsCreateForm extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ducks/fetch-patient-referrals.duck.js">Referrals List Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; import { fetchPatientReferralsDetailRequest } from './fetch-patient-referrals-detail.duck'; // Actions names export const FETCH_PATIENT_REFERRALS_REQUEST = 'FETCH_PATIENT_REFERRALS_REQUEST'; export const FETCH_PATIENT_REFERRALS_SUCCESS = 'FETCH_PATIENT_REFERRALS_SUCCESS'; export const FETCH_PATIENT_REFERRALS_FAILURE = 'FETCH_PATIENT_REFERRALS_FAILURE'; export const FETCH_PATIENT_REFERRALS_UPDATE_REQUEST = 'FETCH_PATIENT_REFERRALS_UPDATE_REQUEST'; // Actions export const fetchPatientReferralsRequest = createAction(FETCH_PATIENT_REFERRALS_REQUEST); export const fetchPatientReferralsSuccess = createAction(FETCH_PATIENT_REFERRALS_SUCCESS); export const fetchPatientReferralsFailure = createAction(FETCH_PATIENT_REFERRALS_FAILURE); export const fetchPatientReferralsUpdateRequest = createAction(FETCH_PATIENT_REFERRALS_UPDATE_REQUEST); // Epics for async actions export const fetchPatientReferralsEpic = (action$, store) => {}; export const fetchPatientReferralsUpdateEpic = (action$, store) => {}; // reducer export default function reducer(patientsReferrals = {}, action) { switch (action.type) { case FETCH_PATIENT_REFERRALS_SUCCESS: return _.set(action.payload.userId, action.payload.referrals, patientsReferrals); default: return patientsReferrals; } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ducks/fetch-patient-referrals-detail.duck.js">Referrals Detail Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; // Actions names export const FETCH_PATIENT_REFERRALS_DETAIL_REQUEST = 'FETCH_PATIENT_REFERRALS_DETAIL_REQUEST'; export const FETCH_PATIENT_REFERRALS_DETAIL_SUCCESS = 'FETCH_PATIENT_REFERRALS_DETAIL_SUCCESS'; export const FETCH_PATIENT_REFERRALS_DETAIL_FAILURE = 'FETCH_PATIENT_REFERRALS_DETAIL_FAILURE'; // Actions export const fetchPatientReferralsDetailRequest = createAction(FETCH_PATIENT_REFERRALS_DETAIL_REQUEST); export const fetchPatientReferralsDetailSuccess = createAction(FETCH_PATIENT_REFERRALS_DETAIL_SUCCESS); export const fetchPatientReferralsDetailFailure = createAction(FETCH_PATIENT_REFERRALS_DETAIL_FAILURE); // Epics for async actions export const fetchPatientReferralsDetailEpic = (action$, store) => {}; // reducer export default function reducer(referralsDetail = {}, action) { switch (action.type) { case FETCH_PATIENT_REFERRALS_DETAIL_SUCCESS: return _.set(action.payload.userId, action.payload.referralsDetail, referralsDetail); default: return referralsDetail; } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ducks/fetch-patient-referrals-detail-edit.duck.js">Referrals Detail Edit Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; import { fetchPatientReferralsUpdateRequest } from './fetch-patient-referrals.duck' // Actions names export const FETCH_PATIENT_REFERRALS_DETAIL_EDIT_REQUEST = 'FETCH_PATIENT_REFERRALS_DETAIL_EDIT_REQUEST'; export const FETCH_PATIENT_REFERRALS_DETAIL_EDIT_SUCCESS = 'FETCH_PATIENT_REFERRALS_DETAIL_EDIT_SUCCESS'; export const FETCH_PATIENT_REFERRALS_DETAIL_EDIT_FAILURE = 'FETCH_PATIENT_REFERRALS_DETAIL_EDIT_FAILURE'; // Actions export const fetchPatientReferralsDetailEditRequest = createAction(FETCH_PATIENT_REFERRALS_DETAIL_EDIT_REQUEST); export const fetchPatientReferralsDetailEditSuccess = createAction(FETCH_PATIENT_REFERRALS_DETAIL_EDIT_SUCCESS); export const fetchPatientReferralsDetailEditFailure = createAction(FETCH_PATIENT_REFERRALS_DETAIL_EDIT_FAILURE); // Epics for async actions export const fetchPatientReferralsDetailEditEpic = (action$, store) => {}; // reducer export default function reducer(referralsDetailEdit = {}, action) { switch (action.type) { case FETCH_PATIENT_REFERRALS_DETAIL_EDIT_SUCCESS: return action.payload; default: return referralsDetailEdit; } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Referrals/ducks/fetch-patient-referrals-create.duck.js">Referrals Create Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; import { fetchPatientReferralsRequest } from './fetch-patient-referrals.duck' // Actions names export const FETCH_PATIENT_REFERRALS_CREATE_REQUEST = 'FETCH_PATIENT_REFERRALS_CREATE_REQUEST'; export const FETCH_PATIENT_REFERRALS_CREATE_SUCCESS = 'FETCH_PATIENT_REFERRALS_CREATE_SUCCESS'; export const FETCH_PATIENT_REFERRALS_CREATE_FAILURE = 'FETCH_PATIENT_REFERRALS_CREATE_FAILURE'; // Actions export const fetchPatientReferralsCreateRequest = createAction(FETCH_PATIENT_REFERRALS_CREATE_REQUEST); export const fetchPatientReferralsCreateSuccess = createAction(FETCH_PATIENT_REFERRALS_CREATE_SUCCESS); export const fetchPatientReferralsCreateFailure = createAction(FETCH_PATIENT_REFERRALS_CREATE_FAILURE); // Epics for async actions export const fetchPatientReferralsCreateEpic = (action$, store) => {}; // reducer export default function reducer(patientReferralsCreate = {}, action) { switch (action.type) { case FETCH_PATIENT_REFERRALS_CREATE_SUCCESS: return action.payload; default: return patientReferralsCreate } } </pre><file_sep>/README.md # Documentation for the PulseTile UX/UI Framework See [PulseTile Documentation here](http://docs.pulsetile.com/ ) PulseTile is supported by the [Ripple Foundation](http://ripple.foundation/ ) <file_sep>/pages/react/plugin-tiles/react-events.html --- title: Events module keywords: sample summary: "Events module" sidebar: react_sidebar permalink: react-events.html folder: react/plugin-tiles filename: react-events.html --- <!--<p>Please note, that the functionality for events (in particular - webRTC chat-related tool) is located within the separate repository, and can be found <a href="https://github.com/PulseTile-Plugins/Carbon-Plugin-WebRTC"> here </a>--> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/Events.js">Events</a></h4> {% include image.html file="events/eventslist.png" url="#" alt="Events view" caption="Events" %} {% include image.html file="events/eventsline.png" url="#" alt="Events Time line" caption="Events Time line" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events </pre> <h5>GET response</h5> <pre> { dateCreated: 1494586220000 dateTime: 1494496220958 description: "Needs nursing and supervisory care" name: "Discharge to care home" source: "ethercis" sourceId: "93ac376d-3ff4-4e0b-b080-47eb3fe81750" type: "Appointment" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { lifecycle, compose } from 'recompose'; import { debounce } from 'throttle-debounce'; import EventsListHeader from './events-page-component/EventsListHeader'; import EventsMainPanel from './events-page-component/EventsMainPanel'; import { fetchPatientEventsRequest } from './ducks/fetch-patient-events.duck'; import { fetchPatientEventsDetailRequest } from './ducks/fetch-patient-events-detail.duck'; import { fetchPatientEventsDetailEditRequest } from './ducks/fetch-patient-events-detail-edit.duck'; import { fetchPatientEventsCreateRequest } from './ducks/fetch-patient-events-create.duck'; import { fetchPatientEventsOnMount, fetchPatientEventsDetailOnMount } from '../../../utils/HOCs/fetch-patients.utils'; import { patientEventsSelector, patientEventsDetailSelector, eventsDetailFormStateSelector, eventsCreateFormStateSelector } from './selectors'; import { checkIsValidateForm, operationsOnCollection } from '../../../utils/plugin-helpers.utils'; import EventsDetail from './EventsDetail/EventsDetail'; import PluginCreate from '../../plugin-page-component/PluginCreate'; import { modificateEventsArr } from './events-helpers.utils'; import EventsCreateForm from './EventsCreate/EventsCreateForm' // map dispatch to Properties const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ fetchPatientEventsRequest, fetchPatientEventsDetailRequest, fetchPatientEventsDetailEditRequest, fetchPatientEventsCreateRequest }, dispatch) }); // Higher-Order Components (HOC) for get some data @connect(patientEventsSelector, mapDispatchToProps) @connect(patientEventsDetailSelector, mapDispatchToProps) @connect(eventsDetailFormStateSelector) @connect(eventsCreateFormStateSelector) @compose(lifecycle(fetchPatientEventsOnMount), lifecycle(fetchPatientEventsDetailOnMount)) export default class Events extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/EventsDetail/EventsDetail.js">Events Detail</a></h4> {% include image.html file="events/eventsdetail.png" url="#" alt="Events Detail" caption="Events Detail" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events/{sourceId} </pre> <h5>GET response</h5> <pre> { author: "c4h_ripple_osi" dateCreated: 1500896270000 dateTime: 1500896400000 description: "testing" name: "24.07-10" source: "ethercis" sourceId: "bb5352e6-33a5-4c17-b80f-aa77a8047519" type: "Appointment" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import EventsDetailPanel from './EventsDetailPanel' import EventsDetailForm from './EventsDetailForm' export default class EventsDetail extends PureComponent { // React component // component template render() { return () } } </pre> {% include image.html file="events/eventschat.png" url="#" alt="Events Chat" caption="Events Chat" %} <!--<h5>socket channel</h5>--> <!--<pre>--> <!--socket.emit('appointment:messages', {appointmentId: sourceId});--> <!--</pre>--> <!--<h5>response</h5>--> <!--<pre>--> <!--{--> <!--$$hashKey:"object:12432"--> <!--appointment_id:"12164779-2c69-4a67-89bb-ac6620c77475"--> <!--author:""--> <!--message:"H5O has left the chat room"--> <!--timestamp:"11:12"--> <!--}--> <!--</pre>--> <!--{% include image.html file="events/eventsstart.png" url="#" alt="Events Start Appointment" caption="Events Start Appointment" %}--> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/EventsDetail/EventsDetailForm.js">Events Detail Edit Form</a></h4> {% include image.html file="events/eventsdetailedit.jpg" url="#" alt="Events Detail Edit" caption="Events Detail Edit" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events/{sourceId} </pre> <h5>PUT response</h5> <pre> { author:"<EMAIL>" dateTime:"2017-12-27T13:44:00.000Z" description:"test" name:"Test" type:"Appointment" userId:"9999999000" source:"ethercis" sourceId:"a35d5c44-8275-484c-8bd4-ddc36f64005e" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import { Field, reduxForm } from 'redux-form' import ValidatedInput from '../../../form-fields/ValidatedInputFormGroup'; import ValidatedTextareaFormGroup from '../../../form-fields/ValidatedTextareaFormGroup'; import DateInput from '../../../form-fields/DateInput'; import SelectFormGroup from '../../../form-fields/SelectFormGroup'; import { validateEventsForm } from '../forms.validation'; // decorator to connect its form component to Redux @reduxForm({ form: 'eventsDetailFormSelector', validate: validateEventsForm, }) export default class EventsDetailForm extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/EventsCreate/EventsCreateForm.js">Events Create Form</a></h4> {% include image.html file="events/eventscreate.png" url="#" alt="Events Create" caption="Events Create" %} <h5>API URL</h5> <pre> /api/patients/{patientId}/events </pre> <h5>POST data</h5> <pre> { author:"<EMAIL>" dateTime:"2017-12-27T13:44:00.000Z" description:"test" name:"Test" type:"Appointment" userId:"9999999000" } </pre> <h5>Component structure</h5> <pre> // import packages import React, { PureComponent } from 'react'; import { Field, reduxForm } from 'redux-form' import ValidatedInput from '../../../form-fields/ValidatedInputFormGroup'; import ValidatedTextareaFormGroup from '../../../form-fields/ValidatedTextareaFormGroup'; import SelectFormGroup from '../../../form-fields/SelectFormGroup'; import DateInput from '../../../form-fields/DateInput'; import { validateEventsForm } from '../forms.validation'; import { valuesNames, valuesLabels, connectionOptions, detailsOptions } from '../forms.config'; // decorator to connect its form component to Redux @reduxForm({ form: 'eventsCreateFormSelector', validate: validateEventsForm, }) export default class EventsCreateForm extends PureComponent { // React component // component template render() { return () } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/ducks/fetch-patient-events.duck.js">Events List Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; import { fetchPatientEventsDetailRequest } from './fetch-patient-events-detail.duck'; // Actions names export const FETCH_PATIENT_EVENTS_REQUEST = 'FETCH_PATIENT_EVENTS_REQUEST'; export const FETCH_PATIENT_EVENTS_SUCCESS = 'FETCH_PATIENT_EVENTS_SUCCESS'; export const FETCH_PATIENT_EVENTS_FAILURE = 'FETCH_PATIENT_EVENTS_FAILURE'; export const FETCH_PATIENT_EVENTS_UPDATE_REQUEST = 'FETCH_PATIENT_EVENTS_UPDATE_REQUEST'; // Actions export const fetchPatientEventsRequest = createAction(FETCH_PATIENT_EVENTS_REQUEST); export const fetchPatientEventsSuccess = createAction(FETCH_PATIENT_EVENTS_SUCCESS); export const fetchPatientEventsFailure = createAction(FETCH_PATIENT_EVENTS_FAILURE); export const fetchPatientEventsUpdateRequest = createAction(FETCH_PATIENT_EVENTS_UPDATE_REQUEST); // Epics for async actions export const fetchPatientEventsEpic = (action$, store) => {}; export const fetchPatientEventsUpdateEpic = (action$, store) => {}; // reducer export default function reducer(patientsEvents = {}, action) { switch (action.type) { case FETCH_PATIENT_EVENTS_SUCCESS: return _.set(action.payload.userId, action.payload.events, patientsEvents); default: return patientsEvents; } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/ducks/fetch-patient-events-detail.duck.js">Events Detail Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; // Actions names export const FETCH_PATIENT_EVENTS_DETAIL_REQUEST = 'FETCH_PATIENT_EVENTS_DETAIL_REQUEST'; export const FETCH_PATIENT_EVENTS_DETAIL_SUCCESS = 'FETCH_PATIENT_EVENTS_DETAIL_SUCCESS'; export const FETCH_PATIENT_EVENTS_DETAIL_FAILURE = 'FETCH_PATIENT_EVENTS_DETAIL_FAILURE'; // Actions export const fetchPatientEventsDetailRequest = createAction(FETCH_PATIENT_EVENTS_DETAIL_REQUEST); export const fetchPatientEventsDetailSuccess = createAction(FETCH_PATIENT_EVENTS_DETAIL_SUCCESS); export const fetchPatientEventsDetailFailure = createAction(FETCH_PATIENT_EVENTS_DETAIL_FAILURE); // Epics for async actions export const fetchPatientEventsDetailEpic = (action$, store) => {}; // reducer export default function reducer(eventsDetail = {}, action) { switch (action.type) { case FETCH_PATIENT_EVENTS_DETAIL_SUCCESS: return _.set(action.payload.userId, action.payload.eventsDetail, eventsDetail); default: return eventsDetail; } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/ducks/fetch-patient-events-detail-edit.duck.js">Events Detail Edit Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; import { fetchPatientEventsUpdateRequest } from './fetch-patient-events.duck' // Actions names export const FETCH_PATIENT_EVENTS_DETAIL_EDIT_REQUEST = 'FETCH_PATIENT_EVENTS_DETAIL_EDIT_REQUEST'; export const FETCH_PATIENT_EVENTS_DETAIL_EDIT_SUCCESS = 'FETCH_PATIENT_EVENTS_DETAIL_EDIT_SUCCESS'; export const FETCH_PATIENT_EVENTS_DETAIL_EDIT_FAILURE = 'FETCH_PATIENT_EVENTS_DETAIL_EDIT_FAILURE'; // Actions export const fetchPatientEventsDetailEditRequest = createAction(FETCH_PATIENT_EVENTS_DETAIL_EDIT_REQUEST); export const fetchPatientEventsDetailEditSuccess = createAction(FETCH_PATIENT_EVENTS_DETAIL_EDIT_SUCCESS); export const fetchPatientEventsDetailEditFailure = createAction(FETCH_PATIENT_EVENTS_DETAIL_EDIT_FAILURE); // Epics for async actions export const fetchPatientEventsDetailEditEpic = (action$, store) => {}; // reducer export default function reducer(eventsDetailEdit = {}, action) { switch (action.type) { case FETCH_PATIENT_EVENTS_DETAIL_EDIT_SUCCESS: return action.payload; default: return eventsDetailEdit; } } </pre> <h4><a href="https://github.com/PulseTile/PulseTile-React/blob/develop/src/components/pages/Events/ducks/fetch-patient-events-create.duck.js">Events Create Duck</a></h4> <h5>File structure</h5> <pre> // import packages import { Observable } from 'rxjs'; import { ajax } from 'rxjs/observable/dom/ajax'; import { createAction } from 'redux-actions'; import { fetchPatientEventsRequest } from './fetch-patient-events.duck' // Actions names export const FETCH_PATIENT_EVENTS_CREATE_REQUEST = 'FETCH_PATIENT_EVENTS_CREATE_REQUEST'; export const FETCH_PATIENT_EVENTS_CREATE_SUCCESS = 'FETCH_PATIENT_EVENTS_CREATE_SUCCESS'; export const FETCH_PATIENT_EVENTS_CREATE_FAILURE = 'FETCH_PATIENT_EVENTS_CREATE_FAILURE'; // Actions export const fetchPatientEventsCreateRequest = createAction(FETCH_PATIENT_EVENTS_CREATE_REQUEST); export const fetchPatientEventsCreateSuccess = createAction(FETCH_PATIENT_EVENTS_CREATE_SUCCESS); export const fetchPatientEventsCreateFailure = createAction(FETCH_PATIENT_EVENTS_CREATE_FAILURE); // Epics for async actions export const fetchPatientEventsCreateEpic = (action$, store) => {}; // reducer export default function reducer(patientEventsCreate = {}, action) { switch (action.type) { case FETCH_PATIENT_EVENTS_CREATE_SUCCESS: return action.payload; default: return patientEventsCreate } } </pre><file_sep>/pages/react/plugin-tiles/react-procedures-JSON.md --- title: JSON Array Procedures keywords: Procedures summary: "JSON for Procedures module" sidebar: react_sidebar permalink: react-procedures-JSON.html folder: react/plugin-tiles filename: react-procedures-JSON.md --- Sample JSON data to work with Procedures page: ``` { sourceId: "1846a4ae-65c2-496c-b538-7edf8a0f82cc", source: "ethercis", name: "", date: "", time: null }, ``` <file_sep>/pages/angular/core-tiles/angular-patient-summary-JSON.md --- title: JSON Array Patient information keywords: Patient information summary: "JSON for Patients information" sidebar: angular_sidebar permalink: angular-patient-summary-JSON.html folder: angular/core-tiles filename: angular-patient-summary-JSON.md --- Example of JSON object to work obtain patient information and data for patient summary page. ``` { allergies: [ { sourceId: "2a0d4a84-094c-41b0-9a76-9c87002e0183", source: "Marand", text: "allergy to penicillin" }, { sourceId: "336d2b1f-a521-4f99-a8b7-2bfcca3724d3", source: "Marand", text: "Flour" }, { sourceId: "c07888a5-5c27-4234-838c-04b65ef7e1ac", source: "Marand", text: "Grass pollen allergy" }, { sourceId: "ea6adbb4-7313-42e7-9a72-20fa8c84a6ff", source: "Marand", text: "allergy to penicillin" } ], medications: [ { sourceId: "abc3cafa-f843-46ca-b8bf-69b43cd568f6", source: "Marand", text: "Avelox" }, { sourceId: "8887614d-21f0-4847-9587-8e82fc6ba64c", source: "Marand", text: "Avelox" }, { sourceId: "df241976-5a25-49d2-b124-48202af029b0", source: "Marand", text: "Avelox" }, { sourceId: "b574a04e-dc4e-4e9b-8bd8-ed373bf79a80", source: "Marand", text: "High strength pain killers" } ], transfers: [ ], name: "<NAME>", gender: "Male", dateOfBirth: -806976000000, id: 9999999000, address: "6948 Et St., Halesowen, Worcestershire, VX27 5DV", pasNumber: 352541, nhsNumber: "9999999000", gpName: "<NAME>.", gpAddress: "Hamilton Practice, 5544 Ante Street, Hamilton, Lanarkshire, N06 5LP", telephone: "(011981) 32362" } ``` <file_sep>/pages/angular/core-tiles/angular-patient-summary.html --- title: Patient Summary module keywords: sample summary: "Patient Summary module" sidebar: angular_sidebar permalink: angular-patient-summary.html folder: angular/core-tiles filename: angular-patient-summary.html --- <h4><a href="https://github.com/PulseTile/PulseTile/blob/master/src/app/pulsetileui/pages/patient-summary/patients-summary.component.js">Patient Summary</a></h4> {% include image.html file="patientsummary/patientsummary.png" url="#" alt="Patient Summary list view" caption="Patient Summary List" %} <h5>API URL</h5> <pre> /api/patients/{patientId} </pre> <h5>GET data</h5> <pre> { address:"40, High Street, Dublin, D8" allergies:[] contacts:[] dateOfBirth:318384000000 gender:"Female" gpAddress:"Newport Practice, Ap #491-7493 Donec Ave, Newport, Hampshire, JB48 4EL" gpName:"<NAME>." id:9999999003 medications:[ { sourceId: "b693b071-d508-42dd-b114-d6cbd29c70bd", source: "Marand", text: "Aspirin" } ] name:"<NAME>" nhsNumber:"9999999003" pasNumber:332546 problems:[ { sourceId: "05e6df7f-4dcc-46d1-8134-010835e61308", source: "EtherCIS", text: "angina pectoris" } ] telephone:"07624 647524" transfers:[] } </pre> <h5>Component structure</h5> <pre> //component template let templatePatientsSummary = require('./patients-summary.html'); //controller init class PatientsSummaryController { constructor($scope, $state, $stateParams, $ngRedux, $location, patientsActions) { } //component init const PatientsSummaryComponent = { template: templatePatientsSummary, controller: PatientsSummaryController }; //inject services/modules to controller PatientsSummaryController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', '$location', 'patientsActions']; //es6 export for component export default PatientsSummaryComponent; </pre> <file_sep>/images/webRTC/readme.md for WebRTC related images <file_sep>/pages/react/core-tiles/react-medication-JSON.md --- title: JSON Array Medications data keywords: sample summary: "JSON for Medications module" sidebar: react_sidebar permalink: react-medication-JSON.html folder: react/core-tiles filename: react-medication-JSON.md --- Sample data in JSON array for Medications module. ``` { sourceId: "dd51f0f9-8ab0-40f6-969f-87d4af5edcd8", source: "ethercis", name: "Avelox", doseAmount: "20mg" }, { sourceId: "173d29de-22c7-454c-b850-da89f7d5ca36", source: "ethercis", name: "ww test 01 20 Jan", doseAmount: "01mg" }, ``` <file_sep>/pages/react-admin/core-tiles/react-admin-core-tiles.html --- title: Core Tiles keywords: mydoc sidebar: react_admin_sidebar permalink: react-admin-core-tiles.html folder: react-admin/core-tiles filename: react-admin-core-tiles.html --- <p>This section contains core modules of the application, which are the following:</p> <ul> <li>Business Intelligence</li> <li>Patient Search</li> <li>Multi Patients View</li> <li>Patient Summary</li> <li>Allergies</li> <li>Medications</li> <li>Contacts</li> <li>Problems / Diagnosis</li> </ul> <p>This modules are crucial for the application functionality, and should not be removed in order for application to behave properly.</p> <file_sep>/pages/react/plugin-tiles/turn/setup_coturn.sh #!/bin/bash echo 'deb http://http.us.debian.org/debian jessie main' | tee /etc/apt/sources.list.d/coturn.list gpg --keyserver pgpkeys.<EMAIL> --recv-key 8B48AD6246925553 gpg -a --export 8B48AD6246925553 | apt-key add - gpg --keyserver pgpkeys.mit.edu --recv-key <KEY> gpg -a --export <KEY> | apt-key add - gpg --keyserver pgpkeys.mit.edu --recv-key CBF8D6FD518E17E1 gpg -a --export CBF8D6FD518E17E1 | apt-key add - apt-get update apt-get install coturn=4.2.1.2-1 -y cp -f ./turnserver.conf /etc/ cp -f ./turnuserdb.conf /etc/ cp -f ./coturn /etc/default service coturn start <file_sep>/pages/angular/ui-kit/ui-kit2.md --- title: PulseTile - Core - UI Kit keywords: UIKit sidebar: angular_sidebar toc: false permalink: ui-kit-page.html folder: ui_kit filename: ui-kit2.md --- We link from here to our UI kit that is derived from our working showcase application. ## Welcome to the PulseTile UI Kit Click here to explore the [PulseTile UI Kit](http://showcase2.ripple.foundation/ui-kit.html) which opens in an external window In order to get the respective markup for each of the presented components Chrome Developer Toolbar or similar tool should be used. {% include image.html file="ui-kit/ui_kit_chrome_developer_toolbar_example.png" url="#" alt="Chrome Developer Toolbar Screenshot" caption="Using Chrome Developer Toolbar to extract markup for the button component" %} Allows you to explore the PulseTile Components -inc. up close in the console! <file_sep>/pages/react/plugin-tiles/react-referrals-JSON.md --- title: JSON Array Referrals keywords: Referrals summary: "JSON for Referrals module" sidebar: react_sidebar permalink: react-referrals-JSON.html folder: react/plugin-tiles filename: react-referrals-JSON.md --- Sample JSON array to display data for Referrals module. ``` { sourceId: "8a634643-7232-45b7-a773-2375f92deb82", source: "marand", dateOfReferral: 1459987200000, referralFrom: "Dr <NAME>", referralTo: "Dr <NAME>" }, { sourceId: "d51b9b31-9835-414a-b5b4-d0cb91151e6f", source: "marand", dateOfReferral: 1459987200000, referralFrom: "Dr <NAME>", referralTo: "Dr <NAME>" }, ``` <file_sep>/pages/angular/ui-kit/ui-kit-page.md --- title: Core UI keywords: mydoc sidebar: angular_sidebar toc: false permalink: ui-kit-original.html folder: angular/ui-kit --- This section contains description for UI elements. ## Button with drop-down selector {% include image.html file="ui-kit/drop-down.png" alt="drop-down selector" caption="" %} ``` <div uib-dropdown="" class="control-group left control-search-select dropdown"> <button uib-dropdown-toggle="" class="btn btn-success btn-inverse btn-dropdown-toggle btn-search-toggle dropdown-toggle" ng-click="$ctrl.closeSearchOptions()" aria-haspopup="true" aria-expanded="false"><i class="fa fa-bars"></i></button> <div uib-dropdown-menu="" class="dropdown-menu dm-panel dm-left dm-tables dm-search-select"> <div class="heading">Search Options</div> <div class="dm-wrap-list"> <div class="dm-list"> <div class="dm-item" ng-repeat="item in searchOptionsList" ng-click="$ctrl.openAdvancedSearch($index)"><span>{{item.name}}</span></div> </div> </div> </div> </div> ``` ## Input field {% include image.html file="ui-kit/input_field.png" alt="drop-down selector" caption="" %} ``` <input key-bind="" class="form-control ng-pristine ng-untouched ng-valid ng-empty" placeholder="Search" type="text"> ``` ## Button with icon {% include image.html file="ui-kit/button_with_icon.png" alt="drop-down selector" caption="" %} ``` <button ng-show="!searchActive &amp;&amp; !isOpenSearch" class="btn btn-success btn-search" ng-click="$ctrl.searchFunction();"><i class="fa fa-search"></i></button> ``` ## Back button, Logo icon, Logo text {% include image.html file="ui-kit/logo.png" alt="drop-down selector" caption="" %} ``` <a ng-click="$ctrl.goBack()" class="btn-header btn-header-prev ng-scope" ng-if="isShowPreviousBtn"><i class="fa fa-arrow-left"></i></a> <div class="wrap-logo"> <div class="logo"> <div class="logo-icon"> <a ng-click="$ctrl.goChart()"> <span class="img"></span> </a> </div> <div class="logo-text"> <a ng-click="$ctrl.goPatientList()"> <span class="ng-binding">IDCR</span> <span class="logo-mobile-hidden"></span> </a> </div> </div> </div> ``` ## Heading bar {% include image.html file="ui-kit/heading_bar.png" alt="drop-down selector" caption="" %} ``` <div class="header-title ng-binding">Patients Lists</div> ``` ## Breadcrumbs {% include image.html file="ui-kit/breadcrumbs.png" alt="drop-down selector" caption="" %} ``` <div class="breadcrumbs"></div> ``` ## Information / settings bar {% include image.html file="ui-kit/settings_bar.png" alt="drop-down selector" caption="" %} ``` <h3 class="panel-title"> Patient Info </h3> ``` ## Patient list single entity {% include image.html file="ui-kit/patient_list.png" alt="drop-down selector" caption="" %} ``` <table class="table table-striped table-bordered rwd-table table-sorted table-hover table-fixedcol table-patients-full"> <thead> <tr> <th></th> <th>&nbsp;</th> </tr> </thead> <tbody> <tr dir-paginate=""> <td></td> </tr> <tr ng-if="!$ctrl.patients.length"> <td colspan="6"><span class="label label-default">No patients found</span></td> </tr> </tbody> </table> ``` ## Agreement popup {% include image.html file="ui-kit/agreement_popup.png" alt="drop-down selector" caption="" %} ``` <div class="panel panel-secondary without-margin"> <div class="panel-heading"> <h3 class="panel-title">Patient Access Disclaimer</h3> </div> <div class="panel-body"> <div class="panel-body-inner"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec lobortis elit. Aenean mi nunc, feugiat ut aliquet non, iaculis vel tellus. Donec semper felis placerat, posuere nisi a, suscipit turpis. Integer sit amet lacus pellentesque, vestibulum libero id, sagittis nisi. Phasellus eleifend, neque eget vulputate semper, enim dui dictum neque, non iaculis felis augue at nunc. </div> <div class="panel-control"> <div class="wrap-control-group hide-indent-bottom"> <div class="control-group with-indent right"> <button class="btn btn-danger btn-icon-normal" ng-click="cancel()"><i class="fa fa-ban"></i> <span>Decline</span></button> <button class="btn btn-success" ng-click="ok()"><span>Agree</span></button> </div> </div> </div> </div> </div> ``` ## Patient banner {% include image.html file="ui-kit/patient_banner.png" alt="drop-down selector" caption="" %} ``` <div class="header-toolbar"> <div class="wrap-patient-info" ng-class="mobileShowInfo"> <div class="patient-info-caption"> <div class="patient-info-caption-btn btn-dropdown-toggle" ng-click="$ctrl.showInfo()"></div> <div class="patient-info-caption-text text-truncate ng-binding"><NAME></div> </div> <div class="patient-info"> <div class="patient-info-group-2"> <div class="column-1"> <div class="patient-info-item ng-binding"><span class="key">D.O.B.</span> 25-Jan-1974</div> <div class="patient-info-item ng-binding"><span class="key">Phone:</span> 0845 46 47</div> </div> <div class="column-2"> <div class="patient-info-item ng-binding"><span class="key">Gender:</span> Female</div> <div class="patient-info-item"><span class="key">NHS No.</span> <span ng-bind="$ctrl.patient.nhsNumber | formatNHSNumber" class="ng-binding">999 999 9050</span></div> </div> </div> <div class="patient-info-group-1"> <div class="patient-info-item significant hidden-xs ng-binding"><NAME></div> <div class="patient-info-item ng-binding"><span class="key">Doctor:</span> <NAME>.</div> </div> <div class="patient-info-item ng-binding"><span class="key">Address:</span> Port Glasgow Practice, 4872 Cubilia St., Port Glasgow, Renfrewshire, TQ3J 4JG</div> </div> </div></patients-banner-component></div> </div> ``` ## Left-hand menu button / heading list {% include image.html file="ui-kit/menu.png" alt="drop-down selector" caption="" %} ``` <ul class="nav"> <li class="navigation-menu" ng-repeat="link in $ctrl.linksCollection"> <a ng-click="$ctrl.goTo(link.link)" ng-class="{active: isActiveItem(link.link)}">{{link.title}}</a> </li> </ul> ``` ## Patient banner single block {% include image.html file="ui-kit/single_block.png" alt="drop-down selector" caption="" %} ``` <div class="board"> <div class="board-header"> <div class="control-group right"> <button class="btn btn-success btn-inverse btn-board-more" ng-click="$ctrl.goToSection(dashboard.toState)"><i class="fa fa-caret-right"></i></button> </div> <h3 class="board-title ng-binding">Problems</h3> </div> <div class="board-body"> <ul class="board-list"> <li></li> </ul> </div> </div> ``` ## Heading table node {% include image.html file="ui-kit/table_node.png" alt="drop-down selector" caption="" %} ``` <table class="table table-striped table-hover table-bordered rwd-table table-sorted table-fixedcol"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr></tr> <tr ng-if="!$ctrl.medications.length" class="ng-scope"> <td colspan="4"><span class="label label-default">No medications</span></td> </tr> </tbody> </table> ``` ## Heading table header / filter / settings {% include image.html file="ui-kit/table_header.png" alt="drop-down selector" caption="" %} ``` <div class="panel-heading"> <div class="control-group right"> <button class="btn btn-success btn-inverse btn-filter" ng-click="toggleFilter()"><i class="fa fa-filter"></i></button> </div> <h3 class="panel-title">All Medications</h3> <div class="panel-filter ng-hide" ng-show="isFilterOpen"> <div class="inner-addon addon-left"> <div class="addon"> <i class="fa fa-filter"></i> </div> <input type="text" id="filter" class="form-control ng-pristine ng-untouched ng-valid ng-empty" placeholder="Filter..." ng-model="queryFilter"> </div> </div> </div> ``` ## Details heading {% include image.html file="ui-kit/details_heading.png" alt="drop-down selector" caption="" %} ``` <div class="panel-heading"> <div class="control-group right"> <button class="btn btn-success btn-inverse btn-filter" ng-click="toggleFilter()"><i class="fa fa-filter"></i></button> </div> <h3 class="panel-title">All Medications</h3> <div class="panel-filter ng-hide" ng-show="isFilterOpen"> <div class="inner-addon addon-left"> <div class="addon"> <i class="fa fa-filter"></i> </div> <input type="text" id="filter" class="form-control ng-pristine ng-untouched ng-valid ng-empty" placeholder="Filter..." ng-model="queryFilter"> </div> </div> </div> ``` ## Details single instance {% include image.html file="ui-kit/details_single_instance.png" alt="drop-down selector" caption="" %} ``` <div class="form-group"> <label class="control-label">Problem / Diagnosis</label> <div class="form-control-static ng-binding">2E2</div> </div> ``` ## Pagination / Create button {% include image.html file="ui-kit/pagination.png" alt="drop-down selector" caption="" %} ``` <div class="panel-control"> <div class="wrap-control-group"> <div class="control-group with-indent left"> <dir-pagination-controls max-size="6" on-page-change="pageChangeHandler(newPageNumber)" boundary-links="false"></dir-pagination-controls> </div> <div class="control-group with-indent right" ng-if="$ctrl.currentUser.permissions.indexOf('WRITE') !== -1 && $ctrl.isShowCreateBtn"> <button class="btn btn-success btn-inverse btn-create" ng-click="$ctrl.create();"><i class="fa fa-plus"></i> <span>Create</span></button> </div> </div> </div> ``` ## Creation dialogue input {% include image.html file="ui-kit/creation_dialogue_input.png" alt="drop-down selector" caption="" %} ``` <div class="form-group"> <label for="text" class="control-label">Problem / Diagnosis</label> <div class="input-holder"> <input type="text" class="form-control input-sm ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" id="problem" name="problem" ng-model="diagnosis.problem" required=""> </div> <span class="help-block animate-fade ng-hide" ng-show="formSubmitted &amp;&amp; diagnosisForm.problem.$error.required">You must enter a value.</span> </div> ``` ## Non-editable creation input field {% include image.html file="ui-kit/author_input.png" alt="drop-down selector" caption="" %} ``` <div class="form-group"> <label for="author" class="control-label">Author</label> <div class="input-holder"> <input type="text" value="<EMAIL>" placeholder="<EMAIL>" class="form-control input-sm ng-pristine ng-untouched ng-valid ng-not-empty" id="author" name="author" ng-model="diagnosis.author" disabled=""> </div> <span class="help-block animate-fade ng-hide" ng-show="formSubmitted &amp;&amp; diagnosisForm.author.$error.required">You must enter a value.</span> </div> ``` ## Cancel / Complete buttons {% include image.html file="ui-kit/complete_buttons.png" alt="drop-down selector" caption="" %} ``` <div class="panel-control"> <div class="wrap-control-group hide-indent-bottom"> <div class="control-group with-indent right"> <button class="btn btn-danger" ng-click="$ctrl.cancel()"><i class="fa fa-ban"></i> Cancel</button> <button class="btn btn-success" ng-click="create(diagnosisForm, diagnosis)"><i class="fa fa-check"></i> Complete</button> </div> </div> </div> ``` ## Edit button {% include image.html file="ui-kit/edit_button.png" alt="drop-down selector" caption="" %} ``` <div class="panel-control ng-scope" ng-if="diagnosis.source !== 'vista'"> <div class="wrap-control-group"> <div class="control-group right"> <button class="btn btn-success btn-inverse btn-edit" ng-click="$ctrl.edit();"><i class="fa fa-edit"></i> Edit</button> </div> </div> </div> ``` ## Image details {% include image.html file="ui-kit/image_details.png" alt="drop-down selector" caption="" %} ``` <div class="panel-body"> <div class="panel-body-inner"> <div class="form"> <div class="form-group-wrapper"> <div class="form-control-static"> <cornerstone-image imageid="http://172.16.58.3:8086/instances/ecd967b0-aaec17a2-860b3925-91d8ef8b-1932d1c7/preview" class="ng-isolate-scope"><div id="dicomImage" oncontextmenu="return false" unselectable="on" onselectstart="return false;" onmousedown="return false;" style="width: 100%; height: 512px; margin: auto"><canvas width="464" height="512" style="width: 464px; height: 512px;"></canvas></div></cornerstone-image> </div> </div> </div> </div> </div> <div class="panel-control"> <div class="control-group center"> <button id="play" type="button" class="btn btn-inverse btn-success btn-none-border"><i class="fa fa-play"></i></button> <button id="stop" type="button" class="btn btn-inverse btn-success btn-none-border"><i class="fa fa-stop"></i></button> <div class="control-separate"></div> <button id="zoomIn" type="button" class="btn btn-inverse btn-success btn-none-border" ng-click="zoomOut()"><i class="fa fa-search-minus"></i></button> <button id="zoomOut" type="button" class="btn btn-inverse btn-success btn-none-border" ng-click="zoomIn()"><i class="fa fa-search-plus"></i></button> <div class="control-separate"></div> <button id="arrows" type="button" class="btn btn-inverse btn-success btn-none-border"><i class="fa fa-arrows"></i></button> <button id="verticalArrows" type="button" class="btn btn-inverse btn-success btn-none-border"><i class="fa fa-arrows-v"></i></button> </div> </div> </div> ``` ## Document import field {% include image.html file="ui-kit/document_import.png" alt="drop-down selector" caption="" %} ``` <div class="fgs-control"> <div class="wrap-control-group"> <div class="control-group right"> <button class="btn btn-primary" ng-click="importToCreate('diagnoses', $ctrl.clinicalDocument.diagnosisList[0])"><span>Import Data</span></button> </div> </div> </div> ``` ## Vitals details {% include image.html file="ui-kit/vitals-details.png" alt="drop-down selector" caption="" %} ``` <div class="row"> <div class="col-xs-12 col-md-6"> <div class="vitals-group highlighter-wrapper"> <span ng-class="getHighlighterClass('respirationRate')"></span> <label class="vitals-label">Respiration Rate</label> <div class="input-group vitals-holder popover-wrap" ng-class="vitalStatuses.respirationRate.type"> <div class="form-control input-sm">{{vital.respirationRate}}</div> <span class="vitals-addon popover-toggle" ng-click="togglePopover($event)">resps/min</span> <mc-popover-vital title="Respiration Rate" labels="{{popoverLabels.respirationRate}}"></mc-popover-vital> </div> </div> </div> <div class="col-xs-12 col-md-6"> <div class="vitals-group highlighter-wrapper"> <span ng-class="getHighlighterClass('oxygenSaturation')"></span> <label class="vitals-label">Oxygen Saturation</label> <div class="input-group vitals-holder popover-wrap" ng-class="vitalStatuses.oxygenSaturation.type"> <div class="form-control input-sm">{{vital.oxygenSaturation}}</div> <span class="vitals-addon popover-toggle" ng-click="togglePopover($event)">%</span> <mc-popover-vital title="Oxygen Saturation" labels="{{popoverLabels.oxygenSaturation}}"></mc-popover-vital> </div> </div> </div> </div> ``` ## Vitals tooltip {% include image.html file="ui-kit/vitals_tooltip.png" alt="drop-down selector" caption="" %} ``` <div class="popover-inner"> <h3 class="popover-title ng-binding">Respiration Rate</h3> <div class="popover-content"> <div class="range-vital-labels"> <img src="data:image/jpeg;base64 /> </div> </div> </div> ``` ## Clinical Statements Tag {% include image.html file="ui-kit/statements_tag.png" alt="drop-down selector" caption="" %} ``` <span class="label label-success ng-binding ng-scope" ng-repeat="(key, val) in $ctrl.clinicalStatement.tags track by $index">chestpain</span> ``` ## Clinical Statement creation popup {% include image.html file="ui-kit/statement_creation_popup.png" alt="drop-down selector" caption="" %} ``` <div class="dropdown-menu dm-panel dm-statements dm-small dm-top-left ng-scope" ng-if="!statements.length"> <div class="heading wrap-overflow"> <div class="pagination-heading">Tags</div> </div> <div class="dm-wrap-list"> <div class="dm-list"> <div class="dm-item ng-scope"><span class="ng-binding">acutesob</span></div> </div> </div> </div> ``` ## Patient Advanced Search popup {% include image.html file="ui-kit/patient_advanced_search.png" alt="drop-down selector" caption="" %} ``` <div mc-datepicker class="panel panel-secondary without-margin"> <div class="panel-heading"> <div class="control-group right"> <button class="btn btn-success btn-inverse btn-square btn-toggle-rotate" ng-click="cancel()"><i class="fa fa-chevron-up"></i></button> </div> <h3 class="panel-title"> <span>{{ctrl.option.name}}:</span> <span ng-if="searchParams.nhsNumber">NHS Number: {{searchParams.nhsNumber}}</span> </h3> </div> <div class="panel-body"> <div class="panel-body-inner"> <form name="advancedSearchForm" class="form"> <div class="form-group-wrapper"> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="form-group" ng-class="{'has-error': !$ctrl.detailsFocused && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber) && areDetailsFieldsClean(advancedSearchForm), 'has-success': !$ctrl.detailsFocused && advancedSearchForm.nhsNumber.$valid && advancedSearchForm.nhsNumber.$dirty}"> <label for="nhsNumber" class="control-label">NHS Number</label> <div class="input-holder"> <input type="text" tabindex="1" class="form-control input-sm" id="nhsNumber" name="nhsNumber" ng-model="searchParams.nhsNumber" focus-element="nhsNumberFocus" is-valid-nhs-number ng-focus="$ctrl.detailsFocused=false" ng-required="!$ctrl.detailsFocused" placeholder="e.g. 123 456 7890"/> </div> <span class="help-block animate-fade" ng-show="formSubmitted && advancedSearchForm.nhsNumber.$invalid && !$ctrl.detailsFocused">You must enter a value.</span> <span class="required-label" ng-show="!$ctrl.detailsFocused && isNhsNumberRequired(advancedSearchForm)">*Required</span> <span class="required-label" ng-show="!$ctrl.detailsFocused && isNhsNumberTooShort(advancedSearchForm.nhsNumber.$viewValue)">*NHS Number too short</span> <span class="required-label" ng-show="!$ctrl.detailsFocused && isNhsNumberTooLong(advancedSearchForm.nhsNumber.$viewValue)">*NHS Number too long</span> </div> </div> <div> </div> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="form-group" ng-class="{'has-error': advancedSearchForm.surname.$error.required && advancedSearchForm.surname.$invalid && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber), 'has-success': $ctrl.detailsFocused && advancedSearchForm.surname.$valid && advancedSearchForm.surname.$dirty && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber)}"> <label for="surname" class="control-label">Last Name</label> <div class="input-holder"> <input type="text" tabindex="2" class="form-control input-sm" id="surname" name="surname" ng-model="searchParams.surname" focus-element="surnameFocus" ng-focus="$ctrl.detailsFocused=true" ng-required='$ctrl.detailsFocused' placeholder="e. g. Smith"/> </div> <span class="help-block animate-fade" ng-show="formSubmitted && advancedSearchForm.surname.$error.required && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber)">You must enter a value.</span> <span class="required-label" ng-show="$ctrl.detailsFocused && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber) && (advancedSearchForm.surname.$invalid || advancedSearchForm.forename.$invalid || advancedSearchForm.dateOfBirth.$invalid)">*Required</span> </div> </div> <div class="col-xs-12 col-sm-6"> <div class="form-group" ng-class="{'has-error': advancedSearchForm.forename.$error.required && advancedSearchForm.forename.$invalid && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber), 'has-success': $ctrl.detailsFocused && advancedSearchForm.forename.$valid && advancedSearchForm.forename.$dirty && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber)}"> <label for="forename" class="control-label">First Name</label> <div class="input-holder"> <input type="text" tabindex="3" class="form-control input-sm" id="forename" name="forename" ng-model="searchParams.forename" ng-focus="$ctrl.detailsFocused=true" ng-required='$ctrl.detailsFocused' placeholder="e.g. John"/> </div> <span class="help-block animate-fade" ng-show="formSubmitted && advancedSearchForm.forename.$error.required && (advancedSearchForm.nhsNumber.$invalid || advancedSearchForm.nhsNumber.$pristine)">You must enter a value.</span> <span class="required-label" ng-show="$ctrl.detailsFocused && isNhsNumberFieldInvalid(advancedSearchForm.nhsNumber) && (advancedSearchForm.surname.$invalid || advancedSearchForm.forename.$invalid || advancedSearchForm.dateOfBirth.$invalid)">*Required</span> </div> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-4"> <div class="form-group"> <label for="selectAgeField" class="control-label">Select Age Params</label> <select class="form-control input-sm" tabindex="5" id="selectAgeField" name="selectAgeField" ng-model="selectAgeField"> <option value="range">Age Range</option> <option value="birthday">Birthday</option> </select> </div> </div> </div> </div> </form> </div> <div class="panel-control"> <div class="wrap-control-group hide-indent-bottom"> <div class="control-group with-indent right"> <button class="btn btn-danger btn-icon-normal" ng-click="cancel()"><i class="fa fa-times"></i> Close</button> <button class="btn btn-success btn-icon-normal" ng-click="ok(advancedSearchForm)"><i class="fa fa-search"></i> Search</button> </div> </div> </div> </div> </div> ``` ## Footer {% include image.html file="ui-kit/footer.png" alt="drop-down selector" caption="" %} ``` <footer class="footer"> <div class="container-fluid"> <div class="footer-povered"> <span>Powered By</span> <a href="#" class="footer-logo"> <img src="data:image/png;base64" /> </div> <p class="footer-text">IDCR POC</p> </div> </footer> ``` <file_sep>/pages/angular/plugin-tiles/angular-plugin-process.md --- title: Plugin development brief keywords: plugins process structure summary: "Guide to plugins development process" sidebar: angular_sidebar toc: false permalink: angular-plugin-process.html folder: angular/plugin-tiles filename: angular-plugin-process.md --- ## Plugin's development: To get started, copy the core project (https://github.com/PulseTile/PulseTile) for creating your functionality environment. ### We will use next 10 files in our plugin, below explanations of that files: #### example-list.component.js (Link to test file: [clinicalnotes-list.component.js](https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/clinical-notes/clinicalnotes-actions.js)) *It's a list.component functionality file (angular 1.5 component)* ``` //Called component's template. let templateClinicalnotesList = require('./clinicalnotes-list.html'); ``` ``` //Create es6 class with injected services for ClinicalnotesList component. class ClinicalnotesListController { constructor($scope, $state, $stateParams, $ngRedux, clinicalnotesActions, serviceRequests, ClinicalnotesModal, usSpinnerService) { ``` ``` //Connect to $ngRedux service for catching states. //Publish states to this.setCurrentPageData functions for detailed analysis let unsubscribe = $ngRedux.connect(state => ({ getStoreData: this.setCurrentPageData(state) }))(this); $scope.$on('$destroy', unsubscribe); ``` ``` //Create function for call request's methods. this.clinicalnotesLoad = clinicalnotesActions.all; this.clinicalnotesLoad($stateParams.patientId); ``` ``` // component template and controller initialization start const ClinicalnotesListComponent = { template: templateClinicalnotesList, controller: ClinicalnotesListController }; //injected services start here ClinicalnotesListController.$inject = ['$scope', '$state', '$stateParams', '$ngRedux', 'clinicalnotesActions', 'serviceRequests', 'ClinicalnotesModal', 'usSpinnerService']; export default ClinicalnotesListComponent; //injected services end here ``` #### example-list.html (Link to test file: [clinicalnotes-list.html](https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/clinical-notes/clinicalnotes-list.html)) *It is a HTML template file for the list.component - basically, an HTML template for the page. Pretty self-explanatory if you are familiar with HTML* #### example-detail.component.js *It's detail.component functionality file (angular 1.5 component) - used to display a detailed view of particular element, chosen in the left-hand list of items* ``` let templateClinicalnotesDetail = require('./clinicalnotes-detail.html'); class ClinicalnotesDetailController {} ``` #### example-detail.html *It is a HTML Template file for the detail.component* #### example-modal.js *It's modal functionality file (should be added to plugin if the modal window is necessary)* ``` //Create es6 export functions for Modal module and inject certain services or modules. //openModal function called for init/open modal popup in other components. //modalInstance instance from $uibModal service (bootstrap). export default function ClinicalnotesModal($uibModal, clinicalnotesActions, $stateParams) { var isModalClosed = true; var openModal = function (patient, modal, clinicalNote, currentUser) { if (isModalClosed) { isModalClosed = false; var modalInstance = $uibModal.open({ template: require('./clinicalnotes-modal.html'), size: 'lg', controller: function ($scope, $state, $uibModalInstance) {} }); }; return { isModalClosed: isModalClosed, openModal: openModal }; } ClinicalnotesModal.$inject = ['$uibModal', 'clinicalnotesActions', '$stateParams']; ``` #### example-modal.html *It is HTML Template file for the modal window (it should be added in the plugin, if a modal window is necessary)* #### index.route.js (Link to the file: [index.route.js](https://github.com/PulseTile/PulseTile/blob/develop/src/app/index.route.js)) *File with routes for core application* ``` //Create route state for application's pages routing. //Object views contains parts for current page/state. .state('clinicalNotes', { url: '/patients/{patientId:int}/clinicalNotes?reportType&searchString&queryType', views: { banner: {template: '<patients-banner-component></patients-banner-component>'}, actions: {template: '<patients-sidebar-component></patients-sidebar-component>'}, main: {template: '<clinicalnotes-list-component></clinicalnotes-list-component>'} } }) .state('clinicalNotes-detail', { url: '/patients/{patientId:int}/clinicalNotes/{clinicalNoteIndex}?filter&page&reportType&searchString&queryType&source', views: { banner: {template: '<patients-banner-component></patients-banner-component>'}, actions: {template: '<patients-sidebar-component></patients-sidebar-component>'}, main: {template: '<clinicalnotes-list-component></clinicalnotes-list-component>'}, detail: {template: '<clinicalnotes-detail-component></clinicalnotes-detail-component>'} }, params: { source: '{}' } }) ``` #### example-actions.js (Link to file: [clinicalnotes-actions.js](https://github.com/PulseTile/PulseTile/blob/develop/src/app/pulsetileui/pages/clinical-notes/clinicalnotes-actions.js)) *This file contains actions functions for redux architecture* ``` //ES6 import redux instance and redux actions. import {bindActionCreators} from 'redux'; import * as types from '../../../constants/ActionTypes'; ``` ``` //Create es6 export function with request name all. export function all(patientId) { return { types: [types.CLINICALNOTES, types.CLINICALNOTES_SUCCESS, types.CLINICALNOTES_ERROR], shouldCallAPI: (state) => !state.contacts.response, //Call an API to get a necessary data for clinical notes config: { method: 'get', url: '/api/patients/' + patientId + '/clinicalNotes' }, meta: { timestamp: Date.now() } }; } ``` ``` //In the end of file need create export default function which contains requests functions and injected //$ngRedux service. export default function clinicalnotesActions($ngRedux) { let actionCreator = { all, get, create, update }; return bindActionCreators(actionCreator, $ngRedux.dispatch); } clinicalnotesActions.$inject = ['$ngRedux']; ``` #### example-reducer-name.js *It contains reducer functions for redux architecture* ``` //ES6 import redux actions. import * as types from '../../../constants/ActionTypes'; ``` ``` //Creation of INITIAL_STATE object with default parameters for redux states. const INITIAL_STATE = { isFetching: false, //isFetching state error: false, //error state data: null, //data state dataGet: null, //dataGet state dataCreate: null, //dataCreate state dataUpdate: null //dataUpdate state }; ``` ``` //Here we are creating ES6 export default function contacts to watch redux states changes. export default function contacts(state = INITIAL_STATE, action) { const {payload} = action; var actions = { [types.CLINICALNOTES]: (state) => { return Object.assign({}, state, { isFetching: true, error: false }); } } return actions[action.type] ? actions[action.type](state) : state; } ``` #### ActionTypes.js *This file contains actions constants for redux architecture* ``` //Create name of actions for redux state. export const CLINICALNOTES = 'CLINICALNOTES'; export const CLINICALNOTES_SUCCESS = 'CLINICALNOTES_SUCCESS'; export const CLINICALNOTES_ERROR = 'CLINICALNOTES_ERROR'; export const CLINICALNOTES_GET = 'CLINICALNOTES_GET'; export const CLINICALNOTES_GET_SUCCESS = 'CLINICALNOTES_GET_SUCCESS'; export const CLINICALNOTES_GET_ERROR = 'CLINICALNOTES_GET_ERROR'; export const CLINICALNOTES_CREATE = 'CLINICALNOTES_CREATE'; export const CLINICALNOTES_CREATE_SUCCESS = 'CLINICALNOTES_CREATE_SUCCESS'; export const CLINICALNOTES_CREATE_ERROR = 'CLINICALNOTES_CREATE_ERROR'; export const CLINICALNOTES_UPDATE = 'CLINICALNOTES_UPDATE'; export const CLINICALNOTES_UPDATE_SUCCESS = 'CLINICALNOTES_UPDATE_SUCCESS'; export const CLINICALNOTES_UPDATE_ERROR = 'CLINICALNOTES_UPDATE_ERROR'; ``` Create the github repository for your separate module/plugin. Run the following command within your command line: npm/bower install moduleName (Module name here stands for github url for external plugin) `bower i https://github.com/Plugin-for-PulseTile.git` *We are downloading the module from external repository to root application directory* To copy files from node_modules/bower_components use: webpack.config.js --> CopyWebpackPlugin, change path in it's options { from: '', to: '' } *Here we are copying module files from source folder to destination folder* `npm run copy` *Running the copy command itself*
d63d07024bbe470da71f48eebf6fc83409fba61e
[ "Markdown", "HTML", "Shell" ]
34
Markdown
PulseTile/PulseTile-Docs
4b2f1d9ca10d06f9135355db54e86a5fe5b91364
747ea6834bb9216ef90666cdd5939a63db3764ff
refs/heads/master
<file_sep># baidu-gps-transform java实现调用百度坐标转换api将gps坐标转换成百度坐标 <file_sep>import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import com.google.gson.*; import static java.lang.System.out; public class Main { private static String connectURL(String dest_url, String commString) { String rec_string = ""; URL url = null; HttpURLConnection urlconn = null; OutputStream out1 = null; BufferedReader rd = null; try { url = new URL(dest_url); urlconn = (HttpURLConnection) url.openConnection(); urlconn.setReadTimeout(1000 * 30); //urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8"); urlconn.setRequestMethod("POST"); urlconn.setDoInput(true); urlconn.setDoOutput(true); out1 = urlconn.getOutputStream(); out1.write(commString.getBytes("UTF-8")); out1.flush(); out1.close(); rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); StringBuffer sb = new StringBuffer(); int ch; while ((ch = rd.read()) > -1) sb.append((char) ch); rec_string = sb.toString(); } catch (Exception e) { out.println(e); return ""; } finally { try { if (out1 != null) { out1.close(); } if (urlconn != null) { urlconn.disconnect(); } if (rd != null) { rd.close(); } } catch (Exception e) { out.println(e); } } return rec_string; } public static void main(String[] args) throws IOException { File file = new File("data/drivingdatarealpos.txt"); File ofile = new File("data/drivingdatarealposbaidu.txt"); Reader r1 = new FileReader(file); Writer w1 = new FileWriter(ofile); BufferedReader r = new BufferedReader(r1); BufferedWriter w = new BufferedWriter(w1); JsonParser parse =new JsonParser(); //创建json解析器 while (r.ready()) { String l = r.readLine(); String result = connectURL("http://api.map.baidu.com/geoconv/v1/?coords=" + l + "&from=1&to=5&output=json&ak=eA7U8IzN1oX6EZj7r0y7ynsGXfUENK2c", ""); JsonObject json=(JsonObject) parse.parse(result); //创建jsonObject对象 JsonElement e = json.get("result").getAsJsonArray().get(0); double lo = e.getAsJsonObject().get("x").getAsDouble(); double la = e.getAsJsonObject().get("y").getAsDouble(); w.write(lo+","+la+"\n"); w.flush(); out.println("转换坐标ok:" + l); } w.flush(); String coords = "106.6519570767,26.6245856997"; String result = connectURL("http://api.map.baidu.com/geoconv/v1/?coords=" + coords + "&from=1&to=5&output=json&ak=eA7U8IzN1oX6EZj7r0y7ynsGXfUENK2c", ""); out.println(result); r.close(); r1.close(); w.close(); w1.close(); } }
4b52c3ee024f162533bdc719da3e2037604d43fa
[ "Markdown", "Java" ]
2
Markdown
Yves-yuan/baidu-gps-transform
df9a349a936d4163c89cafb5274426dc9e6a9f4f
bff8b579ddc4348cb98d5d5c8d4524f9d1862b2e
refs/heads/master
<file_sep>/* 环图组件对象 */ var H5ComponentRing = function(name, cfg){ var component = new H5ComponentBase(name, cfg); var w = cfg.width/2; var h = cfg.height/2; var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); component.append(cns); cns.width = ctx.width =w; cns.height = ctx.height = h; var step = cfg.data.length; $(cns).css('zIndex',1); //背景层 var r=w/2; ctx.arc(r,r,r,0,2*Math.PI); ctx.fillStyle="#eee"; ctx.fill(); //数据层 var sAnger = 1.5*Math.PI; var aAnger = (2*Math.PI); var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); $(cns).css('zIndex',2); component.append(cns); cns.width = ctx.width =w; cns.height = ctx.height = h; var eAnger = sAnger + aAnger * cfg.data[0][1]; ctx.beginPath(); ctx.moveTo(r,r); ctx.arc(r,r,r-1,sAnger,eAnger); ctx.fillStyle = cfg.data[0][2]?cfg.data[0][2]:'#d2d2d2'; ctx.fill(); //文本信息 var text = $('<div class="text"></div>'); text.html(cfg.data[0][0]+'<br />'+cfg.data[0][1]*100+'%'); text.css('transition','all 0.5s 1s'); component.append(text); //遮罩层 var cns1 = document.createElement('canvas'); var ctx1 = cns1.getContext('2d'); component.append(cns1); $(cns1).css('zIndex',3); cns1.width = ctx1.width =w; cns1.height = ctx1.height = h; ctx1.lineWidth = 1; ctx1.fillStyle = '#eee'; ctx1.strokeStyle = '#eee'; //遮罩层动画 function animatepie(per){ ctx1.clearRect(0,0,w,h); ctx1.beginPath(); ctx1.moveTo(r,r); if(per<=0){ ctx1.arc(r,r,r,0,2*Math.PI); }else{ ctx1.arc(r,r,r,sAnger,sAnger+2*Math.PI*per,true); } ctx1.fill(); } //中间遮罩层 var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); component.append(cns); $(cns).css('zIndex',4).css('border-radius','50%').css({top:'10%',left:'10%'}); cns.width = ctx.width =w*0.8; cns.height = ctx.height = h*0.8; ctx.lineWidth = 1; ctx.fillStyle = '#fff'; ctx.strokeStyle = '#fff'; ctx.arc( (w*0.8)/2, (w*0.8)/2, (w*0.8)/2,sAnger,sAnger+2*Math.PI); ctx.fill(); animatepie(0); component.on('onLoad',function(){ var per = 0; setTimeout(function(){ var t = setInterval(function(){ per=per+0.01; animatepie(per); if(per>=1){ clearInterval(t); } },10) },500) }); component.on('onLeave',function(){ var per = 1; var t = setInterval(function(){ per=per-0.01; animatepie(per); if(per<=0){ clearInterval(t); } },10) }); return component; } <file_sep># webApp 组件化开发webApp 案例 通过慕课网上的课程,研究并动手做了这个demo,第一次采用前端组件化的方式开发一个项目,好处还是很多: - 能够更好的扩展 - 能够更好的维护 - 代码目录结构更加清晰 <file_sep>/* 柱图组件对象 */ var H5ComponentPolyline = function(name, cfg){ var component = new H5ComponentBase(name, cfg); var w = cfg.width/2; var h = cfg.height/2; var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); component.append(cns); cns.width = ctx.width =w; cns.height = ctx.height = h; //设值名称 //水平线 var step = 10; ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle='#aaa'; for (var i = 0; i < step+1; i++) { var y = (h/step)*i; ctx.moveTo(0,y); ctx.lineTo(w,y); } step = cfg.data.length; //竖线 for (var i = 0; i < step+2; i++) { var x = (w/(step+1))*i; ctx.moveTo(x,0); ctx.lineTo(x,h); if(cfg.data[i]){ var text = $("<div class='text'></div>"); text.text(cfg.data[i][0]); text.css({left:x,bottom:"-20px",width:(w/(step+1)),marginLeft:(w/(step+1))/2}); component.append(text); } } ctx.stroke(); //数据层 var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); component.append(cns); cns.width = ctx.width =w; cns.height = ctx.height = h; function animatePoly(ctx,per){ ctx.clearRect(0,0,w,h); //画点 ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle='#ff8878'; //点 var x = y =0 ; for( i in cfg.data){ x = (w/(cfg.data.length+1))*i+(w/(cfg.data.length+1)); y = h*(1-cfg.data[i][1]*per); ctx.moveTo(x,y); ctx.arc(x,y,3,0,2*Math.PI); cfg.data[i][2] && (ctx.fillStyle = cfg.data[i][2]); ctx.fillText(cfg.data[i][1],x-8,y-10); } ctx.moveTo((w/(cfg.data.length+1)),h*(1-cfg.data[0][1]*per)); for( i in cfg.data){ x = (w/(cfg.data.length+1))*i+(w/(cfg.data.length+1)); y = h*(1-cfg.data[i][1]*per); ctx.lineTo(x,y); } ctx.stroke(); //绘制阴影 ctx.lineTo(x,h); ctx.lineTo(w-x,h); ctx.fillStyle="rgba(255, 136, 120, 0.5)"; ctx.fill(); } component.on('onLoad',function(){ var per = 0; setTimeout(function(){ var t = setInterval(function(){ per=per+0.01; animatePoly(ctx,per); if(per>=1){ clearInterval(t); } },10) },500) }); component.on('onLeave',function(){ var per = 1; var t = setInterval(function(){ per=per-0.01; animatePoly(ctx,per); if(per<=0){ clearInterval(t); } },10) }); return component; } <file_sep>/* 基本图文组件对象 */ var H5ComponentBase = function(name,cfg){ var cfg = cfg || {}; var id = ('h5_c_'+Math.random() ).replace(".","_"); var cls = 'h5_component_'+cfg.type+' h5_component_name_'+name; var component = $('<div class="h5_component '+cls+'" id="'+id+'"></div>'); cfg.text && component.text(cfg.text); cfg.width && component.width(cfg.width/2); cfg.height && component.height(cfg.height/2); cfg.css && component.css(cfg.css); cfg.bg && component.css('background-image','url('+cfg.bg+')'); cfg.center && component.css({ 'margin-left':-(cfg.width/4), 'left' :'50%' }); if(typeof cfg.onclick == 'function'){ component.click(cfg.onclick); } component.on('onLeave',function(){ var that = this; setTimeout(function(){ $(that).addClass('h5_component_'+name+'_onLeave'); $(that).removeClass('h5_component_'+name+'_onLoad'); cfg.animateOut && $(that).animate(cfg.animateOut); },cfg.delay || 0); return false; }); component.on('onLoad',function(){ var that = this; setTimeout(function(){ $(that).addClass('h5_component_'+name+'_onLoad'); $(that).removeClass('h5_component_'+name+'_onLeave'); cfg.animateIn && $(that).animate(cfg.animateIn); },cfg.delay || 0); return false; }); return component; } <file_sep>/* 散点图表组件对象 */ var H5ComponentPoint = function(name, cfg){ var component = new H5ComponentBase(name, cfg); $.each(cfg.data,function(idx,item){ var point = $('<div class="point" id="'+idx+'"></div>'); var pre = item[1]/cfg.data[0][1]*100+'%'; var name = $('<div class="name">'+item[0]+'</div>'); var marks = $('<div class="marks">'+item[1]*100+'%'+'</div>'); name.appendTo(point); marks.appendTo(name); point.width(pre) .height(pre) .css("background-color",item[2]) .appendTo(component); point.css('transition','all 1s '+idx*.5+'s') item[3] && point.css('left',item[3]); item[4] && point.css('top',item[4]); }); component.find('.point').on('click',function(){ component.find('.point').removeClass('point_focus'); $(this).addClass('point_focus'); return false; }).eq(0).addClass('point_focus') return component; } <file_sep>var H5_loading = function(images,fistPage){ var id = this.id; if(this._image === undefined){ this._image = (images || []).length; this.loaded = 0; window[id] = this; for(s in images){ var items = images[s]; var img = new Image(); img.onload = function(){ window[id].loader(); } img.src = items; } $("#rate").text('0%'); return this; }else{ this.loaded ++ ; $("#rate").text(((this.loaded/this._image) *100 >> 0) +'%'); if(this.loaded < this._image) { return this; } } this.el.fullpage({ onLeave:function(index,nextIndex,direction){ $(this).find(".h5_component").trigger('onLeave'); }, afterLoad:function(index,nextIndex,direction){ $(this).find(".h5_component").trigger('onLoad'); } }); this.el.find(".h5_page:eq(0) .h5_component").trigger('onLoad'); this.el.show(); fistPage && $.fn.fullpage.moveTo(fistPage); }<file_sep>/* 柱图组件对象 */ var H5ComponentBar = function(name, cfg){ var component = new H5ComponentBase(name, cfg); $(cfg.data).each(function(idx,item){ var line = $("<div class='line'></div>"); var name = $("<div class='name'>"+item[0]+"</div>"); var marks = item[1]*100+"%"; var pre = $("<div class='pre'>"+marks+"</div>"); var color = ['red','green','blue','gray','#ccc','#ffaaaa','#ccaadd']; var bg = item[2] || color[idx]; var progress = $("<div class='progress' style='width:"+marks+"'><div class='bg' style='background:"+bg+"'></div></div>"); pre.css('left',marks); line.append(name).append(progress).append(pre); component.append(line); }); return component; } <file_sep>/* 雷达图组件对象 */ var H5ComponentRadar = function(name, cfg){ var component = new H5ComponentBase(name, cfg); var w = cfg.width/2; var h = cfg.height/2; var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); component.append(cns); cns.width = ctx.width =w; cns.height = ctx.height = h; var step = cfg.data.length; //画圆 var r = w/2; var iscolor = true; for (var s = 10; s > 0; s--) { ctx.beginPath(); //背景正多边形 for (var i = 0; i < step; i++) { var rad = (2*Math.PI/360)*(360/step)*i; var x = r+Math.sin(rad)*r * (s/10); var y = r+Math.cos(rad)*r *(s/10); if(i==0){ ctx.moveTo(x,y); } ctx.lineTo(x,y); } ctx.fillStyle = (iscolor = !iscolor)?'#f1f9ff':'#99c0ff'; ctx.fill(); ctx.closePath(); } ctx.beginPath(); //绘制伞骨 for (var i = 0; i < step; i++) { var rad = (2*Math.PI/360)*(360/step)*i; var x = r+Math.sin(rad)*r; var y = r+Math.cos(rad)*r; ctx.moveTo(r,r); ctx.lineTo(x,y); //数据名称 var text = $('<div class="text"></div>'); text.text(cfg.data[i][0]); component.append(text); if(x<(w/2)){ text.css('right',(w-x)); }else{ text.css('left',x); } if(y<h/2){ text.css('bottom',(h-y)); }else{ text.css('top',y); } text.css('transition','all 0.5s '+(1+i*0.5)+'s'); } ctx.strokeStyle = '#aaa'; ctx.stroke(); var cns = document.createElement('canvas'); var ctx = cns.getContext('2d'); cns.width = ctx.width =w; cns.height = ctx.height = h; component.append(cns); //数据 function animateRadar(per){ ctx.clearRect(0,0,w,h); ctx.beginPath(); //数据圆点 for (var i = 0; i < step; i++) { var rad = (2*Math.PI/360)*(360/step)*i; var x = r+Math.sin(rad)*r * (per)*cfg.data[i][1]; var y = r+Math.cos(rad)*r *(per)*cfg.data[i][1]; ctx.moveTo(x,y); ctx.arc(x,y,3,0,2*Math.PI); ctx.fillStyle = '#ff7676'; ctx.fill(); } //数据线 for (var i = 0; i < step; i++) { var rad = (2*Math.PI/360)*(360/step)*i; var x = r+Math.sin(rad)*r * (per)*cfg.data[i][1]; var y = r+Math.cos(rad)*r *(per)*cfg.data[i][1]; if(i==0){ ctx.moveTo(x,y); } ctx.lineTo(x,y); } ctx.strokeStyle = '#cd5f7e'; ctx.closePath(); ctx.stroke(); } component.on('onLoad',function(){ var per = 0; setTimeout(function(){ var t = setInterval(function(){ per=per+0.01; animateRadar(per); if(per>=1){ clearInterval(t); } },10) },500) }); component.on('onLeave',function(){ var per = 1; var t = setInterval(function(){ per=per-0.01; animateRadar(per); if(per<=0){ clearInterval(t); } },10) }); return component; }
60077a25b5d29e007f178db4368730257bfaa2c7
[ "JavaScript", "Markdown" ]
8
JavaScript
FengLin2016/webApp
23218b281c929adcf7b9e6e0a4c554ea5a98345c
b11783e8cf2cceee9de14e4a977e512a3525483f
refs/heads/master
<repo_name>leetschau/DeepLearningWithPython<file_sep>/one_hot.py import numpy as np import string # code listing 6.1 samples = ['The cat sat on the mat.', 'The dog ate my homework.', 'Some other new sentence.', 'A very long and complex sentence whose length exceeds the max_length.'] token_index = {} for sample in samples: for word in sample.split(): if word not in token_index: token_index[word] = len(token_index) + 1 print('token_index:', token_index) max_length = 10 # 每个 sample 中单词的最大长度,超出的10个单词的句子只截取前10个单词 results = np.zeros(shape=(len(samples), max_length, max(token_index.values()) + 1)) for i, sample in enumerate(samples): for j, word in list(enumerate(sample.split()))[:max_length]: # 这里通过 :max_length 实现了截取操作 index = token_index.get(word) results[i, j, index] = 1. print('shape of results:', results.shape) # code listing 6.2 characters = string.printable token_index = dict(zip(characters, range(1, len(characters) + 1))) print('token_index:', token_index) max_length = 50 results = np.zeros((len(samples), max_length, max(token_index.values()) + 1)) for i, sample in enumerate(samples): # print('sample:', sample) for j, character in enumerate(sample[:max_length]): index = token_index.get(character) # print('char and index: %s, %s' % (character, index)) results[i, j, index] = 1. print('shape of results:', results.shape) # code listing 6.3 from keras.preprocessing.text import Tokenizer tokenizer = Tokenizer(num_words=1000) tokenizer.fit_on_texts(samples) one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary') one_hot_results.shape # (4, 1000), 其中 4 表示 samples 包含4个元素,1000表示每个元素(句子)被编码为长度为1000的向量 # 编码只能反映一个句子包含哪些单词,丢掉了单词前后顺序信息 word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) # code listing 6.4 dimensionality = 1000 # 整个 samples 中单词的容量 max_length = 12 # 一个 sample 最多包含的单词数 results = np.zeros((len(samples), max_length, dimensionality)) for i, sample in enumerate(samples): for j, word in list(enumerate(sample.split()))[:max_length]: index = abs(hash(word)) % dimensionality results[i, j, index] = 1. print(results.shape) # (4, 12, 1000) # 与 6.3 的实现方法相比,增加了一个维度,体现出了单词的顺序 <file_sep>/imdb_word_embedding.py # code listing 6-8 import os from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding, Flatten, Dense import numpy as np import matplotlib.pyplot as plt imdb_dir = './aclImdb' train_dir = os.path.join(imdb_dir, 'train') labels = [] texts = [] for label_type in ['neg', 'pos']: dir_name = os.path.join(train_dir, label_type) for fname in os.listdir(dir_name): if fname[-4:] == '.txt': f = open(os.path.join(dir_name, fname)) texts.append(f.read()) f.close() if label_type == 'neg': labels.append(0) else: labels.append(1) # 共 25000 个文本文件,前一半在 neg 文件夹里,对应 label 为 0 # 后一半在 pos 文件夹里,对应 label 为 1 # code listing 6-9 maxlen = 100 training_samples = 200 validation_samples = 10000 max_words = 10000 tokenizer = Tokenizer(num_words=max_words) tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) # this is a list, whose element is a integer list # the length of the integer list is the word count # in the corresponding txt file word_index = tokenizer.word_index print("Found %s unique tokens." % len(word_index)) data = pad_sequences(sequences, maxlen=maxlen) # 将长度不一致的 sequences 各个元素(都是 List[int])的长度都填充/截断为 # maxlen 长度,转为形状为 (25000, 100) 的 numpy.ndarray 赋给 data labels = np.asarray(labels) print('Shape of data tensor:', data.shape) print('Shape of label tensor:', labels.shape) indices = np.arange(data.shape[0]) np.random.shuffle(indices) # 对 indices 做 in-place 修改,详细说明见 ?np.random.shuffle data = data[indices] # 这样对变量做 in-place 修改是不好的 labels = labels[indices] x_train = data[:training_samples] y_train = labels[:training_samples] x_val = data[training_samples: training_samples + validation_samples] y_val = labels[training_samples: training_samples + validation_samples] # code listing 6-10 glove_dir = './glove.6B' embeddings_index = {} # glove.6B.100d.txt 文件每行包含101个元素,彼此用空格分隔, # 第一个是一个英文单词,后面是100个实数 f = open(os.path.join(glove_dir, 'glove.6B.100d.txt')) for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Found %s word vectors' % len(embeddings_index)) # code list 6-11 embedding_dim = 100 embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in word_index.items(): if i < max_words: embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector # code listing 6-12 model = Sequential() model.add(Embedding(max_words, embedding_dim, input_length=maxlen)) model.add(Flatten()) model.add(Dense(32, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.summary() # code listing 6-13, 使用预训练嵌入层 model.layers[0].set_weights([embedding_matrix]) model.layers[0].trainable = False # code listing 6-14 model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val)) model.save_weights('pre_trained_glove_model.h5') # code listing 6-15 acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'ro', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'ro', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # code listing 6-16, 不使用预训练嵌入层 # 即没有对 embedding 层(第0层)做 set_weights 操作 model2 = Sequential() model2.add(Embedding(max_words, embedding_dim, input_length=maxlen)) model2.add(Flatten()) model2.add(Dense(32, activation='relu')) model2.add(Dense(1, activation='sigmoid')) model2.summary() model2.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history2 = model2.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=[x_val, y_val]) acc2 = history2.history['acc'] val_acc2 = history2.history['val_acc'] loss2 = history2.history['loss'] val_loss2 = history2.history['val_loss'] epochs2 = range(1, len(acc2) + 1) plt.plot(epochs2, acc2, 'ro', label='Training acc') plt.plot(epochs2, val_acc2, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs2, loss2, 'ro', label='Training loss') plt.plot(epochs2, val_loss2, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # code listing 6-17 对测试集数据分词 test_dir = os.path.join(imdb_dir, 'test') labels = [] texts = [] for label_type in ['neg', 'pos']: dir_name = os.path.join(test_dir, label_type) for fname in sorted(os.listdir(dir_name)): if fname[-4:] == '.txt': f = open(os.path.join(dir_name, fname)) texts.append(f.read()) f.close() if label_type == 'neg': labels.append(0) else: labels.append(1) sequences = tokenizer.texts_to_sequences(texts) x_test = pad_sequences(sequences, maxlen=maxlen) y_test = np.asarray(labels) # code listing 6-18 model.load_weights('pre_trained_glove_model.h5') model.evaluate(x_test, y_test) <file_sep>/imdb_exp.py # explanations of imdb_cls.py import numpy as np from imdb_cls import train_data results = np.zeros((len(train_data), 10000)) results[0, [3,4,5,4,2]] = 3 # 可以通过 list 给 numpy.ndarray 的某个维度的多个元素一次性赋值, # 且 list 中可以包含重复的值,例如上面 [3,4,5,4,2] 中的 4, # 但最终的效果和 [2,3,4,5] 一样 print(results[0:5, 0:5]) train_enum = enumerate(train_data) i, sequence = next(train_enum) assert sequence == train_data[0] results[0,:] = 0 # 回退到初始状态 results[i, sequence] = 1 # 将第一条评论的所有单词 index 设置为1,丢失了单词的顺序和次数信息 # 例如 "this movie is so so so good" 和 "so good this movie" 被 `vectorize_sequences` # 处理后的结果应该是一样的 <file_sep>/jena_load_data.py """读取源数据,定义数据加载函数 """ import numpy as np def data_gen(data, lookback, delay, min_index, max_index, shuffle=False, batch_size=128, step=6): """生成历史和预测数据集 算法执行过程:首先在合理区间里找出一系列时间基准值保存在 rows 中, 根据 shuffle 的取值以及上次取值结束位置(保存在 i 中), 这个合理区间可能是:(min_index + lookback, max_index), 或者 (i, i + batch_size), (i, max_index)。 对 rows 的每个元素 row,以 row - lookback 为左边界、 row 为右边界、step 为间隔,生成一系列历史数据采样点, 将这些时间点上所有 14 个测量值被放入 samples 中, 将 row + delay 时间点上的温度值作为标签(预测值,与算法给出的预测结果比较) 放入 target 里。 本例中,一个批量取 128 个样本,一个样本有一个基准时间, 向前推10天,在这个区间内等间隔取240个点(每1小时采样一次), 每个点上取源数据中所有14个物理测量值,形成一个 240 x 14 的矩阵作为预测依据, 再取基准时间后1天的温度作为预测目标。 Parameters: data (numpy.ndarray): 本例中为 420551 行,14 列 lookback (int): 历史数据长度,本例中为 1440,即 10 天(原始数据间隔为10分钟); delay: 从基准时间(lookback 的结束时间点)向后推 delay 时间,预测目标是这个时间点上的温度值 min_index (int): 历史区间的左边界 max_index (int): 历史区间的右边界 batch_size (int): 样本个数 step: 采样点时间间隔,本例中 6 表示每 6 个点采样一次,即采用间隔为 1 小时 Returns: tuple: 包含(历史 预测)二元组, 第一部分是形状为 (batch_size, lookback/step, feature_number), 本例中为 (128, 240, 14) 的 numpy.ndarray, 第二部分(预测)是一个长度为 batch_size 的一元 ndarray, 本例中形状为 (128,)。 """ if max_index is None: max_index = len(data) - delay - 1 # 防止 target 取值时数组下标右越界 i = min_index + lookback # 防止 samples 向回取历史值(保存在 indices 里)时左越界 while 1: if shuffle: rows = np.random.randint(min_index + lookback, max_index, size=batch_size) # rows 的每个元素以自己为右边界,生成一个时间序列作为历史和一个预测值, # 彼此之间没有顺序,所以可以乱序。 else: if i + batch_size >= max_index: i = min_index + lookback rows = np.arange(i, min(i + batch_size, max_index)) i += len(rows) samples = np.zeros((len(rows), lookback // step, data.shape[-1])) # data 的最后一个维度,即除时间戳外的特征数,14 targets = np.zeros((len(rows),)) for j, row in enumerate(rows): indices = range(rows[j] - lookback, rows[j], step) samples[j] = data[indices] targets[j] = data[rows[j] + delay][1] yield samples, targets fname = './jena_climate_2009_2016.csv' with open(fname, 'r') as f: rawlines = f.readlines() striped = map(lambda x: x.strip(), rawlines) header = next(striped).split(',') lines = list(striped) print('Header:', header) print('Number of data lines:', len(lines)) float_data = np.zeros((len(lines), len(header) - 1)) # 在 header 包含的列数上 -1 是因为不包含时间列 for i, line in enumerate(lines): values = [float(x) for x in line.split(',')[1:]] float_data[i] = values mean = float_data[:200000].mean(axis=0) float_data -= mean std = float_data[:200000].std(axis=0) float_data /= std <file_sep>/README.md # Intro Run the codes: ``` $ conda activate r-tensorflow $ ipython > %load imdb.py ``` Reference: * [fchollet/deep-learning-with-python-notebooks](https://github.com/fchollet/deep-learning-with-python-notebooks) <file_sep>/dogs_vs_cats/README.md # Intro This folder is for chapter 5. I didn't use Python scripts in the origin codes (which is too verbose for this task). The equivalent shell script is as follows (the training picture files is downloaded and extracted to folder *~/Downloads/dogs-vs-cats*): ``` mkdir -p train/{cats,dogs} validation/{cats,dogs} test/{cats,dogs} ls ~/Downloads/dogs-vs-cats/train/cat*|head -1000|xargs -I % cp % train/cats ls ~/Downloads/dogs-vs-cats/train/cat*|head -1500|tail -500|xargs -I % cp % validation/cats ls ~/Downloads/dogs-vs-cats/train/cat*|head -2000|tail -500|xargs -I % cp % test/cats ls ~/Downloads/dogs-vs-cats/train/dog*|head -1000|xargs -I % cp % train/dogs ls ~/Downloads/dogs-vs-cats/train/dog*|head -1500|tail -500|xargs -I % cp % validation/dogs ls ~/Downloads/dogs-vs-cats/train/dog*|head -2000|tail -500|xargs -I % cp % test/dogs ``` Then run dogs_cats_cnn.py. Each epoch takes 55 ~ 70s. So the first training takes half an hour (30 epochs), the second takes 100 minutes (100 epochs) on my machine (CPU: Intel i7-6700 3.40GHz, 8 cores, Memory: 32GB). <file_sep>/dogs_vs_cats/dogs_cats_cnn.py from keras import layers from keras import models model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dense(512, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) # Let's take a look at how the dimensions of the feature maps change with every successive layer: model.summary() # For our compilation step, we'll go with the `RMSprop` optimizer as usual. Since we ended our network with a single sigmoid unit, we will # use binary crossentropy as our loss (as a reminder, check out the table in Chapter 4, section 5 for a cheatsheet on what loss function to # use in various situations). from keras import optimizers model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc']) # ## Data preprocessing # # As you already know by now, data should be formatted into appropriately pre-processed floating point tensors before being fed into our # network. Currently, our data sits on a drive as JPEG files, so the steps for getting it into our network are roughly: # # * Read the picture files. # * Decode the JPEG content to RBG grids of pixels. # * Convert these into floating point tensors. # * Rescale the pixel values (between 0 and 255) to the [0, 1] interval (as you know, neural networks prefer to deal with small input values). # # It may seem a bit daunting, but thankfully Keras has utilities to take care of these steps automatically. Keras has a module with image # processing helper tools, located at `keras.preprocessing.image`. In particular, it contains the class `ImageDataGenerator` which allows to # quickly set up Python generators that can automatically turn image files on disk into batches of pre-processed tensors. This is what we # will use here. train_dir = 'train' validation_dir = 'validation' test_dir = 'test' from keras.preprocessing.image import ImageDataGenerator # All images will be rescaled by 1./255 train_datagen = ImageDataGenerator(rescale=1./255) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( # This is the target directory train_dir, # All images will be resized to 150x150 target_size=(150, 150), batch_size=20, # Since we use binary_crossentropy loss, we need binary labels class_mode='binary') validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(150, 150), batch_size=20, class_mode='binary') # Let's take a look at the output of one of these generators: it yields batches of 150x150 RGB images (shape `(20, 150, 150, 3)`) and binary # labels (shape `(20,)`). 20 is the number of samples in each batch (the batch size). Note that the generator yields these batches # indefinitely: it just loops endlessly over the images present in the target folder. For this reason, we need to `break` the iteration loop # at some point. for data_batch, labels_batch in train_generator: print('data batch shape:', data_batch.shape) print('labels batch shape:', labels_batch.shape) break # Let's fit our model to the data using the generator. We do it using the `fit_generator` method, the equivalent of `fit` for data generators # like ours. It expects as first argument a Python generator that will yield batches of inputs and targets indefinitely, like ours does. # Because the data is being generated endlessly, the generator needs to know example how many samples to draw from the generator before # declaring an epoch over. This is the role of the `steps_per_epoch` argument: after having drawn `steps_per_epoch` batches from the # generator, i.e. after having run for `steps_per_epoch` gradient descent steps, the fitting process will go to the next epoch. In our case, # batches are 20-sample large, so it will take 100 batches until we see our target of 2000 samples. # # When using `fit_generator`, one may pass a `validation_data` argument, much like with the `fit` method. Importantly, this argument is # allowed to be a data generator itself, but it could be a tuple of Numpy arrays as well. If you pass a generator as `validation_data`, then # this generator is expected to yield batches of validation data endlessly, and thus you should also specify the `validation_steps` argument, # which tells the process how many batches to draw from the validation generator for evaluation. history = model.fit_generator( train_generator, steps_per_epoch=100, epochs=30, validation_data=validation_generator, validation_steps=50) # It is good practice to always save your models after training: model.save('cats_and_dogs_small_1.h5') # Let's plot the loss and accuracy of the model over the training and validation data during training: import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # These plots are characteristic of overfitting. Our training accuracy increases linearly over time, until it reaches nearly 100%, while our # validation accuracy stalls at 70-72%. Our validation loss reaches its minimum after only five epochs then stalls, while the training loss # keeps decreasing linearly until it reaches nearly 0. # # Because we only have relatively few training samples (2000), overfitting is going to be our number one concern. You already know about a # number of techniques that can help mitigate overfitting, such as dropout and weight decay (L2 regularization). We are now going to # introduce a new one, specific to computer vision, and used almost universally when processing images with deep learning models: *data # augmentation*. # ## Using data augmentation # # Overfitting is caused by having too few samples to learn from, rendering us unable to train a model able to generalize to new data. # Given infinite data, our model would be exposed to every possible aspect of the data distribution at hand: we would never overfit. Data # augmentation takes the approach of generating more training data from existing training samples, by "augmenting" the samples via a number # of random transformations that yield believable-looking images. The goal is that at training time, our model would never see the exact same # picture twice. This helps the model get exposed to more aspects of the data and generalize better. # # In Keras, this can be done by configuring a number of random transformations to be performed on the images read by our `ImageDataGenerator` # instance. Let's get started with an example: datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') # These are just a few of the options available (for more, see the Keras documentation). Let's quickly go over what we just wrote: # # * `rotation_range` is a value in degrees (0-180), a range within which to randomly rotate pictures. # * `width_shift` and `height_shift` are ranges (as a fraction of total width or height) within which to randomly translate pictures # vertically or horizontally. # * `shear_range` is for randomly applying shearing transformations. # * `zoom_range` is for randomly zooming inside pictures. # * `horizontal_flip` is for randomly flipping half of the images horizontally -- relevant when there are no assumptions of horizontal # asymmetry (e.g. real-world pictures). # * `fill_mode` is the strategy used for filling in newly created pixels, which can appear after a rotation or a width/height shift. # # Let's take a look at our augmented images: train_cats_dir = train_dir + '/cats' # This is module with image preprocessing utilities import os from keras.preprocessing import image fnames = [os.path.join(train_cats_dir, fname) for fname in os.listdir(train_cats_dir)] # We pick one image to "augment" img_path = fnames[3] # Read the image and resize it img = image.load_img(img_path, target_size=(150, 150)) # Convert it to a Numpy array with shape (150, 150, 3) x = image.img_to_array(img) # Reshape it to (1, 150, 150, 3) x = x.reshape((1,) + x.shape) # The .flow() command below generates batches of randomly transformed images. # It will loop indefinitely, so we need to `break` the loop at some point! i = 0 for batch in datagen.flow(x, batch_size=1): plt.figure(i) imgplot = plt.imshow(image.array_to_img(batch[0])) i += 1 if i % 4 == 0: break plt.show() # If we train a new network using this data augmentation configuration, our network will never see twice the same input. However, the inputs # that it sees are still heavily intercorrelated, since they come from a small number of original images -- we cannot produce new information, # we can only remix existing information. As such, this might not be quite enough to completely get rid of overfitting. To further fight # overfitting, we will also add a Dropout layer to our model, right before the densely-connected classifier: model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dropout(0.5)) model.add(layers.Dense(512, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc']) # Let's train our network using data augmentation and dropout: train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True,) # Note that the validation data should not be augmented! test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( # This is the target directory train_dir, # All images will be resized to 150x150 target_size=(150, 150), batch_size=32, # Since we use binary_crossentropy loss, we need binary labels class_mode='binary') validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(150, 150), batch_size=32, class_mode='binary') history = model.fit_generator( train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=50) # Let's save our model -- we will be using it in the section on convnet visualization. model.save('cats_and_dogs_small_2.h5') # Let's plot our results again: acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # Thanks to data augmentation and dropout, we are no longer overfitting: the training curves are rather closely tracking the validation # curves. We are now able to reach an accuracy of 82%, a 15% relative improvement over the non-regularized model. # # By leveraging regularization techniques even further and by tuning the network's parameters (such as the number of filters per convolution # layer, or the number of layers in the network), we may be able to get an even better accuracy, likely up to 86-87%. However, it would prove # very difficult to go any higher just by training our own convnet from scratch, simply because we have so little data to work with. As a # next step to improve our accuracy on this problem, we will have to leverage a pre-trained model, which will be the focus of the next two # sections. <file_sep>/dogs_vs_cats/vgg_fine_tuning.py # 本脚本实现了 5.3.2 节微调模型算法 from keras.preprocessing.image import ImageDataGenerator from keras import models from keras import layers from keras import optimizers from keras.applications import VGG16 import matplotlib.pyplot as plt conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3)) model = models.Sequential() model.add(conv_base) model.add(layers.Flatten()) model.add(layers.Dense(256, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) # --- 向 vgg_extended.py 中增加新代码开始 conv_base.trainable = True set_trainable = False for layer in conv_base.layers: if layer.name == 'block5_conv1': set_trainable = True if set_trainable: layer.trainable = True else: layer.trainable = False # --- 增加代码结束 --- train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') test_datagen = ImageDataGenerator(rescale=1./255) train_dir = 'train' validation_dir = 'validation' test_dir = 'test' train_generator = train_datagen.flow_from_directory( train_dir, target_size=(150, 150), batch_size=20, class_mode='binary') validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(150, 150), batch_size=20, class_mode='binary') model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-5), metrics=['acc']) history = model.fit_generator( train_generator, steps_per_epoch=100, # 一个 epoch 包含100个 steps epochs=100, validation_data=validation_generator, validation_steps=50) # step 和 epoch 的区别和联系: # 一个 step 在一个 batch (包含 batch_size 个 sample,这里是 20) 上进行一次梯度下降计算; # 100 个 steps 处理 100 个 batch,共 2000 个 sample,完成一个 epoch(见书 p42 对 epoch 的定义), # 所以 总 sample 数量 = batch_size * steps_per_epoch,即 2000 = 20 * 100, # 这里总 sample 数量就是 train 文件夹下总图片文件数 # 问题:如果 batch_size * steps_per_epoch 超过了总 sample 数,会出现什么情况? acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() <file_sep>/rnn_numpy.py import numpy as np # 下面3行注释针对文本分析的例子,不是本文件代码的含义 timestamps = 100 # 100个时间步,对应100个字符(也可以是单词,但本章用字符作为处理单位) input_features = 32 # 输入的每个字符是一个长度为32的,由 0, 1 组成的向量 output_features = 64 # 输出的每个单位是一个长度为64的,由 0, 1 组成的向量 inputs = np.random.random((timestamps, input_features)) # inputs.shape: (100, 32) state_t = np.zeros((output_features, )) W = np.random.random((output_features, input_features)) # W.shape: (64, 32) U = np.random.random((output_features, output_features)) # U.shape: (64, 64) b = np.random.random((output_features, )) # b.shape: (64,) successive_outputs = [] for input_t in inputs: # input_t.shape: (32,) output_t = np.tanh(np.dot(W, input_t) + np.dot(U, state_t) + b) # np.dot: 矩阵乘法 # np.dot(W, input_t).shape: (64,) # output_t.shape: (64,) successive_outputs.append(output_t) state_t = output_t # state_t.shape: (64,) final_output_sequence = np.concatenate(successive_outputs, axis=0) # final_output_sequence.shape: (6400,) <file_sep>/bidir_rnn.py # for section 6.3.8 # 使用逆序序列评估 LSTM from keras.datasets import imdb from keras.preprocessing import sequence from keras import layers from keras.models import Sequential from keras.optimizers import RMSprop import matplotlib.pyplot as plt max_features = 10000 maxlen = 500 (x_train, y_train), (x_test, y_test) = imdb.load_data( num_words=max_features) x_train = [x[::-1] for x in x_train] x_test = [x[::-1] for x in x_test] x_train = sequence.pad_sequences(x_train, maxlen=maxlen) x_test = sequence.pad_sequences(x_test, maxlen=maxlen) model = Sequential() model.add(layers.Embedding(max_features, 128)) model.add(layers.LSTM(32)) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history = model.fit(x_train, y_train, epochs=8, batch_size=128, validation_split=0.2) acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'ro', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'ro', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # code listing 6-43 训练并评估一个双向 LSTM model_bilstm = Sequential() model_bilstm.add(layers.Embedding(max_features, 32)) model_bilstm.add(layers.Bidirectional(layers.LSTM(32))) model_bilstm.add(layers.Dense(1, activation='sigmoid')) model_bilstm.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history = model_bilstm.fit(x_train, y_train, epochs=3, batch_size=128, validation_split=0.2) acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'ro', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'ro', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() <file_sep>/jena_cnn_rnn.py # for section 6.4.4 import numpy as np from keras.models import Sequential from keras import layers from keras.optimizers import RMSprop import matplotlib.pyplot as plt from jena_load_data import data_gen, float_data lookback = 720 step = 3 delay = 144 batch_size = 128 train_gen = data_gen(float_data, lookback=lookback, delay=delay, min_index=0, max_index=200000, shuffle=True, step=step) val_gen = data_gen(float_data, lookback=lookback, delay=delay, min_index=200001, max_index=300000, step=step) test_gen = data_gen(float_data, lookback=lookback, delay=delay, min_index=300001, max_index=None, step=step) val_steps = (300000 - 200001 - lookback) // batch_size test_steps = (len(float_data) - 300001 - lookback) // batch_size model = Sequential() model.add(layers.Conv1D(32, 5, activation='relu', input_shape=(None, float_data.shape[-1]))) model.add(layers.MaxPooling1D(3)) model.add(layers.Conv1D(32, 5, activation='relu')) model.add(layers.GRU(32, dropout=0.1, recurrent_dropout=0.5)) model.add(layers.Dense(1)) model.summary() model.compile(optimizer=RMSprop(), loss='mae') history = model.fit_generator(train_gen, steps_per_epoch=500, epochs=3, validation_data=val_gen, validation_steps=val_steps) loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'ro', label='CNN-RNN MAE Training loss') plt.plot(epochs, val_loss, 'b', label='CNN-RNN MAE Validation loss') plt.title('CNN-RNN MAE Training and validation loss') plt.legend() plt.show() <file_sep>/dogs_vs_cats/vgg_pretrained.py # 本脚本实现了 5.3.1 节的 *不使用数据增强的快速特征提取* 算法 from keras.applications import VGG16 import os import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras import models from keras import layers from keras import optimizers import matplotlib.pyplot as plt conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3)) conv_base.summary() train_dir = 'train' validation_dir = 'validation' test_dir = 'test' datagen = ImageDataGenerator(rescale=1./255) batch_size = 20 def extract_features(directory, sample_count): features = np.zeros(shape=(sample_count, 4, 4, 512)) labels = np.zeros(shape=(sample_count)) generator = datagen.flow_from_directory( directory, target_size=(150,150), batch_size=batch_size, class_mode='binary') i = 0 for inputs_batch, labels_batch in generator: features_batch = conv_base.predict(inputs_batch) features[i * batch_size : (i + 1) * batch_size] = features_batch labels[i * batch_size : (i + 1) * batch_size] = labels_batch i += 1 if i * batch_size >= sample_count: break return features, labels # 得到卷积基模型,保存在 numpy.ndarray 中 train_features, train_labels = extract_features(train_dir, 2000) validation_features, validation_labels = extract_features(validation_dir, 1000) test_features, test_labels = extract_features(test_dir, 1000) type(train_features) # numpy.ndarray train_features.shape # (2000, 4, 4, 512) train_features_res = np.reshape(train_features, (2000, 4 * 4 * 512)) validation_features_res = np.reshape(validation_features, (1000, 4 * 4 * 512)) test_features_res = np.reshape(test_features, (1000, 4 * 4 * 512)) model = models.Sequential() model.add(layers.Dense(256, activation='relu', input_dim= 4 * 4 * 512)) model.add(layers.Dropout(0.5)) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer=optimizers.RMSprop(lr=2e-5), loss='binary_crossentropy', metrics=['acc']) history = model.fit(train_features_res, train_labels, epochs=30, batch_size=20, validation_data=(validation_features_res, validation_labels)) acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] # 这里 `val` 前缀表示 validation,所以 val_loss 表示 loss on validation set epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() <file_sep>/visual_cnn.py # 使用 `ipython --matplotlib=qt` 启动 IPython console,避免输入 `plt.show()` # 为了每次只显示一张图,在下面标记出来的3行处加断点,例如: # >>> run -d -b23 visual_cnn.py # ipdb> b 32 # ipdb> b 44 from keras.models import load_model from keras.preprocessing import image from keras import models import numpy as np import matplotlib.pyplot as plt model = load_model('dogs_vs_cats/cats_and_dogs_small_2.h5') model.summary() img_path = 'dogs_vs_cats/test/cats/cat.11350.jpg' img = image.load_img(img_path, target_size=(150, 150)) img_tensor = image.img_to_array(img) img_tensor = np.expand_dims(img_tensor, axis=0) img_tensor /= 255. print(img_tensor.shape) plt.imshow(img_tensor[0]) # add breakpoint add this line,原始图片 layer_outputs = [layer.output for layer in model.layers[:8]] activation_model = models.Model(inputs=model.input, outputs=layer_outputs) activations = activation_model.predict(img_tensor) first_layer_activation = activations[0] print(first_layer_activation.shape) plt.matshow(first_layer_activation[0, :, :, 4], cmap='viridis') # add breakpoint add this line plt.matshow(first_layer_activation[0, :, :, 7], cmap='viridis') # 第一层的两个特征,与原始图片相似度较高 layer_names = [] for layer in model.layers[:8]: layer_names.append(layer.name) # 每行16张图,包含16个featrue images_per_row = 16 # 每个循环绘制一个layer中所有特征的激活图,共绘制8张图(8个layer) for layer_name, layer_activation in zip(layer_names, activations): n_features = layer_activation.shape[-1] # add breakpoint add this line size = layer_activation.shape[1] n_cols = n_features // images_per_row # 生成整个空白画布(二维数组) display_grid = np.zeros((size * n_cols, images_per_row * size)) # 填充一列特征图 for col in range(n_cols): # 填充一行特征图 for row in range(images_per_row): channel_image = layer_activation[0, :, :, col * images_per_row + row] channel_image -= channel_image.mean() channel_image /= channel_image.std() channel_image *= 64 channel_image += 128 channel_image = np.clip(channel_image, 0, 255).astype('uint8') # 填充一个特征图 display_grid[col * size : (col + 1) * size, row * size : (row + 1) * size] = channel_image scale = 1. / size plt.figure(figsize=(scale * display_grid.shape[1], scale * display_grid.shape[0])) plt.title(layer_name) plt.grid(False) plt.imshow(display_grid, aspect='auto', cmap='viridis') # 第1轮输出图中包含2行16列共32张图,与第0层 conv2d_5 的输出形状 # (None, 148, 148, 32) 中的32个 feature 吻合 # 后续循环中,每张图中包含的子图越来越多(feature 越来越多), # 每个子图越来越小,例如 conv2d_6(第3层)每个子图 72 * 72,共 64 张图, # conv2d_8(第7层)每个子图 15 * 15,共 128 张图 <file_sep>/jena_prediction.py # for section 6.3.1 ~ 6.3.7 import numpy as np from keras.models import Sequential from keras import layers from keras.optimizers import RMSprop import matplotlib.pyplot as plt from jena_load_data import float_data, data_gen lookback = 1440 step = 6 delay = 144 batch_size = 128 train_gen = data_gen(float_data, lookback=lookback, delay=delay, min_index=0, max_index=200000, shuffle=True, step=step, batch_size=batch_size) val_gen = data_gen(float_data, lookback=lookback, delay=delay, min_index=200001, max_index=300000, step=step, batch_size=batch_size) test_gen = data_gen(float_data, lookback=lookback, delay=delay, min_index=300001, max_index=None, step=step, batch_size=batch_size) val_steps = (300000 - 200001 - lookback) // batch_size test_steps = (len(float_data) - 300001 - lookback) // batch_size # A common sense, non-machine learning baseline def evaluate_naive_method(): batch_maes = [] for step in range(val_steps): samples, targets = next(val_gen) # 用取所有样本的最后一个时间点上的第2列(列名:t (degC))数据作为预测值: preds = samples[:, -1, 1] mae = np.mean(np.abs(preds - targets)) batch_maes.append(mae) return np.mean(batch_maes) print(evaluate_naive_method()) # A basic machine learning approach model = Sequential() model.add(layers.Flatten(input_shape=(lookback // step, float_data.shape[-1]))) model.add(layers.Dense(32, activation='relu')) model.add(layers.Dense(1)) model.compile(optimizer=RMSprop(), loss='mae') history = model.fit_generator(train_gen, steps_per_epoch=500, epochs=20, validation_data=val_gen, validation_steps=val_steps) loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'ro', label='Double Dense MAE Training loss') plt.plot(epochs, val_loss, 'b', label='Double Dense MAE Validation loss') plt.title('Double Dense MAE Training and validation loss') plt.legend() plt.show() # 实际运行结果,在 epoch 8 处,loss 和 validation loss 都出现了尖峰, # 与书上曲线趋势不一致。 # A first recurrent baseline model_gru = Sequential() model_gru.add(layers.GRU(32, input_shape=(None, float_data.shape[-1]))) model_gru.add(layers.Dense(1)) model_gru.compile(optimizer=RMSprop(), loss='mae') history = model_gru.fit_generator(train_gen, steps_per_epoch=500, epochs=8, validation_data=val_gen, validation_steps=val_steps) # Dell 笔记本在 epoch 9 处卡死,这里将 epoch 数改成了8, # 趋势已足够清楚 loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'ro', label='GRU Training loss') plt.plot(epochs, val_loss, 'b', label='GRU Validation loss') plt.title('GRU Training and validation loss') plt.legend() plt.show() # Using recurrent dropout to fight overfitting model_dropout = Sequential() model_dropout.add(layers.GRU(32, dropout=0.2, recurrent_dropout=0.2, input_shape=(None, float_data.shape[-1]))) model_dropout.add(layers.Dense(1)) model_dropout.compile(optimizer=RMSprop(), loss='mae') history = model_dropout.fit_generator(train_gen, steps_per_epoch=500, epochs=8, validation_data=val_gen, validation_steps=val_steps) loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'ro', label='Dropout Training loss') plt.plot(epochs, val_loss, 'b', label='Dropout Validation loss') plt.title('Dropout Training and validation loss') plt.legend() plt.show() # Stacking recurrent layers model_stack = Sequential() model_stack.add(layers.GRU(32, dropout=0.1, recurrent_dropout=0.5, return_sequences=True, input_shape=(None, float_data.shape[-1]))) model_stack.add(layers.GRU(64, activation='relu', dropout=0.1, recurrent_dropout=0.5)) model_stack.add(layers.Dense(1)) model_stack.compile(optimizer=RMSprop(), loss='mae') history = model_stack.fit_generator(train_gen, steps_per_epoch=500, epochs=20, validation_data=val_gen, validation_steps=val_steps) loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'ro', label='Stack Training loss') plt.plot(epochs, val_loss, 'b', label='Stack Validation loss') plt.title('Stack Training and validation loss') plt.legend() plt.show() # code listing 6-44 训练并评估一个双向 GRU model_bigru = Sequential() model_bigru.add(layers.Bidirectional(layers.GRU(32), input_shape=(None, float_data.shape[-1]))) model_bigru.add(layers.Dense(1)) model_bigru.compile(optimizer=RMSprop(), loss='mae') history = model_bigru.fit_generator(train_gen, steps_per_epoch=500, epochs=3, validation_data=val_gen, validation_steps=val_steps) loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'ro', label='Bidirectional GRU MAE Training loss') plt.plot(epochs, val_loss, 'b', label='Bidirectional GRU MAE Validation loss') plt.title('Bidirectional GRU MAE Training and validation loss') plt.legend() plt.show()
593130f4af24fabd1fbff83cd182f7aec817e829
[ "Markdown", "Python" ]
14
Python
leetschau/DeepLearningWithPython
20b9dfab2445f700f46ce9872dcce43e9a228074
44b7311def790a0480329e688c9ed6ed14da6a26
refs/heads/master
<file_sep>sysctl kernel.perf_event_paranoid=0 sysctl kernel.kptr_restrict=0 sysctl -w net.ipv4.ip_local_port_range="1025 65535" service lightdm stop<file_sep>curl --data-urlencode "(2*(9+22/5)-((9-1)/4)^2)+(3^2+((5*5-1)/2)" http://localhost:8080/api/calc<file_sep> var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var http = require('http'); // var utils = require('../node-calc-core/utils'); var serviceName = "SUBTRACT"; var servicePort = 8082; // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); http.globalAgent.keepAlive = true; var port = process.env.PORT || servicePort; // ROUTES FOR OUR API // ============================================================================= var router = express.Router(); // test route to make sure everything is working (accessed at GET http://localhost:8080/api) router.get('/', function(req, res) { res.json({ message: `welcome from the ${serviceName} service` }); }); router.get("/subtract", function(req, res) { var calcid = req.query.calcId; var left = req.query.leftOp; var right = req.query.rightOp; var result = Number(left) - Number(right); res.write(result.toString()); res.statusCode = 200; res.end(); var params = { MessageGroupId: calcid, MessageAttributes: { "LeftOperand": { DataType: "String", StringValue: left }, "RightOperand": { DataType: "String", StringValue: right }, Operator: { DataType: "String", StringValue: "-" } }, MessageBody: `${left}-${right}=${result}` }; }); // REGISTER OUR ROUTES ------------------------------- // all of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); console.log(`${serviceName} service listening on port: ` + port); <file_sep> https://www.carlhopf.com/blog/2016/09/11/nodejs-cpu-profiling-production/ perf script | stackcollapse-perf.pl | flamegraph.pl --color=js --hash > node.svg stackvis perf flamegraph-svg < out.nodestacks > collapsed.svg ./FlameGraph/stackcollapse-perf.pl < out.nodestacks https://github.com/thlorenz/flamegraph for dir in ./node-*; do (cd "$dir" && node --perf_basic_prof server.js > /dev/null &); done offcpu bcc/eBPF sudo python offcpu -f -p 7932 > offcpu.stack offcpu perf echo 1 | sudo tee /proc/sys/kernel/sched_schedstats sudo perf record --event sched:sched_stat_sleep --event sched:sched_process_exit --event sched:sched_switch -g --output perf.data.raw -p ${PID} //-call-graph=dwarf sudo perf inject -v -s -i perf.data.raw -o perf.data perf script -F comm,pid,tid,cpu,time,period,event,ip,sym,dso,trace | awk ' NF > 4 { exec = $1; period_ms = int($5 / 1000000) } NF > 1 && NF <= 4 && period_ms > 0 { print $2 } NF < 2 && period_ms > 0 { printf "%s\n%d\n\n", exec, period_ms }' > offcpu.stack cat offcpu.stack | stackcollapse.pl | flamegraph.pl --colors=js > offcpu.svg perf elevate rights by <NAME> (shell-helpers/blob/master/elevate_perf_rights.sh) sudo mount -o remount,mode=755 /sys/kernel/debug sudo mount -o remount,mode=755 /sys/kernel/debug/tracing echo "-1" | sudo tee /proc/sys/kernel/perf_event_paranoid https://poormansprofiler.org/ netutils/irqs https://github.com/strizhechenko/netutils-linux pv /dev/zero > /dev/null tinkerboard [2.54GiB/s] tegra tk1 [5.17GiB/s] mac pro i7 [16.0GiB/s] Pentium CPU G3460 @ 3.50GHz [16.8GiB/s] iperf -s iperf -c 127.0.0.1 network mac -> pentium tegra tk1 0.0-10.0 sec 11.4 GBytes 9.82 Gbits/sec Pentium 0.0-10.0 sec 43.0 GBytes 36.9 Gbits/sec mac pro 0.0-10.0 sec 48.2 GBytes 41.4 Gbits/sec mac->tegra: 26.5 Mbits/sec perf bench futex hash pentium 3576627 ops/sec || 3582566 ops/sec perf stat -e cycles sleep 1 pentium 916 075 cycles<file_sep>version: "3" services: calc: build: context: ./node-calc dockerfile: ./Dockerfile container_name: CALC image: node-calc ports: - "8080:8080" networks: calcnet: ipv4_address: 172.19.0.100 postfix: build: context: ./node-postfix dockerfile: ./Dockerfile container_name: POSTIX image: node-postfix ports: - "9090:9090" networks: calcnet: ipv4_address: 172.19.0.200 add: build: context: ./node-add dockerfile: ./Dockerfile container_name: ADD image: node-add ports: - "8081:8081" networks: calcnet: ipv4_address: 172.19.10.1 subtract: build: context: ./node-subtract dockerfile: ./Dockerfile container_name: SUBTRACT image: node-subtract ports: - "8082:8082" networks: calcnet: ipv4_address: 172.19.10.2 multiply: build: context: ./node-multiply dockerfile: ./Dockerfile container_name: MULTIPLY image: node-multiply ports: - "8083:8083" networks: calcnet: ipv4_address: 172.19.10.3 divide: build: context: ./node-divide dockerfile: ./Dockerfile container_name: DIVIDE image: node-divide ports: - "8084:8084" networks: calcnet: ipv4_address: 172.19.10.4 power: build: context: ./node-power dockerfile: ./Dockerfile container_name: POWER image: node-power ports: - "8085:8085" networks: calcnet: ipv4_address: 172.19.10.5 networks: calcnet: driver: bridge ipam: driver: default config: - subnet: 172.19.0.0/16<file_sep>var express = require('express'); // call express var app = express(); // define our app using express var bodyParser = require('body-parser'); var http = require('http'); // var utils = require('../node-calc-core/utils'); var mathsolver = require("./mathsolver.js"); var serviceName = "POSTFIX"; var servicePort = 9090; // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); http.globalAgent.keepAlive = true; var port = process.env.PORT || servicePort; // ROUTES FOR OUR API // ============================================================================= var router = express.Router(); // test route to make sure everything is working (accessed at GET http://localhost:8080/api) router.get('/', function(req, res) { res.json({ message: `welcome from the ${serviceName} service` }); }); router.post("/postfix", function(req, res) { var calcid = req.body.calcid; var infix = req.body.expression; var postfix = mathsolver.infixToPostfix(infix).trim(); res.write(postfix); res.statusCode = 200; res.end(); var params = { MessageGroupId: calcid, MessageAttributes: { "Infix": { DataType: "String", StringValue: infix }, "Postfix": { DataType: "String", StringValue: postfix }, }, MessageBody: `${infix} converts to ${postfix}`, }; }); // REGISTER OUR ROUTES ------------------------------- // all of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); console.log(`${serviceName} service listening on port: ` + port); <file_sep>var rp = require('request-promise'); let addUrl = "add"; let subtractUrl = "subtract"; let multiplyUrl = "multiply"; let divideUrl = "divide"; let powerUrl = "power"; String.prototype.isNumeric = function() { return !isNaN(parseFloat(this)) && isFinite(this); } Array.prototype.clean = function() { for(var i = 0; i < this.length; i++) { if(this[i] === "") { this.splice(i, 1); } } return this; } module.exports = { infixToPostfix: function(infix) { var outputQueue = ""; var operatorStack = []; var operators = { "^": { precedence: 4, associativity: "Right" }, "/": { precedence: 3, associativity: "Left" }, "*": { precedence: 3, associativity: "Left" }, "+": { precedence: 2, associativity: "Left" }, "-": { precedence: 2, associativity: "Left" } } infix = infix.replace(/\s+/g, ""); infix = infix.split(/([\+\-\*\/\^\(\)])/).clean(); for(var i = 0; i < infix.length; i++) { var token = infix[i]; if(token.isNumeric()) { outputQueue += token + " "; } else if("^*/+-".indexOf(token) !== -1) { var o1 = token; var o2 = operatorStack[operatorStack.length - 1]; while("^*/+-".indexOf(o2) !== -1 && ((operators[o1].associativity === "Left" && operators[o1].precedence <= operators[o2].precedence) || (operators[o1].associativity === "Right" && operators[o1].precedence < operators[o2].precedence))) { outputQueue += operatorStack.pop() + " "; o2 = operatorStack[operatorStack.length - 1]; } operatorStack.push(o1); } else if(token === "(") { operatorStack.push(token); } else if(token === ")") { while(operatorStack[operatorStack.length - 1] !== "(") { outputQueue += operatorStack.pop() + " "; } operatorStack.pop(); } } while(operatorStack.length > 0) { outputQueue += operatorStack.pop() + " "; } return outputQueue; }, solvePostfix: function(postfix, callback) { var resultStack = []; postfix = postfix.split(" "); var i = 0; calculate(postfix, i, resultStack, function(result){ callback(result); }); } }; function calculate(postfix, i, resultStack, callback){ if(postfix[i].isNumeric()) { resultStack.push(postfix[i]); i = i + 1; calculate(postfix, i, resultStack, callback); } else { var a = resultStack.pop(); var b = resultStack.pop(); var left = parseInt(a); var right = parseInt(b); if(postfix[i] === "+") { //resultStack.push(parseInt(a) + parseInt(b)); var options = { uri: 'http://'+addUrl+':8081/api/add/', qs: { leftOp: left, rightOp: right } }; } else if(postfix[i] === "-") { //resultStack.push(parseInt(b) - parseInt(a)); var options = { uri: 'http://'+subtractUrl+':8082/api/subtract/', qs: { leftOp: right, rightOp: left } }; } else if(postfix[i] === "*") { //resultStack.push(parseInt(a) * parseInt(b)); var options = { uri: 'http://'+multiplyUrl+':8083/api/multiply/', qs: { leftOp: left, rightOp: right } }; } else if(postfix[i] === "/") { //resultStack.push(parseInt(b) / parseInt(a)); var options = { uri: 'http://'+divideUrl+':8084/api/divide/', qs: { leftOp: right, rightOp: left } }; } else if(postfix[i] === "^") { //resultStack.push(Math.pow(parseInt(b), parseInt(a))); var options = { uri: 'http://'+powerUrl+':8085/api/power/', qs: { leftOp: right, rightOp: left } }; } rp(options) .then(function (data) { var result = parseInt(data); resultStack.push(result); i = i + 1; if(i < postfix.length){ calculate(postfix, i, resultStack, callback); } else{ if(resultStack.length > 1) { return "error"; } else { var resultVal = resultStack.pop(); callback(resultVal); return; } } }) .catch(function (err) { console.error("error!!"); }); } }<file_sep>import http from "k6/http"; import {check} from "k6"; import {Rate} from "k6/metrics"; export let errorRate = new Rate("errors"); export let options = { thresholds: { "errors": ["rate<0.01"], // <1% errors http_req_duration: ["avg<100", "p(95)<800"] }, insecureSkipTLSVerify: true, vus: 6, duration: "60s" // stages: [ // {duration: "10s", target: 10}, // {duration: "35s", target: 30}, // {duration: "50s", target: 50}, // {duration: "60s", target: 80} // ] }; export default function () { let payload = { calcid: 1234, expression: "(2*(9+22/5)-((9-1)/4)^2)+(3^2+((5*5-1)/2))" }; let res = http.post("http://localhost:8080/api/calc", payload); check(res, { "status was 200": (r) => r.status == 200, // "body contains result": (r) => r.body.indexOf("result") !== -1, "ANSWER = 43.8": (r) => r.body.indexOf("ANSWER = 43.8") !== -1 }) || errorRate.add(1); }; // export default function () { // let res = http.get("https://127.0.0.1:8080/api"); // check(res, { // "status was 200": (r) => r.status == 200, // "CALCULATOR is present": (r) => r.body.indexOf("CALCULATOR") !== -1 // }) || errorRate.add(1); // };<file_sep>curl --data-urlencode "expression=((5+3)/2)^3" http://localhost:8080/api/calc<file_sep>export POSTFIX_URL=127.0.0.1 export ADD_URL=127.0.0.1 export SUB_URL=127.0.0.1 export MUL_URL=127.0.0.1 export DIVIDE_URL=127.0.0.1 export POWER_URL=127.0.0.1
0e67048eb25d325e7ab3065897b4d44c6d5afded
[ "JavaScript", "YAML", "Markdown", "Shell" ]
10
Shell
olka/microservices-calc
ac58973061aa669d8474884a1c255051d709639a
e8a562311ffb2ecfe4aa10b8b31b3bcf3f71129b
refs/heads/master
<file_sep>#!/usr/bin/env sh echo Cleaning all... rm -fr lwjgl3 rm -fr native-libs <file_sep>#!/bin/sh ROOT=/usr/home/cameron/Documents/lwjgl3-port LWJGL_JLP_OVRD="${ROOT}/native-libs:${ROOT}/lwjgl3/bin/libs:/usr/local/lib:/usr/lib" LWJGL_OVRD="${ROOT}/lwjgl3/bin/RELEASE/lwjgl/lwjgl.jar" LWJGL_OGL_OVRD="${ROOT}/lwjgl3/bin/RELEASE/lwjgl-opengl/lwjgl-opengl.jar" LWJGL_OAL_OVRD="${ROOT}/lwjgl3/bin/RELEASE/lwjgl-openal/lwjgl-openal.jar" LWJGL_GLFW_OVRD="${ROOT}/lwjgl3/bin/RELEASE/lwjgl-glfw/lwjgl-glfw.jar" LWJGL_STB_OVRD="${ROOT}/lwjgl3/bin/RELEASE/lwjgl-stb/lwjgl-stb.jar" LWJGL_JEM_OVRD="${ROOT}/lwjgl3/bin/RELEASE/lwjgl-jemalloc/lwjgl-jemalloc.jar" # Use openjdk16 for 1.17 support export JAVA_HOME=/usr/local/openjdk16 build_classpath() { local IFS=":" for p in ${1} do case "${p}" in *lwjgl-3.2.2.jar) cp="${cp}:${LWJGL_OVRD}" ;; *lwjgl-opengl*) cp="${cp}:${LWJGL_OGL_OVRD}" ;; *lwjgl-openal*) cp="${cp}:${LWJGL_OAL_OVRD}" ;; *lwjgl-glfw*) cp="${cp}:${LWJGL_GLFW_OVRD}" ;; *lwjgl-stb*) cp="${cp}:${LWJGL_STB_OVRD}" ;; *lwjgl-jemalloc*) cp="${cp}:${LWJGL_JEM_OVRD}" ;; *) cp="${cp}:${p}" ;; esac done cp=${cp#?} } for var in "${@}" do case "${var}" in -Djava.library*) args="${args} -Djava.library.path=${LWJGL_JLP_OVRD}" ;; *lwjgl-opengl*) build_classpath "${var}" args="${args} ${cp}" ;; *) args="${args} ${var}" ;; esac done ${JAVA_HOME}/bin/java ${args} <file_sep># Minecraft 1.14.3 - 1.17.1 This repo contains - Build script to fetch and compile code required to run Minecraft 1.14.3 - 1.17.1 - Self-contained launcher script for Minecraft client Dependencies are - https://github.com/CRKatri/lwjgl3 ### Instructions Step 1 Read through the `build.sh` script. Install binary dependencies if necessary. Step 2 Execute `./build.sh` When build is complete, set `ROOT` in `minecraft-runtime` to this folder From the Minecraft launcher, edit your profile and change the executable to `<absolute-path-to-this-folder>/minecraft-runtime` Or in MultiMC set your java runtime to `<absolute-path-to-this-folder>/minecraft-runtime` <file_sep>#!/usr/bin/env sh echo Cleaning build... cd lwjgl3/ ant -Dos.name=Linux -Dplatform=linux clean cd .. <file_sep>#!/usr/bin/env sh echo echo Make sure you install required build dependencies by executing echo pkg install git apache-ant dyncall echo And runtime dependencies echo pkg install glfw openal-soft echo # (there might be more that I've missed) ROOT=`pwd` LIBS=${ROOT}/native-libs mkdir -p ${LIBS} || exit 1 echo Cloning dependencies... GIT_OPTIONS="--single-branch --depth 1" # main repo git clone -b 'freebsd-3.2.2' ${GIT_OPTIONS} <EMAIL>:CRKatri/lwjgl3.git ln -sf /usr/local/lib/libopenal.so ${LIBS}/ ln -sf /usr/local/lib/libglfw.so ${LIBS}/ cd ${ROOT}/lwjgl3 ant -Dos.name=Linux -Dplatform=linux || exit 1 ant -Dos.name=Linux -Dplatform=linux release || exit 1
53d2bcb57917f7749db19126c892e970fba2a916
[ "Markdown", "Shell" ]
5
Shell
CRKatri/freebsd-minecraft-1.17
5d1dca8ef577dfd81e29e3515d24ae444a71fa37
156516f3d099f653583a16de2ce3b0cddab7ef57
refs/heads/master
<file_sep>Pod::Spec.new do |s| s.name = 'DHSplitCells' s.version = '0.1.3' s.summary = 'DHSplitCells is cell split module of CloudCash App.' s.description = <<-DESC DHSplitCells is cell split module of CloudCash App on iOS. DESC s.homepage = 'http://git.2dfire-inc.com/ccd-iOS/DHSplitCells' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'fengli' => '<EMAIL>' } s.source = { :git => '<EMAIL>:ccd-iOS/DHSplitCells.git', :tag => s.version.to_s } s.ios.deployment_target = '7.0' s.source_files = 'DHSplitCells/Classes/**/*' s.requires_arc = true # s.frameworks = 'UIKit', 'MapKit' end <file_sep># DHSplitCells [![CI Status](http://img.shields.io/travis/zhandongwang/DHSplitCells.svg?style=flat)](https://travis-ci.org/zhandongwang/DHSplitCells) [![Version](https://img.shields.io/cocoapods/v/DHSplitCells.svg?style=flat)](http://cocoapods.org/pods/DHSplitCells) [![License](https://img.shields.io/cocoapods/l/DHSplitCells.svg?style=flat)](http://cocoapods.org/pods/DHSplitCells) [![Platform](https://img.shields.io/cocoapods/p/DHSplitCells.svg?style=flat)](http://cocoapods.org/pods/DHSplitCells) ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements ## Installation DHSplitCells is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "DHSplitCells" ``` ## Author zhandongwang, <EMAIL> ## License DHSplitCells is available under the MIT license. See the LICENSE file for more info. <file_sep>use_frameworks! target 'DHSplitCells_Example' do pod 'DHSplitCells', :path => '../' target 'DHSplitCells_Tests' do inherit! :search_paths end end
41079d1184e29d8c615f60b08ee0774391411966
[ "Markdown", "Ruby" ]
3
Ruby
zhandongwang/SplitCell
6bfa37c609c89cd7ec68dd5b21a714516a009b3a
cb975bf8e18b9bb8a5c0000e56e01c8e2ed16dc5
refs/heads/master
<file_sep>package utils import ( "os" "bytes" "log" "strings" "time" "testing" "github.com/stretchr/testify/require" ) func TestWebsocketListen(t *testing.T) { app := setupWithPlentyBalanceAccount(t) // DO NOT TOUCH - wait next block time.Sleep(time.Second * 10) var logBuf bytes.Buffer log.SetOutput(&logBuf) defer log.SetOutput(os.Stderr) app.TriggerInterval = "1" app.ListenNewBLock(true) result := logBuf.String() require.True(t, strings.Contains(result, "[Success]")) }<file_sep># Santa ![banner](./banner.png) [![codecov](https://codecov.io/gh/terra-project/santa/branch/master/graph/badge.svg)](https://codecov.io/gh/terra-project/santa) Santa subsidizes block rewards for Terra's Columbus mainnet. It is intended to support the security of the network until Terra transaction volume (and attendent staking returns from transaction fees) has had sufficient time to mature. Read [here](./MOTIVATION.md) for more details on the project motivation. ## Mechanism The config file looks something like the following: ``` key_dir: ... node: ... trigger_interval: 1 fee_amount: 1000000uluna ``` Every `trigger_interval` number of blocks on Columbus, Santa sends a transaction containing `1 uluna` with `fee_amount` of fees to itself. Effectively, this scheme allows Santa to subsidize block rewards by paying fees over periodic block intervals. For example, in order to subsidize 21.6 million Luna tokens every block over 1 year, one needs to set `trigger_interval` to 1, and `fee_amount` to `21.6 million / (3.154e+7 / 6.5) * 10^6 = 4451490 uluna`. ## Status An instance of Santa is currently being jointly operated and supported by several top validators in the network: ``` Hashed Arrington XRP Capital Polychain Labs Certus One Chorus One Terraform Labs B Harvest A Team Dokia Capital Terraforming Healings ``` To kick off the process, Terraform Labs has donated 21.6 million tokens to be distributed over the course of the next year, slightly above a 10% annualized return on currently staked tokens. You can see Santa hard at work here: https://finder.terra.money/columbus-2/account/terra13u66u4knssnws7n7w0n38mzyyqak5ygp807gyl Some details on future operations: - **IMPORTANT**: Santa will operate independently of existing rewards from fees and swaps. As Terra transaction volume goes up, expected rewards may well be significantly higher than that provided by Santa. - Every time the number of staked tokens go up by more than 10 million tokens, Terraform Labs is commiting to deposit an additional 1 million Luna to Santa to prevent reward dilution for existing stakeholders. No tokens will be withdrawn in the opposite case where the number of staked tokens go down. - Terra's validator community will actively monitor the network's reward dynamics and continue supporting Santa in the unlikely case that staking returns continue to lag behind the industry average. The Terraform Labs validator will commit up to 100 million Luna tokens for this purpose, which, at current parameters, sufficient to keep Santa running for the next five years. - Members of the community looking to support the network are either encouraged to either donate tokens to the [currently active Santa address](https://finder.terra.money/columbus-2/account/terra13u66u4knssnws7n7w0n38mzyyqak5ygp807gyl) or start their own instances of Santa. ## Build & Install First, check out the repo: ``` $ git clone https://github.com/terra-project/santa.git $ git checkout master ``` Then, build and install: ``` $ make install ``` To initialize the config file for Santa: ``` $ santa config ``` To edit the config file: ``` $ vim ~/.santa/config.yaml ``` To add a key to an account containing tokens to be doled out: ``` $ santa keys add ``` To recover a key: ``` $ santa keys add --recover ``` Finally: to start santa and have Christmas come early: ``` $ santa start ```
246fe30a86b6ce1f9b8551ef2a0d34f011d18bae
[ "Markdown", "Go" ]
2
Go
ChorusOne/santa
ece7c43f1cca4bc23647a789dc2beeee25839929
d18ceb00dd8314800573168a9062096e573e06ab
refs/heads/master
<repo_name>HoneyLuka/HYGPUImageCreator<file_sep>/Podfile source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' pod 'Reachability', '~> 3.2' pod 'JSONModel', '~> 1.1.2' pod 'Masonry', '~> 0.6.3' pod 'GPUImage', '~> 0.1.7' pod 'SVProgressHUD', '~> 2.0-beta' pod 'LGAlertView', '~> 2.0.13'
ad7fff482e81d56138ff756a888ae8afe1351df1
[ "Ruby" ]
1
Ruby
HoneyLuka/HYGPUImageCreator
e9ab4840c6c9976be836233fbb820874492ba213
1a5fe62a749d5e85a426e82c2a38698b6d5421b0
refs/heads/master
<file_sep>Ten projekt jest zrobiony z wykorzystaniem technologii: Angular, Java, Spring, Hibernate i Postgres, REST. Dla uruchomienia projektu trzeba pobrać folder z Java projektem i osobno z angular foldery i pliki. I do kompilacji javy plików jest potrzebny IDE z kompilatorem Javy conajmniej 14 wersji, i też w pliku applikation.properties ustawić login i hasło do lokalnej BD. Do kompilacji plików Angular trzeba posiadać IDE z kompilatorem TS poleceniem ng serve. I po skompilowaniu obu projektów należy uruchomić przeglądarkę "http://localhost:4200/". Dany projekt jest stworzony dla tworzenia i zapisanie się na sportowe wydarzenia. W projekcie są dostępne następne opcje: zarejestrownie użytkownika, logowanie, wylogowanie, dodanie wydarzeń, zapis na wydazenie i wypis z wydarzenia. <file_sep>import { Component, OnInit } from '@angular/core'; import{Person} from '../login/login.component' import { DataService } from '../service/data.service'; import { MyEvent } from '../add-event/add-event.component'; import { AuthService } from '../service/auth.service'; @Component({ selector: 'app-events', templateUrl: './events.component.html', styleUrls: ['./events.component.css'] }) export class EventsComponent implements OnInit { constructor(private service: DataService, private serviceGuard:AuthService) { } alreadySigned:boolean=false ngOnInit(): void { let username = sessionStorage.getItem("authenticatedUser") if(username!=null) this.serviceGuard.LoggedIn.next(true) this.service.getPersonByUsername(username).subscribe( data=>{ //console.log("User:"+ data) this.person=data } ) this.getData(); } events:MyEvent[]; person:Person; event:MyEvent // show(a,b){ // console.log(a,b) // console.log(sessionStorage.getItem("authenticatedUser")) // let variable = sessionStorage.getItem("authenticatedUser") // // this.service.getPerson2(variable).subscribe( // // data=>{ // // console.log(data) // // } // // ) // } signUp2(var1){ let username = sessionStorage.getItem("authenticatedUser") this.service.signUpToEvent(var1,username).subscribe( response=>{ if(response===null){ console.log('you are already subscribed') this.alreadySigned=true }else{ this.getData(); window.location.reload(); } } ) } getData(){ this.service.showEvents().subscribe( data=>{ this.events=data; } ) } } <file_sep>import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { BehaviorSubject, Observable } from 'rxjs'; import { Person } from '../registration/registration.component'; import { DataService } from './data.service'; @Injectable({ providedIn: 'root' }) export class AuthService { public LoggedIn = new BehaviorSubject<boolean>(false); // {1} get isLoggedIn() { return this.LoggedIn.asObservable(); // {2} } constructor(private data:DataService, private router:Router){} login(username: string, password: string){ this.data.getPerson(username,password).subscribe( data=>{ if(data!=null){ sessionStorage.setItem('authenticatedUser', username); this.router.navigate(['welcome']) this.LoggedIn.next(true); return true; } else{ return false } } ) } logout() { sessionStorage.removeItem('authenticatedUser'); this.router.navigate(['login']) this.LoggedIn.next(false); } public get loggedIn(): boolean { return (sessionStorage.getItem('authenticatedUser') !== null); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {LoginComponent} from './login/login.component' import { WelcomeComponent } from './welcome/welcome.component'; import { ErrorComponent } from './error/error.component'; import { RegistrationComponent } from './registration/registration.component'; import { AddEventComponent } from './add-event/add-event.component'; import { EventsComponent } from './events/events.component'; import {PersonEventsComponent} from './person-events/person-events.component'; import{AuthGuard} from '../app/auth.guard' import { RestEventsComponent } from './rest-events/rest-events.component'; import { ChangePasswordComponent } from './change-password/change-password.component'; const routes: Routes = [ {path: '', component: LoginComponent}, {path: 'login', component: LoginComponent}, {path: 'welcome', component:WelcomeComponent,canActivate: [AuthGuard] }, {path: 'registration', component:RegistrationComponent}, {path: 'addEvent', component:AddEventComponent,canActivate: [AuthGuard]}, {path: 'events', component:EventsComponent,canActivate: [AuthGuard] }, {path: ':name/events', component:PersonEventsComponent,canActivate: [AuthGuard] }, {path: 'events/:type', component:RestEventsComponent,canActivate: [AuthGuard] }, {path: 'changePassword', component:ChangePasswordComponent}, {path: '**', component:ErrorComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>package com.example.demo.models; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import lombok.AllArgsConstructor; import lombok.Data; import lombok.RequiredArgsConstructor; @Entity @RequiredArgsConstructor @AllArgsConstructor @Data public class Event { @Id @GeneratedValue(strategy=GenerationType.AUTO ) private Long Id; @Enumerated(EnumType.STRING) private Type type; private int places; private Date dateEvent; private String organizerPhone; @ManyToMany(mappedBy="events") @JsonIgnore private List<Person> persons=new ArrayList<Person>(); } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; import { Person } from '../registration/registration.component'; import {MyEvent} from '../add-event/add-event.component' import { Subject } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http:HttpClient) { } createPerson(person){ return this.http.post("http://localhost:8080/persons",person) } getPerson(username,password){ let params = new HttpParams() .set('username',username) .set('password',<PASSWORD>); return this.http.get<Person>("http://localhost:8080/login",{params:params}) } getPersonByUsername(username){ let params = new HttpParams().set('str',username); return this.http.get<Person>("http://localhost:8080//getUser",{params:params}) } addEvent(event:MyEvent,username){ let params = new HttpParams().set('username',username); return this.http.post<MyEvent>("http://localhost:8080/addEvent",event,{params:params}) } showEvents(){ return this.http.get<MyEvent[]>("http://localhost:8080/events") } showEvent(){ return this.http.get<MyEvent>("http://localhost:8080/event") } // getPerson2(username){ // let params = new HttpParams().set('str',username); // return this.http.get<Person>("http://localhost:8080/person",{params:params}) // } signUpToEvent(var1,var2){ let params = new HttpParams().set('name',var1).set('person',var2); return this.http.post("http://localhost:8080/signUpToEvent", params) } // retrievePerson(username:string, password:string){ // return this.http.get<Person>("http://localhost:8080/person", { username, password }) // } deleteEvent(eventID, person){ let params = new HttpParams().set('eventID',eventID).set('person',person); return this.http.delete("http://localhost:8080/unsubscribe",{params:params}) } getEventsByType(type){ return this.http.get<MyEvent[]>(`http://localhost:8080/events/${type}`) } forgotPassword(username, email, password){ let params = new HttpParams() .set('username',username) .set('email',email) .set('password',<PASSWORD>) return this.http.put("http://localhost:8080/changePassword",params) } } <file_sep>import { Component, OnInit } from '@angular/core'; import{Person} from '../login/login.component'; import { DataService } from '../service/data.service'; import { MyEvent } from '../add-event/add-event.component'; import { AuthService } from '../service/auth.service'; @Component({ selector: 'app-person-events', templateUrl: './person-events.component.html', styleUrls: ['./person-events.component.css'] }) export class PersonEventsComponent implements OnInit { constructor(private personservice: DataService, private serviceGuard:AuthService) { } person:Person events:MyEvent[] // this.ws.homeboxPGetAll().map((res:Response) => res.json()).subscribe( // homeboxsp => { // this.homeboxsp = homeboxsp.sensors; // } // ); ngOnInit(): void { let variable = sessionStorage.getItem("authenticatedUser") if(variable!=null) this.serviceGuard.LoggedIn.next(true) this.personservice.getPersonByUsername(variable).subscribe( data=>{ this.person=data this.events=this.person.events } ) } deleteEvent(eventID){ let variable = sessionStorage.getItem("authenticatedUser") this.personservice.deleteEvent(eventID,variable).subscribe( data=>{ } ) window.location.reload(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute} from '@angular/router'; import { DataService } from '../service/data.service'; import { MyEvent } from '../add-event/add-event.component'; import { THIS_EXPR } from '@angular/compiler/src/output/output_ast'; @Component({ selector: 'app-rest-events', templateUrl: './rest-events.component.html', styleUrls: ['./rest-events.component.css'] }) export class RestEventsComponent implements OnInit { events:MyEvent[] constructor(private activatedRoute: ActivatedRoute, private service: DataService) { } private type: string; private typeToLower: string; ngOnInit(): void { this.type = this.activatedRoute.snapshot.paramMap.get('type') console.log("type:"+this.type) this.typeToLower=this.type.toLowerCase() this.service.getEventsByType(this.typeToLower).subscribe( data=>{ console.log(data) this.events=data } ) } } <file_sep>import { Component, OnInit, Injectable } from '@angular/core'; import { DataService } from '../service/data.service'; import { AuthService } from '../service/auth.service'; import { Router } from '@angular/router'; import { MyEvent } from '../add-event/add-event.component'; import { BehaviorSubject, Observable } from 'rxjs'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { username:string = ''; password:string = ''; errorMessage:string='Incorrect login or password '; hide: boolean=false; constructor(private personservice: DataService, private authService:AuthService, private router:Router) { } ngOnInit(): void { } Login(){ this.authService.login(this.username,this.password) this.hide=true //let person = new Person(this.username,this.password) // person.showDet() // this.personservice.getPerson(person).subscribe( // data=>{ // if(data){ // sessionStorage.setItem('authenticatedUser',this.username); // this.loggedIn.next(true); // // console.log("logged in: "+this.state) // this.router.navigate(['welcome',this.username]) // } // console.log(data) // // console.log(this.state) // } // ) } } export class Person{ id:number username:string; password:string; email:string events:Array<MyEvent> //id:number; constructor(username,password?,email?,id?,events?){ this.username=username; this.password=<PASSWORD>; this.email=email; this.id=id; this.events=events } // showDet(){ // console.log("Username:"+this.username+"password:" + this.password) // } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RestEventsComponent } from './rest-events.component'; describe('RestEventsComponent', () => { let component: RestEventsComponent; let fixture: ComponentFixture<RestEventsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ RestEventsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(RestEventsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { DataService } from '../service/data.service'; import { Person } from '../registration/registration.component'; import { AuthService } from '../service/auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-add-event', templateUrl: './add-event.component.html', styleUrls: ['./add-event.component.css'] }) export class AddEventComponent implements OnInit { public type: string = ''; public places: number = 0; public dateEvent: Date = new Date(); public persons: Array<Person>; public owner: Person; //public phone: string = ''; public Event: MyEvent; constructor(private service: DataService, private serviceGuard:AuthService, private router:Router) { } ngOnInit(): void { let username = sessionStorage.getItem('authenticatedUser'); if(username!=null) this.serviceGuard.LoggedIn.next(true) this.service.getPersonByUsername(username).subscribe( data => { this.owner = data; } ) } add() { this.Event = new MyEvent(this.type, this.places, this.dateEvent, this.owner.phoneNumber, this.owner) this.Event.showDet(); this.service.addEvent(this.Event, this.owner.username).subscribe( data=>{ this.router.navigate(['events']) } ) } } export class MyEvent { constructor(type, places, dateEvent, organizerPhone, persons?, id?) { this.organizerPhone = organizerPhone this.id = id this.dateEvent = dateEvent this.places = places this.type = type this.persons = persons } public id: number; public type: string; public places: number; public dateEvent: Date; public organizerPhone: string; public persons: Array<Person> showDet() { console.log("type:" + this.type + " places:" + this.places + " date event" + this.dateEvent + "organizerNumber" + this.organizerPhone + "persons:" + this.persons) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import {LoginComponent} from '../login/login.component'; import { Observable } from 'rxjs'; import { AuthService } from '../service/auth.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { user:string=''; constructor(private router:Router, private authService:AuthService, public login:LoginComponent ) { } isLoggedIn$: Observable<boolean>; ngOnInit(): void { this.isLoggedIn$ = this.authService.isLoggedIn this.user=sessionStorage.getItem('authenticatedUser') } getUser(){ let username =sessionStorage.getItem('authenticatedUser') return username } logout(){ this.authService.logout() } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from '../service/auth.service'; @Component({ selector: 'app-welcome', templateUrl: './welcome.component.html', styleUrls: ['./welcome.component.css'] }) export class WelcomeComponent implements OnInit { constructor(private serviceGuard:AuthService) { } ngOnInit(): void { let username = sessionStorage.getItem("authenticatedUser") if(username!=null) this.serviceGuard.LoggedIn.next(true) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { DataService } from '../service/data.service'; import { Router } from '@angular/router'; import { MyEvent } from '../add-event/add-event.component'; import { Validators } from '@angular/forms'; @Component({ selector: 'app-registration', templateUrl: './registration.component.html', styleUrls: ['./registration.component.css'] }) export class RegistrationComponent implements OnInit { password:string; username:string; email:string; phone:string; person:Person; usernameBusy:boolean=false; constructor(private personservice: DataService,private router:Router) { } ngOnInit(): void { } createPerson(){ this.person = new Person(this.password,this.username,this.email,this.phone) this.personservice.createPerson(this.person) .subscribe( data=>{ console.log(data) if (data===null){ console.log("An username is already busy") this.usernameBusy=true } else{ this.usernameBusy=false } if(!this.usernameBusy) this.router.navigate(['login']) } ) } } export class Person{ password:string; username:string; email:string; id:number; phoneNumber:string; events:Array<MyEvent> constructor(password,username,email?,phoneNumber?,id?,events?){ this.password=<PASSWORD>; this.username=username; this.email = email; this.id=id this.events=events this.phoneNumber=phoneNumber } showDetails(){ console.log('password:'+this.password + ' username:'+this.username+' e-mail:'+this.email+" PhoneNumber: "+ this.phoneNumber) } }<file_sep>import { Component, OnInit } from '@angular/core'; import { DataService } from '../service/data.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-change-password', templateUrl: './change-password.component.html', styleUrls: ['./change-password.component.css'] }) export class ChangePasswordComponent implements OnInit { username:string=''; email:string=''; password:string=''; constructor(private service:DataService, private router:Router) { } ngOnInit(): void { } // showData(){ // console.log(this.username+" Email:"+this.email+" Password:"+this.password) // } changePassword(){ this.service.forgotPassword(this.username,this.email,this.password).subscribe( data=>{ if(data===null){ console.log("no data") }else{ console.log(data) this.router.navigate(['login']) } } ) } }
1f2e4f9a487ec450481dafe0cb22c82bec1c0060
[ "Markdown", "Java", "TypeScript" ]
15
Markdown
Andrii438/SportEventsService1
e7a967a69832e07064fad8a27ae5f4847451f20f
cc2a2c5fa41d184b6528ad97a2260300fd9a5cab
refs/heads/master
<file_sep>from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from mock import patch from sentry.models import ScheduledJob from sentry.testutils import TestCase from sentry.tasks.scheduler import enqueue_scheduled_jobs class EnqueueScheduledJobsTest(TestCase): def test_does_not_schedule_future_job(self): sj = ScheduledJob.objects.create( name='sentry.tasks.enqueue_scheduled_jobs', payload={'foo': 'baz'}, date_scheduled=timezone.now() + timedelta(days=1), ) enqueue_scheduled_jobs() assert ScheduledJob.objects.filter( id=sj.id, ).exists() @patch('sentry.celery.app.send_task') def test_schedules_due_job(self, mock_send_task): sj = ScheduledJob.objects.create( name='sentry.tasks.enqueue_scheduled_jobs', payload={'foo': 'bar'}, date_scheduled=timezone.now(), ) enqueue_scheduled_jobs() assert not ScheduledJob.objects.filter( id=sj.id, ).exists() mock_send_task.assert_called_once_with( 'sentry.tasks.enqueue_scheduled_jobs', kwargs={'foo': 'bar'}, ) <file_sep>from __future__ import absolute_import from django.core.urlresolvers import reverse import json from sentry.testutils import APITestCase class ProjectCreateSampleTest(APITestCase): def test_simple(self): self.login_as(user=self.user) team = self.create_team() project = self.create_project(team=team, name='foo') url = reverse( 'sentry-api-0-project-create-sample', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, } ) response = self.client.post(url, format='json') assert response.status_code == 200, response.content assert 'groupID' in json.loads(response.content) def test_project_platform(self): self.login_as(user=self.user) team = self.create_team() project = self.create_project(team=team, name='foo', platform='javascript-react') url = reverse( 'sentry-api-0-project-create-sample', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, } ) response = self.client.post(url, format='json') assert response.status_code == 200, response.content assert 'groupID' in json.loads(response.content) <file_sep>from __future__ import absolute_import, print_function from django.db import models from django.utils import timezone from jsonfield import JSONField from sentry.db.models import Model, sane_repr class ScheduledJob(Model): __core__ = False name = models.CharField(max_length=128) payload = JSONField() date_added = models.DateTimeField(default=timezone.now) date_scheduled = models.DateTimeField() class Meta: app_label = 'sentry' db_table = 'sentry_scheduledjob' __repr__ = sane_repr('name', 'date_scheduled')
baf2ad76e6d4bf71b17717706d227ef9504712f3
[ "Python" ]
3
Python
nguyentruongky/sentry
211d44f2b6236f11e62e5672681fcddec1117b6c
b1fe26b8af1a850814fbbb8e2681636f30489daf
refs/heads/main
<file_sep>import requests import json course=[] id_list=[] slug_list=[] def api_first(): x = requests.get('http://saral.navgurukul.org/api/courses') y=(x.text) with open("courses.json","w") as f: fi=json.loads(y) json.dump(fi,f,indent=2) list1=(fi["availableCourses"]) index=0 while index<len(list1): course_available=list1[index]["name"] course.append(course_available) id_avaible=list1[index]["id"] id_list.append(id_avaible) print(index,course_available,id_avaible) index+=1 user=int(input("Enter id:- ")) global w t=list1[user] w=t["id"] print("****","Cource Name : ",t["name"],"****") print() api_first() def api_second(): s="http://saral.navgurukul.org/api/courses/74/exercises" s=s.replace("74",w) a=requests.get(s) b=(a.text) with open("data2.json","w") as file1: file2=json.loads(b) json.dump(file2,file1,indent=4) value_dataa=file2["data"] sub_count=0 for u in value_dataa: sub_count+=1 sub=0 print("**",sub_count,":",u["name"],"**") slug_data=u["slug"] slug_list.append(slug_data) if len(u["childExercises"])==0: print(" ",u["childExercises"]," ") else: child_dict=u["childExercises"] ind=0 while ind<len(child_dict): for kill in child_dict[ind]: if kill=="name": sub+=1 print(" " ,child_dict[ind][kill]," ") ind+=1 print(len(slug_list),slug_list) file1.close() api_second() def slug_fun(): user_up_slug=input("enter weather you want to do up or slug: ") if user_up_slug=="up": slug_list.clear() api_first() api_second() slug_fun() elif user_up_slug=="slug": user_slug=int(input("enter your slug index: ")) url='http://saral.navgurukul.org/api/courses/75/exercise/getBySlug?slug=requests__using-json' url=url.replace('requests__using-json',slug_list[user_slug]) slug_url= requests.get(url) print(slug_url.text) next_previous=input("enter weather you want 1. up 2. Next 3. Previous 4. exit ") leng=len(slug_list) if next_previous=="up": slug_list.clear() api_first() api_second() slug_fun() elif next_previous=="next": if user_slug==leng-1: print("no next slug exists") else: ind2=slug_list[user_slug+1] url=url.replace(slug_list[user_slug],slug_list[user_slug+1]) slug_url1= requests.get(url) print(slug_url1.text) elif next_previous=="previous": if user_slug==0: print("no previous slug exists") else: ind3=slug_list[user_slug-1] url=url.replace(slug_list[user_slug],slug_list[user_slug-1]) slug_url2= requests.get(url) print(slug_url2.text) elif next_previous=="exit": print("**EXIT**") slug_fun()
a1163d0ffc862cb77145a5028b5ac3033e3f8981
[ "Python" ]
1
Python
Sana-mohd/Request
67400d21d71f614e748e5337cdd740223417c5ed
06245aafcd6312f1cb5d59a3f6989c4c7e3413e9
refs/heads/master
<repo_name>lhowes86/03_Howes_Laura_2018<file_sep>/03_Howes_Laura_2018.R #'---------------------- #' #' Homework week 03 #' #' @Date 2018-09-28 #' #' @author <NAME> #' #' --------------------- #' #--- # Problem 1 #--- library(dplyr) library(ggplot2) library(forcats) # #1 question 10a setwd("C:/Users/Laura/Dropbox/Grad school/BIOL 607 Biostats/Homework/data") getwd() Gene_data <- read.csv("./04q11NumberGenesRegulated.csv") Gene_data str(Gene_data) Mean_Gene_data <- mean(Gene_data$ngenes) SD_Gene_data <- sd(Gene_data$ngenes) #n = 109 SE_Gene_data <- (SD_Gene_data/sqrt(109)) CI_Gene <- (2*SE_Gene_data) CI_Lower_Gene <- Mean_Gene_data-(CI_Gene) CI_Lower_Gene CI_Upper_Gene <- Mean_Gene_data+(CI_Gene) CI_Upper_Gene #The confidence interval is 12.71 < Mean_Gene_Data < 16.29, or you could write it as #14.5 +or- 1.79 #1 question 10b #This confidence interval from 12.71 to 16.29 shows that in 95% of samples of the sample #population will contain the true mean of the population (within that range). #1 question 17 #This the correct interpretation, as 0.9 < mean < 3.1 as a confidence interval states #95% of samples will contain the true population mean, and the remaining 5% of samples #(2.5% each) could fall above 0.9 or 3.1. #1 question 18a-f beetles_per_night <- c(51,45,61,76,11,117,7,132,52,149) #18a beetles_per_night_mean <- mean(beetles_per_night) beetles_per_night_mean #mean is 70.1 beetles_per_night_sd <- sd(beetles_per_night) beetles_per_night_sd #SD is 48.50074 #18b beetles_per_night_SE <- beetles_per_night_sd/sqrt(length(beetles_per_night)) beetles_per_night_SE #SE is 15.33728 #18c CI_beetles <- 2*beetles_per_night_SE CI_beetles #CI = 30.67456 CI_lower <- beetles_per_night_mean - (2*CI_beetles) CI_lower #CI lower = 8.750872 CI_upper <- beetles_per_night_mean + (2*CI_beetles) CI_upper #CI upper = 131.4491 #18d If I had 25 points instead of 10, would the Mean be greater, less, or the same? #The mean would be about the same no matter what sample size #18e If I had 25 points instead of 10, would the SD be greater, less, or the same? #The SD would be about the same as well, as it's a measure of population like the mean #18f If I had 25 points instead of 10, would the SE be greater, less, or the same? #The standard error would probably be smaller, since more data would help with precision #and you would be dividing by a larger value (since you're taking the sqaure root of a #bigger number) #--- # Problem 2 #--- #2.1 Load the data using readr and make the Month_Names column into a factor #whose levels are in order of month using forcats::fct_inorder. Use levels() - #a function that takes a factor vector and returns the unique levels - on the #column. Are they in the right order? library(readr) sea_ice_data_readr <- read.csv("./NH_seaice_extent_monthly_1978_2016.csv") sea_ice_data_readr <- sea_ice_data_readr %>% mutate(Month_Name = factor(Month_Name)) %>% mutate(Month_Name = fct_inorder(Month_Name)) levels(sea_ice_data_readr$Month_Name) #They are not in the right order, just the ordered they were listed in the data #"Nov" "Dec" "Feb" "Mar" "Jun" "Jul" "Sep" "Oct" "Jan" "Apr" "May" "Aug" #2.2 Try fct_rev() on ice$Month_Name (I called my data frame ice when I made this). #What is the order of factor levels that results? Try out fct_relevel(), and last, #fct_recode() as well. Look at the help files to learn more, and in particular try #out the examples. Use these to guide how you try each functino out. After trying #each of these, mutate month name to get the months in the right order, from January #to December. Show that it worked with levels() fct_rev(sea_ice_data_readr$Month_Name) #They are in reverse order from the levels function #Aug May Apr Jan Oct Sep Jul Jun Mar Feb Dec Nov ?fct_relevel sea_ice_relevel <- fct_relevel(sea_ice_data_readr$Month_Name,"Jan","Feb","Mar","Apr","May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec") sea_ice_relevel ?fct_recode sea_ice_recode <- fct_recode(sea_ice_data_readr$Month_Name,"Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec") sea_ice_recode sea_ice_mutated <- sea_ice_data_readr %>% mutate(Month_Name = fct_relevel(Month_Name,"Jan","Feb","Mar","Apr","May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec")) sea_ice_mutated levels(sea_ice_mutated$Month_Name) #2.3 Now, using what you have just learned about forcats, make a column called Season #that is a copy of Month_Name. Use the function fct_recode to turn it into a factor #vector with the levels Winter, Spring, Summer, Fall in that order. Use levels() on #ice$Season to show that it worked. sea_ice_mutated <- sea_ice_mutated %>% mutate(Season = Month_Name) %>% mutate(Season = fct_recode(Season, Winter = "Jan", Winter = "Feb", Spring = "Mar", Spring = "Apr", Spring = "May", Summer = "Jun", Summer = "Jul", Summer = "Aug", Fall = "Sep", Fall ="Oct", Fall= "Nov", Winter = "Dec")) sea_ice_mutated levels(sea_ice_mutated$Season) #2.4a Make a boxplot showing the variability in sea ice extent every month. Sea_ice_extent <- ggplot(data = sea_ice_mutated, mapping = aes(x = Month_Name, y = Extent)) Sea_ice_extent + geom_boxplot() #2.4b Use dplyr to get the annual minimum sea ice extent. Plot minimum ice #by year, and add a trendline (either a smooth spline or a straight line). Sea_ice_ann_min <- sea_ice_mutated %>% group_by(Year) %>% summarize(min_ice = min(Extent)) ggplot(data = Sea_ice_ann_min, mapping = aes(x = Year, y = min_ice)) + geom_point() + stat_smooth(method = "auto") #2.5 With the original data, plot sea ice by year, with different lines #for different months. Then, use facet_wrap and cut_interval(Month, n=4) to #split the plot into seasons. Sea_ice_by_year <- ggplot(data = sea_ice_mutated, mapping = aes(x = Year, y = Extent, group = Month, color = Month)) Sea_ice_by_year_plot <- Sea_ice_by_year + geom_line() + scale_color_gradientn(colors = rainbow(12)) + facet_wrap(~Season) Sea_ice_by_year_plot #2.6 Last, make a line plot of sea ice by month with different lines as #different years. Gussy it up with colors by year, a different theme, #and whatever other annotations, changes to axes, etc., you think best show #the story of this data. For ideas, see the lab. library(viridisLite) library(viridis) Line_plot_Sea_Ice_Year <- ggplot(data = sea_ice_mutated, mapping = aes(x = Month_Name, y = Extent, group = Year, color = Year)) Line_plot_Sea_Ice_Year + geom_line() + scale_color_viridis(option = "A") + ggtitle("Sea Ice by Year") #2.7 I couldn't get gganimate to install for me :( #2.8 something new Sea_ice_by_year_jitter <-ggplot(data = sea_ice_mutated, mapping = aes(x = Year, y = Extent, group = Month, color = Month)) Sea_ice_by_year_jitter + geom_jitter() scale_color_gradient(low = "blue", high = "red") #EC attempt to install gganimate: install.packages('devtools') devtools::install_github('thomasp85/gganimate') devtools::install_github("thomasp85/tweenr") devtools::install_github("thomasp85/transformr") <file_sep>/03_Howes_Laura_2018.rmd --- output: word_document: default html_document: default --- #'---------------------- #' #' Homework week 03 #' #' Date 2018-09-28 #' #' <NAME> #' #' --------------------- #' ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Problem 1 ```{r eval=FALSE} library(dplyr) library(ggplot2) library(forcats) ``` ###10a ```{r eval=FALSE} setwd("C:/Users/Laura/Dropbox/Grad school/BIOL 607 Biostats/Homework/data") getwd() Gene_data <- read.csv("./04q11NumberGenesRegulated.csv") Gene_data str(Gene_data) Mean_Gene_data <- mean(Gene_data$ngenes) SD_Gene_data <- sd(Gene_data$ngenes) #####n = 109 SE_Gene_data <- (SD_Gene_data/sqrt(109)) CI_Gene <- (2*SE_Gene_data) CI_Lower_Gene <- Mean_Gene_data-(CI_Gene) CI_Lower_Gene CI_Upper_Gene <- Mean_Gene_data+(CI_Gene) CI_Upper_Gene ``` #####The confidence interval is 12.71 < Mean_Gene_Data < 16.29, or you could write it as 14.5 +or- 1.79 ###10b #####This confidence interval from 12.71 to 16.29 shows that in 95% of samples of the sample population will contain the true mean of the population (within that range). ###17 #####This the correct interpretation, as 0.9 < mean < 3.1 as a confidence interval states 95% of samples will contain the true population mean, and the remaining 5% of samples (2.5% each) could fall above 0.9 or 3.1. ###18a-f data set-up ```{r eval=FALSE} beetles_per_night <- c(51,45,61,76,11,117,7,132,52,149) ``` ###18a ```{r eval=FALSE} beetles_per_night_mean <- mean(beetles_per_night) beetles_per_night_mean ``` #####mean is 70.1 ```{r eval=FALSE} beetles_per_night_sd <- sd(beetles_per_night) beetles_per_night_sd ``` #####SD is 48.50074 ###18b ```{r eval=FALSE} beetles_per_night_SE <- beetles_per_night_sd/sqrt(length(beetles_per_night)) beetles_per_night_SE ``` #####SE is 15.33728 ###18c ```{r eval=FALSE} CI_beetles <- 2*beetles_per_night_SE CI_beetles ``` #####CI = 30.67456 ```{r eval=FALSE} CI_lower <- beetles_per_night_mean - (2*CI_beetles) CI_lower ``` #####CI lower = 8.750872 ```{r eval=FALSE} CI_upper <- beetles_per_night_mean + (2*CI_beetles) CI_upper ``` #####CI upper = 131.4491 ###18d ####If I had 25 points instead of 10, would the Mean be greater, less, or the same? #####The mean would be about the same no matter what sample size ###18e ####If I had 25 points instead of 10, would the SD be greater, less, or the same? #####The SD would be about the same as well, as it's a measure of population like the mean ###18f ####If I had 25 points instead of 10, would the SE be greater, less, or the same? #####The standard error would probably be smaller, since more data would help with precision and you would be dividing by a larger value (since you're taking the sqaure root of a bigger number) # Problem 2 ###2.1 ####Load the data using readr and make the Month_Names column into a factor whose levels are in order of month using forcats::fct_inorder. Use levels() - a function that takes a factor vector and returns the unique levels - on the column. Are they in the right order? ```{r eval=FALSE} library(readr) sea_ice_data_readr <- read.csv("./NH_seaice_extent_monthly_1978_2016.csv") sea_ice_data_readr <- sea_ice_data_readr %>% mutate(Month_Name = factor(Month_Name)) %>% mutate(Month_Name = fct_inorder(Month_Name)) levels(sea_ice_data_readr$Month_Name) ``` #####They are not in the right order, just the ordered they were listed in the data "Nov" "Dec" "Feb" "Mar" "Jun" "Jul" "Sep" "Oct" "Jan" "Apr" "May" "Aug" ###2.2 ####Try fct_rev() on ice$Month_Name (I called my data frame ice when I made this). What is the order of factor levels that results? Try out fct_relevel(), and last, fct_recode() as well. Look at the help files to learn more, and in particular try out the examples. Use these to guide how you try each functino out. After trying each of these, mutate month name to get the months in the right order, from January to December. Show that it worked with levels() ```{r eval=FALSE} fct_rev(sea_ice_data_readr$Month_Name) ``` #####They are in reverse order from the levels function. Aug May Apr Jan Oct Sep Jul Jun Mar Feb Dec Nov ```{r eval=FALSE} ?fct_relevel sea_ice_relevel <- fct_relevel(sea_ice_data_readr$Month_Name,"Jan","Feb","Mar","Apr","May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec") sea_ice_relevel ?fct_recode sea_ice_recode <- fct_recode(sea_ice_data_readr$Month_Name,"Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec") sea_ice_recode sea_ice_mutated <- sea_ice_data_readr %>% mutate(Month_Name = fct_relevel(Month_Name,"Jan","Feb","Mar","Apr","May", "Jun","Jul","Aug","Sep","Oct","Nov","Dec")) sea_ice_mutated levels(sea_ice_mutated$Month_Name) ``` ###2.3 ####Now, using what you have just learned about forcats, make a column called Season that is a copy of Month_Name. Use the function fct_recode to turn it into a factor vector with the levels Winter, Spring, Summer, Fall in that order. Use levels() on ice$Season to show that it worked. ```{r eval=FALSE} sea_ice_mutated <- sea_ice_mutated %>% mutate(Season = Month_Name) %>% mutate(Season = fct_recode(Season, Winter = "Jan", Winter = "Feb", Spring = "Mar", Spring = "Apr", Spring = "May", Summer = "Jun", Summer = "Jul", Summer = "Aug", Fall = "Sep", Fall ="Oct", Fall= "Nov", Winter = "Dec")) sea_ice_mutated levels(sea_ice_mutated$Season) ``` ###2.4a ####Make a boxplot showing the variability in sea ice extent every month. ```{r eval=FALSE} Sea_ice_extent <- ggplot(data = sea_ice_mutated, mapping = aes(x = Month_Name, y = Extent)) Sea_ice_extent + geom_boxplot() ``` ###2.4b ####Use dplyr to get the annual minimum sea ice extent. Plot minimum ice by year, and add a trendline (either a smooth spline or a straight line). ```{r eval=FALSE} Sea_ice_ann_min <- sea_ice_mutated %>% group_by(Year) %>% summarize(min_ice = min(Extent)) ggplot(data = Sea_ice_ann_min, mapping = aes(x = Year, y = min_ice)) + geom_point() + stat_smooth(method = "auto") ``` ###2.5 ####With the original data, plot sea ice by year, with different lines for different months. Then, use facet_wrap and cut_interval(Month, n=4) to split the plot into seasons. ```{r eval=FALSE} Sea_ice_by_year <- ggplot(data = sea_ice_mutated, mapping = aes(x = Year, y = Extent, group = Month, color = Month)) Sea_ice_by_year_plot <- Sea_ice_by_year + geom_line() + scale_color_gradientn(colors = rainbow(12)) + facet_wrap(~Season) Sea_ice_by_year_plot ``` ###2.6 ####Last, make a line plot of sea ice by month with different lines as different years. Gussy it up with colors by year, a different theme, and whatever other annotations, changes to axes, etc., you think best show the story of this data. For ideas, see the lab. ```{r eval=FALSE} library(viridisLite) library(viridis) Line_plot_Sea_Ice_Year <- ggplot(data = sea_ice_mutated, mapping = aes(x = Month_Name, y = Extent, group = Year, color = Year)) Line_plot_Sea_Ice_Year + geom_line() + scale_color_viridis(option = "A") + ggtitle("Sea Ice by Year") ``` ###2.7 #####I couldn't get gganimate to install for me :( ###2.8 something new ```{r eval=FALSE} Sea_ice_by_year_jitter <-ggplot(data = sea_ice_mutated, mapping = aes(x = Year, y = Extent, group = Month, color = Month)) Sea_ice_by_year_jitter + geom_jitter() scale_color_gradient(low = "blue", high = "red") ``` ###EC attempt to install gganimate: ```{r eval=FALSE} install.packages('devtools') devtools::install_github('thomasp85/gganimate') devtools::install_github("thomasp85/tweenr") devtools::install_github("thomasp85/transformr") ```
0f1878245771f65705b2aef6dc2674519bbfe05f
[ "R", "RMarkdown" ]
2
R
lhowes86/03_Howes_Laura_2018
e157875927b2e94d5291ed1f728e73fac6c7ee51
8137f67fa9662b4dd41b7e58c409100452c10cc1
refs/heads/main
<file_sep>/***************************************** * <NAME> * LU ID: 0347567 * ****************************************/ public class SingleThreadSolver { private int numberOfSteps; public SingleThreadSolver() { numberOfSteps = 0; } /*** * Starts at the first location in the board and check whether it is valid or * not This function is to ensure the user cannot skip values. * * @param board * @return */ public boolean runSingleThreadSolver(SudokuBoard board) { return singleSolver(board, 0); } /*** * * @param board * @param index * @return */ private boolean singleSolver(SudokuBoard board, int index) { if (index < board.GRIDSIZE * board.GRIDSIZE) { int row = index / board.GRIDSIZE; int column = index % board.GRIDSIZE; if (board.getValue(row, column) != 0) { return singleSolver(board, index + 1); } else { for (int value = 1; value <= board.GRIDSIZE; value++) { if (isBoardValid(board, row, column, value)) { board.setValue(row, column, value); numberOfSteps++; if (singleSolver(board, index + 1)) { return true; } else { board.setValue(row, column, 0); } } } } return false; } else { return true; } } private boolean isBoardValid(SudokuBoard board, int row, int column, int value) { int rowSubGrid = row / board.ROWS * board.ROWS; int columnSubGrid = column / board.COLUMNS * board.COLUMNS; for (int i = 0; i < board.GRIDSIZE; i++) { if (board.getValue(row, i) == value) { return false; } else if (board.getValue(i, column) == value) { return false; } else if (board.getValue(rowSubGrid + i % board.ROWS, columnSubGrid + i / board.COLUMNS) == value) { return false; } } return true; } public void displayNumberOfSteps() { System.out.println("It took " + numberOfSteps + " steps to solve this puzzle. \n"); } }
0c622cae3f3ea1d6af43fdd0ae2ef4254977581f
[ "Java" ]
1
Java
Rylekt/Sudoku_Solver
93507ab56c9ba44d77aaa15e3c6086b1ae60f194
6566215ddacec6bd71f927426ddb3ad64f10ac16
refs/heads/master
<file_sep>package GameGUI; import Logic.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Klasa odpowiedzialna za graficzny intefejs użytkownika. */ public class table extends JFrame { private static Game game; private JButton NewGame; private JPanel panel1; private JPanel Gracz2; private JPanel Gracz3; private JPanel Musik; private JLabel PlayerName2; private JButton nextPlayer; private JLabel one; private JLabel two; private JLabel three; private JLabel four; private JLabel five; private JLabel six; private JLabel seven; private JLabel eight; private JButton playCard1; private JButton playCard2; private JButton playCard3; private JButton playCard4; private JButton playCard5; private JButton playCard6; private JButton playCard7; private JButton playCard8; private JLabel playGround0; private JLabel playGround1; private JLabel playGround2; private JButton playGround0Button; private JTextField answer1; private JButton OKButton; public JPanel enter1; private JPanel enter2; private JPanel enter3; private JTextField answer2; private JTextField answer3; private JButton OkButton2; private JButton OkButton3; private JLabel PlayerName3; private JLabel PlayerName1; private JPanel playGround1Panel; private JButton playGround1Button; private JButton playGround2Button; private JButton startButton; private JButton revealButton; private JLabel ask1; private JLabel ask2; private JLabel ask3; private JLabel Name1; private JLabel Name2; private JLabel Name3; private JLabel Points1; private JLabel Points2; private JLabel Points3; private JButton dismissButton1; private JButton dismissButton2; private JButton dismissButton3; private JLabel textLabel; private JLabel numberLabel; private JLabel textLabel2; private JLabel numberLabel2; private JLabel winnerText; private JLabel winnerLabel; private JButton melduj; private JButton cancelMelduj; private JLabel currentMendunek; private JLabel meldunekValue; private table() { Init(); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { startButton.setVisible(false); enter1.setVisible(true); } }); OKButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ String textFieldValue = answer1.getText(); if (game.voting) { if(game.players[0].dismissed) enter1.setVisible(false); int intFieldValue = -1; try { intFieldValue = Integer.parseInt(textFieldValue); } catch (NumberFormatException e) { ask1.setText("Wrong value. Try again:"); } if(intFieldValue != -1 && intFieldValue > game.howMuch && intFieldValue%10 == 0) { game.howMuch = intFieldValue; game.gamer = 0; game.players[0]._votingPoints = intFieldValue; game.players[1]._votingPoints = 0; game.players[2]._votingPoints = 0; enter1.setVisible(false); nextPlayer.setVisible(true); } else { ask1.setText("Wrong value. Try again:"); } } else { PlayerName1.setText(textFieldValue); game.players[0]._name = textFieldValue; Name1.setText(textFieldValue); enter1.setVisible(false); enter2.setVisible(true); } answer1.setText(""); } }); dismissButton1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.players[0].dismissed = true; game.players[0]._votingPoints = 0; game.dismissCounter--; if(game.dismissCounter == 0) { game.voting = false; game.musik = true; playGround0Button.setEnabled(true); playGround1Button.setEnabled(true); playGround2Button.setEnabled(true); if(!game.players[1].dismissed)game.currentPlayer = 0; if(!game.players[2].dismissed)game.currentPlayer = 1; } enter1.setVisible(false); nextPlayer.setVisible(true); nextPlayer.setEnabled(true); } }); OkButton2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ String textFieldValue = answer2.getText(); if (game.voting) { if(game.players[1].dismissed) enter2.setVisible(false); int intFieldValue = -1; try { intFieldValue = Integer.parseInt(textFieldValue); } catch (NumberFormatException e) { ask2.setText("Wrong value. Try again:"); } if(intFieldValue != -1 && intFieldValue > game.howMuch && intFieldValue%10 == 0) { game.howMuch = intFieldValue; game.gamer = 1; game.players[0]._votingPoints = 0; game.players[1]._votingPoints = intFieldValue; game.players[2]._votingPoints = 0; enter2.setVisible(false); nextPlayer.setVisible(true); } else { ask2.setText("Wrong value. Try again:"); } } else { PlayerName2.setText(textFieldValue); game.players[1]._name = textFieldValue; Name2.setText(textFieldValue); enter2.setVisible(false); enter3.setVisible(true); } answer2.setText(""); } }); dismissButton2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.players[1].dismissed = true; game.players[1]._votingPoints = 0; game.dismissCounter--; if(game.dismissCounter == 0) { game.voting = false; game.musik = true; playGround0Button.setEnabled(true); playGround1Button.setEnabled(true); playGround2Button.setEnabled(true); if(!game.players[0].dismissed)game.currentPlayer = 2; if(!game.players[2].dismissed)game.currentPlayer = 1; } enter2.setVisible(false); nextPlayer.setVisible(true); nextPlayer.setEnabled(true); } }); OkButton3.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ String textFieldValue = answer3.getText(); if (game.voting) { if(game.players[2].dismissed) enter3.setVisible(false); int intFieldValue = -1; try { intFieldValue = Integer.parseInt(textFieldValue); } catch (NumberFormatException e) { ask3.setText("Wrong value. Try again:"); } if(intFieldValue != -1 && intFieldValue > game.howMuch && intFieldValue%10 == 0) { game.howMuch = intFieldValue; game.gamer = 2; game.players[0]._votingPoints = 0; game.players[1]._votingPoints = 0; game.players[2]._votingPoints = intFieldValue; enter3.setVisible(false); nextPlayer.setVisible(true); } else { ask3.setText("Wrong value. Try again:"); } } else { PlayerName3.setText(textFieldValue); game.players[2]._name = textFieldValue; Name3.setText(textFieldValue); enter3.setVisible(false); revealButton.setVisible(true); SetPlayGroundVisible(true); game.voting = true; } answer3.setText(""); } }); dismissButton3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.players[2].dismissed = true; game.players[2]._votingPoints = 0; game.dismissCounter--; if(game.dismissCounter == 0) { game.voting = false; game.musik = true; playGround0Button.setEnabled(true); playGround1Button.setEnabled(true); playGround2Button.setEnabled(true); if(!game.players[0].dismissed)game.currentPlayer = 2; if(!game.players[1].dismissed)game.currentPlayer = 0; } enter3.setVisible(false); nextPlayer.setVisible(true); nextPlayer.setEnabled(true); } }); nextPlayer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(game.playGround[0].getImageURL() != "./Cards/blankCard.png" && game.playGround[1].getImageURL() != "./Cards/blankCard.png" && game.playGround[2].getImageURL() != "./Cards/blankCard.png") { game.CircleEnd(); } else { game.currentPlayer = (game.currentPlayer + 1) % 3; } CoverCards(); revealButton.setVisible(true); nextPlayer.setVisible(false); PlayerName1.setText(game.players[game.currentPlayer]._name); PlayerName2.setText(game.players[(game.currentPlayer + 1) % 3]._name); PlayerName3.setText(game.players[(game.currentPlayer + 2) % 3]._name); melduj.setVisible(false); cancelMelduj.setVisible(false); } }); revealButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MeldunekIcon(game.meldunek); if(game.voting) { textLabel.setText("Higher vote: "); numberLabel.setText(Integer.toString(game.howMuch)); ShowHand(); SetPlayButtonsVisible(false); if(game.currentPlayer == 0) { enter1.setVisible(true); dismissButton1.setVisible(true); ask1.setText("How much you can play?"); } else if(game.currentPlayer == 1) { enter2.setVisible(true); dismissButton2.setVisible(true); ask2.setText("How much you can play?"); } else if(game.currentPlayer == 2) { enter3.setVisible(true); dismissButton3.setVisible(true); ask3.setText("How much you can play?"); } } else { if(!game.musik) { textLabel.setText("Voted points: "); numberLabel.setText(Integer.toString(game.players[game.currentPlayer]._votingPoints)); textLabel2.setText("Round points: "); numberLabel2.setText(Integer.toString(game.players[game.currentPlayer]._roundPionts)); Card blankCard = new Card(0, 0, "./Cards/blankCard.png"); if (game.playGround[0].getImageURL() != "./Cards/blankCard.png" && game.playGround[1].getImageURL() != "./Cards/blankCard.png" && game.playGround[2].getImageURL() != "./Cards/blankCard.png") { game.playGround[0] = blankCard; game.playGround[1] = blankCard; game.playGround[2] = blankCard; game.circleCounter--; } ShowHand(); ShowPlayGround(); SetPlayButtonsVisible(true); nextPlayer.setVisible(true); nextPlayer.setEnabled(false); int winner; if(game.circleCounter == 0) { winner = game.RoundEnd(); if(winner == -1) { game.RoundStart(); MeldunekIcon(0); revealButton.doClick(); } else { SetPlayGroundVisible(false); SetPlayButtonsVisible(false); SetPlayButtonsVisible(false); CoverCards(); enter1.setVisible(false); enter2.setVisible(false); enter3.setVisible(false); nextPlayer.setVisible(false); melduj.setVisible(false); MeldunekIcon(0); Name1.setVisible(false); Name2.setVisible(false); Name3.setVisible(false); Points1.setVisible(false); Points2.setVisible(false); Points3.setVisible(false); textLabel.setVisible(false); textLabel2.setVisible(false); numberLabel.setVisible(false); numberLabel2.setVisible(false); winnerText.setText("The winner is "); winnerLabel.setText(game.players[winner]._name + " !!!"); } } if (game.playGround[0].getImageURL() == "./Cards/blankCard.png" && game.playGround[1].getImageURL() == "./Cards/blankCard.png" && game.playGround[2].getImageURL() == "./Cards/blankCard.png") { melduj.setVisible(true); cancelMelduj.setVisible(false); } } else { playGround0.setIcon(game._deck.getCard(0).getImage()); playGround1.setIcon(game._deck.getCard(1).getImage()); playGround2.setIcon(game._deck.getCard(2).getImage()); SetPlayGroundButtonsVisible(true); SetPlayButtonsVisible(true); SetPlayButtonsText("Dismiss"); ShowHand(); ShowPlayGround(); } } revealButton.setVisible(false); UpdatePoints(); } }); playGround0Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Dismiss(0); playGround0Button.setEnabled(false); } }); playGround1Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Dismiss(1); playGround1Button.setEnabled(false); } }); playGround2Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Dismiss(2); playGround2Button.setEnabled(false); } }); playCard1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(0); } }); playCard2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(1); } }); playCard3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(2); } }); playCard4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(3); } }); playCard5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(4); } }); playCard6.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(5); } }); playCard7.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(6); } }); playCard8.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Click_Play(7); } }); melduj.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { melduj.setVisible(false); cancelMelduj.setVisible(true); DisablePlayButtons(); if(IfContainsMeldunek(40)) { Card tmpQeen = new Card(3,40, "./Cards/c13.png"); EnableQueenPlayButton(QueenIndex(40)); } if(IfContainsMeldunek(60)) { Card tmpQeen = new Card(3,60, "./Cards/s13.png"); EnableQueenPlayButton(QueenIndex(60)); } if(IfContainsMeldunek(80)) { Card tmpQeen = new Card(3,80, "./Cards/d13.png"); EnableQueenPlayButton(QueenIndex(80)); } if(IfContainsMeldunek(100)) { Card tmpQeen = new Card(3,100, "./Cards/h13.png"); EnableQueenPlayButton(QueenIndex(100)); } game.melduj = true; } }); cancelMelduj.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancelMelduj.setVisible(false); melduj.setVisible(true); game.melduj = false; ShowHand(); } }); } private void Init() { SetPlayGroundButtonsVisible(false); SetPlayButtonsVisible(false); SetPlayGroundVisible(false); nextPlayer.setVisible(false); revealButton.setVisible(false); dismissButton1.setVisible(false); dismissButton2.setVisible(false); dismissButton3.setVisible(false); enter1.setVisible(false); enter2.setVisible(false); enter3.setVisible(false); melduj.setVisible(false); cancelMelduj.setVisible(false); } private void Click_Play(int index) { if(!game.musik && !game.melduj) { game.playCard(index); ShowHand(); ShowPlayGround(); DisablePlayButtons(); nextPlayer.setEnabled(true); melduj.setVisible(false); } if(game.musik){ game.players[(game.currentPlayer + game.musikCounter) % 3]._hand.add(game.players[game.currentPlayer].GetHand().get(index)); game.players[game.currentPlayer].removeCard(index); game.musikCounter--; ShowHand(); MusikEnd(); } if(game.melduj) { game.meldunek = game.players[game.currentPlayer]._hand.get(index).getColor(); game.playCard(index); ShowHand(); ShowPlayGround(); DisablePlayButtons(); nextPlayer.setEnabled(true); cancelMelduj.setVisible(false); game.players[game.currentPlayer]._roundPionts += game.meldunek; game.melduj = false; } } private void MeldunekIcon(int color) { if(color == 0) { currentMendunek.setText(""); meldunekValue.setText(""); } if(color == 40){ currentMendunek.setText("Current meldunek: "); meldunekValue.setText("Spades"); } if(color == 60){ currentMendunek.setText("Current meldunek: "); meldunekValue.setText("Clubs"); } if(color == 80){ currentMendunek.setText("Current meldunek: "); meldunekValue.setText("Diamonds"); } if(color == 100){ currentMendunek.setText("Current meldunek: "); meldunekValue.setText("Hearts"); } } private void Click_Dismiss(int index) { game.players[(game.currentPlayer + game.musikCounter) % 3].GetHand().add(game._deck.getCard(index)); game._deck.removeCard(index); game.musikCounter--; ShowPlayGround(); ShowHand(); MusikEnd(); } private void MusikEnd() { if(game.musikCounter == 0) { if(game._deck.getCard(0).getImageURL() != "./Cards/blankCard.png")game.players[game.currentPlayer]._hand.add(game._deck.getCard(0)); if(game._deck.getCard(1).getImageURL() != "./Cards/blankCard.png")game.players[game.currentPlayer]._hand.add(game._deck.getCard(1)); if(game._deck.getCard(2).getImageURL() != "./Cards/blankCard.png")game.players[game.currentPlayer]._hand.add(game._deck.getCard(2)); game.players[0].ClearHand(); game.players[1].ClearHand(); game.players[2].ClearHand(); game.musik = false; Card blankCard = new Card(0, 0, "./Cards/blankCard.png"); if (game.playGround[0].getImageURL() != "./Cards/blankCard.png" && game.playGround[1].getImageURL() != "./Cards/blankCard.png" && game.playGround[2].getImageURL() != "./Cards/blankCard.png") { game.playGround[0] = blankCard; game.playGround[1] = blankCard; game.playGround[2] = blankCard; } ShowHand(); ShowPlayGround(); SetPlayButtonsVisible(true); nextPlayer.setVisible(true); nextPlayer.setEnabled(false); UpdatePoints(); playGround0Button.setEnabled(true); playGround1Button.setEnabled(true); playGround2Button.setEnabled(true); SetPlayGroundButtonsVisible(false); SetPlayButtonsText("Play"); melduj.setVisible(true); } } private void ShowPlayGround() { if(!game.musik) { playGround0.setIcon(game.playGround[0].getImage()); playGround1.setIcon(game.playGround[1].getImage()); playGround2.setIcon(game.playGround[2].getImage()); } else { playGround0.setIcon(game._deck.getCard(0).getImage()); playGround1.setIcon(game._deck.getCard(1).getImage()); playGround2.setIcon(game._deck.getCard(2).getImage()); } } private void ShowHand() { one.setIcon(game.players[game.currentPlayer].GetHand().get(0).getImage()); two.setIcon(game.players[game.currentPlayer].GetHand().get(1).getImage()); three.setIcon(game.players[game.currentPlayer].GetHand().get(2).getImage()); four.setIcon(game.players[game.currentPlayer].GetHand().get(3).getImage()); five.setIcon(game.players[game.currentPlayer].GetHand().get(4).getImage()); six.setIcon(game.players[game.currentPlayer].GetHand().get(5).getImage()); seven.setIcon(game.players[game.currentPlayer].GetHand().get(6).getImage()); eight.setIcon(game.players[game.currentPlayer].GetHand().get(7).getImage()); playCard1.setEnabled(false); playCard2.setEnabled(false); playCard3.setEnabled(false); playCard4.setEnabled(false); playCard5.setEnabled(false); playCard6.setEnabled(false); playCard7.setEnabled(false); playCard8.setEnabled(false); if(game.currentPlayer != game.gamer) { int gamerColor = game.playGround[game.gamer].getColor(); int flag = 0; for (Card card : game.players[game.currentPlayer].GetHand()) { if (card.getColor() == gamerColor) { flag = 1; } } if(flag == 1){ if (game.players[game.currentPlayer].GetHand().get(0).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(0).getColor() == gamerColor) playCard1.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(1).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(1).getColor() == gamerColor) playCard2.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(2).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(2).getColor() == gamerColor) playCard3.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(3).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(3).getColor() == gamerColor) playCard4.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(4).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(4).getColor() == gamerColor) playCard5.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(5).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(5).getColor() == gamerColor) playCard6.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(6).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(6).getColor() == gamerColor) playCard7.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(7).getImageURL() != "./Cards/blankCard.png" && game.players[game.currentPlayer].GetHand().get(7).getColor() == gamerColor) playCard8.setEnabled(true); } else { if (game.players[game.currentPlayer].GetHand().get(0).getImageURL() != "./Cards/blankCard.png") playCard1.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(1).getImageURL() != "./Cards/blankCard.png") playCard2.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(2).getImageURL() != "./Cards/blankCard.png") playCard3.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(3).getImageURL() != "./Cards/blankCard.png") playCard4.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(4).getImageURL() != "./Cards/blankCard.png") playCard5.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(5).getImageURL() != "./Cards/blankCard.png") playCard6.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(6).getImageURL() != "./Cards/blankCard.png") playCard7.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(7).getImageURL() != "./Cards/blankCard.png") playCard8.setEnabled(true); } } else { if (game.players[game.currentPlayer].GetHand().get(0).getImageURL() != "./Cards/blankCard.png") playCard1.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(1).getImageURL() != "./Cards/blankCard.png") playCard2.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(2).getImageURL() != "./Cards/blankCard.png") playCard3.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(3).getImageURL() != "./Cards/blankCard.png") playCard4.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(4).getImageURL() != "./Cards/blankCard.png") playCard5.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(5).getImageURL() != "./Cards/blankCard.png") playCard6.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(6).getImageURL() != "./Cards/blankCard.png") playCard7.setEnabled(true); if (game.players[game.currentPlayer].GetHand().get(7).getImageURL() != "./Cards/blankCard.png") playCard8.setEnabled(true); } } private void CoverCards() { ImageIcon image = new javax.swing.ImageIcon(table.class.getResource("./CardBacks/Card-Back-01.png")); one.setIcon(image); two.setIcon(image); three.setIcon(image); four.setIcon(image); five.setIcon(image); six.setIcon(image); seven.setIcon(image); eight.setIcon(image); } private void DisablePlayButtons() { playCard1.setEnabled(false); playCard2.setEnabled(false); playCard3.setEnabled(false); playCard4.setEnabled(false); playCard5.setEnabled(false); playCard6.setEnabled(false); playCard7.setEnabled(false); playCard8.setEnabled(false); } private void SetPlayButtonsVisible(boolean set) { playCard1.setVisible(set); playCard2.setVisible(set); playCard3.setVisible(set); playCard4.setVisible(set); playCard5.setVisible(set); playCard6.setVisible(set); playCard7.setVisible(set); playCard8.setVisible(set); } private void SetPlayButtonsText(String tekst) { playCard1.setText(tekst); playCard2.setText(tekst); playCard3.setText(tekst); playCard4.setText(tekst); playCard5.setText(tekst); playCard6.setText(tekst); playCard7.setText(tekst); playCard8.setText(tekst); } private void SetPlayGroundButtonsVisible(boolean set) { playGround0Button.setVisible(set); playGround1Button.setVisible(set); playGround2Button.setVisible(set); } private void SetPlayGroundVisible(boolean set) { playGround0.setVisible(set); playGround1.setVisible(set); playGround2.setVisible(set); } private void UpdatePoints() { String tmpString; tmpString = Integer.toString(game.players[0]._points); Points1.setText(tmpString + " points"); tmpString = Integer.toString(game.players[1]._points); Points2.setText(tmpString + " points"); tmpString = Integer.toString(game.players[2]._points); Points3.setText(tmpString + " points"); textLabel.setText("Voted points: "); numberLabel.setText(Integer.toString(game.players[game.currentPlayer]._votingPoints)); textLabel2.setText("Round points: "); numberLabel2.setText(Integer.toString(game.players[game.currentPlayer]._roundPionts)); } private boolean IfContainsMeldunek(int color) { int couple = 0; for(Card queen: game.players[game.currentPlayer]._hand) { if(queen.getColor() == color && queen.getValue() == 3) couple++; } for(Card king: game.players[game.currentPlayer]._hand) { if(king.getColor() == color && king.getValue() == 4) couple++; } if(couple == 2) { return true; } else { return false; } } private void EnableQueenPlayButton(int index) { if(index == 0) playCard1.setEnabled(true); if(index == 1) playCard2.setEnabled(true); if(index == 2) playCard3.setEnabled(true); if(index == 3) playCard4.setEnabled(true); if(index == 4) playCard5.setEnabled(true); if(index == 5) playCard6.setEnabled(true); if(index == 6) playCard7.setEnabled(true); if(index == 7) playCard8.setEnabled(true); } private int QueenIndex(int color) { int index = 0; int i = 0; for(Card queen: game.players[game.currentPlayer]._hand) { if(queen.getValue() == 3 && queen.getColor() == color) index = i; i++; } return index; } /** * Metoda main odpowiedzialna za inicjację aplikacji, jej interfejsu graficznego oraz tworząca nową grę (Game). * @param args default. */ public static void main(String[] args){ JFrame frame = new JFrame("App"); frame.setContentPane (new table().panel1); game = new Game(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } private void createUIComponents() { // TODO: place custom component creation code here } }<file_sep># Tysiac Gra w tysiąca - Projekt na zajęcia z Jezyków i Technik Programowania na Wojskowej Akademii Technicznej.
a15e02a3fc57a28ced98987940d8230bf87c37e9
[ "Markdown", "Java" ]
2
Java
SzymonPapierzewski/Tysiac
e4993537a114625e9fdc9619225042457e0e1a11
90c3b905253d5edf759b06801127a57fdd26b997
refs/heads/master
<repo_name>SergeyShamrikov/prosoft11<file_sep>/public_html/Дизайн/prosoft_change/public_html/script.js $(document).ready(function(){ resize(); /* placeHolder */ var placeHolder = 'Искать программное обеспечение, документацию, презентации...'; $('#query').val(placeHolder).addClass('placeHolder'); $('#query').focus(function(){ if ( $(this).val()==placeHolder ) { $(this).val('').removeClass('placeHolder'); } }).blur(function(){ if ( $(this).val()=='' ) { $('#query').val(placeHolder).addClass('placeHolder'); } }); /* ie */ if ( browser()=='Internet Explorer' ) { $('#ex_bot_inner_bot ul').css({ 'position': 'relative', 'top': -7 }); } /* additional from clearFields */ $('#clearFields').click(function(){ setTimeout(function(){ $('#query').val(placeHolder); }, 100); }); /* скрываем/отображаем область расширенного поиска */ $('#extend_link a').click(function(){ if ( !$('#extend_area').hasClass('extend_area2') ) { if ( !$(this).hasClass('active') ) { $(this).addClass('active'); $('#extend_area > div').show(); } else { $(this).removeClass('active'); $('#extend_area > div').hide(); } } else { if ( !$(this).hasClass('active') ) { $(this).addClass('active'); $('#extend_area').show(); } else { $(this).removeClass('active'); $('#extend_area').hide(); } } }); /* сброс формы поиска (всей) */ $('#clearFields').click(function(){ $('#_clearFields').click(); }); /* скрипт для календаря */ }); function resize() { if ( $('body').height()<$('#page > table.cm').height() ) { $('body').css('height', $('#page > table.cm').height()+40); } if ( $(window).width()>=1280 ) { $('#page.page2').css('margin-left', 80); } else { $('#page.page2').css('margin-left', 30); } } function browser() { var ua = navigator.userAgent; if (ua.search(/MSIE/) > 0) return 'Internet Explorer'; if (ua.search(/Firefox/) > 0) return 'Firefox'; if (ua.search(/Opera/) > 0) return 'Opera'; if (ua.search(/Chrome/) > 0) return 'Google Chrome'; if (ua.search(/Safari/) > 0) return 'Safari'; if (ua.search(/Konqueror/) > 0) return 'Konqueror'; if (ua.search(/Iceweasel/) > 0) return 'Debian Iceweasel'; if (ua.search(/SeaMonkey/) > 0) return 'SeaMonkey'; if (ua.search(/Gecko/) > 0) return 'Gecko'; return 'Search Bot'; } $(window).resize(function(){ resize(); });
01f614f2840300967daabd5597dc97949dcc3494
[ "JavaScript" ]
1
JavaScript
SergeyShamrikov/prosoft11
e271160ece67515d6c225195fce3294c8e90a9c0
249fdf482214e7a60f3f7a21e1553cef98f1771a
refs/heads/master
<file_sep># 太工微社区 本项目为**太原工业学院**微社区小程序: 技术背景 - [云开发](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html):微信官方的云开发技术 - [WeUI](https://weui.io/):采用微信官方WeUI基础库,统一视觉体验 ## 开发人员 - [张嘉祺](https://www.mttgo.com) - 李瑞彬 - 郭丁菲 <file_sep>// miniprogram/pages/post/post.js const app = getApp() const db = wx.cloud.database() const sorts = db.collection('Sorts') const posts = db.collection('Posts') var sections Page({ /** * 页面的初始数据 */ data: { mtop: app.globalData.height * 2 + 22 + "px", length: 0, sections: ["请选择板块"], sectionId: ["0"], sectionIndex: 0, content: "", navbarData: { title: "发帖", show: 0, back: 1 }, urlArr: [], fileID: [], isSubmit: 0 }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { console.log(app.globalData.openid) this.setData({ selectFile: this.selectFile.bind(this), uplaodFile: this.uplaodFile.bind(this), }); var sections = this.data.sections; var sectionId = this.data.sectionId; var that = this; sorts.get({ success: function (res) { for (let i = 0; i < res.data.length; i++) { //sections[res.data[i]._id] = res.data[i].name; sections.push(res.data[i].name) sectionId.push(res.data[i]._id) } that.setData({ sections: sections, sectionId: sectionId }) } }) console.log(this.data.sections) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () {}, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, TextareaInput: function (e) { this.setData({ length: e.detail.value.length, content: e.detail.value }) }, chooseImage: function (e) { var that = this; wx.chooseImage({ sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 that.setData({ files: that.data.files.concat(res.tempFilePaths) }); } }) }, /**previewImage: function (e) { wx.previewImage({ current: e.currentTarget.id, // 当前显示图片的http链接 urls: this.data.files // 需要预览的图片http链接列表 }) },**/ selectFile(files) { console.log('files', files) // 返回false可以阻止某次文件上传 }, uplaodFile(files) { var that = this; console.log('upload files', files) // 文件上传的函数,返回一个promise return new Promise((resolve, reject) => { var tempFilePaths = files.tempFilePaths; var object = []; object['urls'] = []; var flag = false; var count = 0; var urlArr = that.data.urlArr; var fileID = that.data.fileID; for (let i = 0; i < tempFilePaths.length; i++) { var extension = tempFilePaths[i].substr(tempFilePaths[i].lastIndexOf(".")); console.log("扩展名:" + extension); wx.cloud.uploadFile({ cloudPath: 'uploadImg/' + new Date().getTime() + Math.ceil(Math.random() * 1000) + extension, // 上传至云端的路径 filePath: tempFilePaths[i], // 小程序临时文件路径 success: res => { console.log("上传成功fileID:" + res.fileID); //返回文件id到全局数据 fileID.push(res.fileID) that.setData({ fileID: fileID }); wx.cloud.getTempFileURL({ fileList: [res.fileID], success: res => { console.log("临时url:", res.fileList[0].tempFileURL); //返回url到全局数据 urlArr.push(res.fileList[0].tempFileURL) that.setData({ urlArr: urlArr }); object['urls'] = object['urls'].concat(res.fileList[0].tempFileURL); }, fail: console.error }) }, fail: console.error }); if ((i + 1) >= tempFilePaths.length) { flag = true; } } var re = setInterval(() => { if (object['urls'].length > 0 && flag) { resolve(object); clearInterval(re); } else { count++ if (count > 100) { reject('上传超时') clearInterval(re); } } }, 100) }) }, uploadError(e) { console.log('upload error', e.detail) }, uploadSuccess(e) { console.log('upload success', e.detail) }, deleteImg(e) { console.log('deleteImg', e.detail) var urlArr = this.data.urlArr; var fileID = this.data.fileID; urlArr.splice(e.detail.index, 1); fileID.splice(e.detail.index, 1); this.setData({ urlArr: urlArr, fileID: fileID }) }, bindSectionChange: function (e) { console.log('板块选择发生变化,下标为', e.detail.value); console.log('对应名称为', this.data.sections[e.detail.value]); console.log('对应id为', this.data.sectionId[e.detail.value]); this.setData({ sectionIndex: e.detail.value }) }, bindSectionTap: function (e) { this.setData({ sections: sections }) console.log('setdata'); }, submitForm() { console.log(this.data.length); console.log(this.data.fileID) console.log(this.data.urlArr) if (this.data.length === 0) { wx.showToast({ title: '请先编辑帖子', icon: 'error' }) } else if (this.data.length < 10) { wx.showToast({ title: '最少10字哦', icon: 'error' }) } else if (this.data.sectionIndex === '0' || this.data.sectionIndex === 0) { wx.showToast({ title: '请选择板块', icon: 'error' }) } else if (this.data.isSubmit == 1) { wx.showToast({ title: '请勿重复提交', icon: 'error' }) } else { this.setData({ isSubmit: 1 }) posts.add({ data: { openid: app.globalData.openid, content: this.data.content, sortId: this.data.sectionId[this.data.sectionIndex], images: this.data.fileID, createTime: new Date() }, success: function (res) { console.log(res) wx.showToast({ title: '提交成功' }) setTimeout(function () { var pages = getCurrentPages(); var prevPage = pages[pages.length - 2]; prevPage.setData({ reload: true, }); wx.navigateBack({ delta: 0, }) }, 1500) } }) } } })<file_sep>// miniprogram/pages/postDetails/postDetails.js const app = getApp() const db = wx.cloud.database() const comments = db.collection('Comments') //评论表 const posts = db.collection('Posts') //帖子表 const users = db.collection('Users') //用户表 const notice = db.collection('Notice') //系统通知表 Page({ /** * 页面的初始数据 */ data: { navbarData: { title: "帖子详情", show: 0, back:1 }, inputIsFocus:false, deleteIndex:-1, reportConfirm:[{ text: '确认举报', value: 1 }], deleteConfirm:[{ text: '确认删除', value: 1 }], showDelete:false, showReport:false, commentsItem:[], content:"", noCommnet:true }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let object=JSON.parse(options.str); this.setData({ post:object }) this.getComments(object.postId) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { this.setData({ height: (app.globalData.height) * 2 + 48 }) var that = this var i = 0 var setData = setInterval(function(){ that.setData({ commentsItem: that.data.commentsItem, noCommnet:that.data.commentsItem.length>0?false:true }) i++; if(i>50){ clearInterval(setData) } },100) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, getComments: function(postId){ var that = this var commentsItem = [] comments.orderBy("createTime","desc").where({ postId:postId }).get({ success:function(res){ commentsItem = res.data for(let i=0;i<commentsItem.length;i++){ let createTime = new Date(commentsItem[i].createTime); let time = (new Date() - createTime)/1000 if(time<60){ commentsItem[i].createTime="1分钟前" }else if(time<60*60){ commentsItem[i].createTime= parseInt((time/60))+"分钟前" }else if(time<60*60*24){ commentsItem[i].createTime= parseInt((time/60/60))+"小时前" }else if(time<60*60*24*30){ commentsItem[i].createTime= parseInt((time/60/60/24))+"天前" }else{ if(createTime.getFullYear() == new Date().getFullYear()){ commentsItem[i].createTime= (createTime.getMonth()+1)+"月"+createTime.getDay()+"日"; }else{ commentsItem[i].createTime= createTime.getFullYear()+"年"+(createTime.getMonth()+1)+"月"+createTime.getDay()+"日"; } } users.where({ openid:commentsItem[i].openid }).get({ success:function(res){ commentsItem[i].profile = res.data[0].profile commentsItem[i].nickname = res.data[0].nickname } }) } that.setData({ commentsItem:commentsItem }) console.log(commentsItem) } }) }, inputOnFocus:function(e){ this.setData({ inputIsFocus:true }) }, inputOnBlur:function(e){ this.setData({ content:e.detail.value }) var that= this setTimeout(function(){ that.setData({ inputIsFocus:false }) },500) }, submit:function(e){ var that = this; setTimeout(function(){ if(that.data.content.trim().length==0){ wx.showToast({ title: '请填写评论', icon: 'error' }) }else if(that.data.content.trim().length<2){ wx.showToast({ title: '至少2字哦', icon: 'error' }) }else{ comments.add({ data:{ openid:app.globalData.openid, postId:that.data.post.postId, content:that.data.content, createTime:new Date() }, success:function(res){ console.log(res) wx.showToast({ title: '评论成功', }) let contentTemp = that.data.content that.setData({ content:"" }) let commentsItem = that.data.commentsItem let comment = {} comment.content = contentTemp; comment.openid = app.globalData.openid; comment.postId = that.data.post.postId; comment.createTime = "刚刚" comment.profile = app.globalData.User[1] comment.nickname = app.globalData.User[2] //console.log(app.globalData.User) console.log(comment) commentsItem.unshift(comment) console.log(commentsItem) that.setData({ commentsItem: commentsItem, noCommnet:false }) console.log("this.commentsItem",that.data.commentsItem) } }) } }, 200); if(app.globalData.openid.trim()!=this.data.post.openid){ notice.where({ postId:that.data.post.postId, openid:that.data.post.openid, isRead:false }).count({ success:function(res){ if(res.total > 0){ console.log("相同类型通知仍有未读") }else{ notice.add({ data:{ content:"您的帖子“"+that.data.post.content+"”被评论了,点击查看", createTime:new Date(), openid:that.data.post.openid, postId:that.data.post.postId, isRead:false }, success:function(res){ console.log(res) } }) } } }) } }, deleteTap:function(e){ this.setData({ showDelete:true, commandId:e.currentTarget.dataset.postid, deleteIndex:e.currentTarget.dataset.index }) console.log("删除",e.currentTarget.dataset.postid) this.setData({ isTap:false }) }, reportTap:function(e){ this.setData({ showReport:true, commandId:e.currentTarget.dataset.postid }) console.log("举报",e.currentTarget.dataset.postid) this.setData({ isTap:false }) }, reportConfirm:function(e){ this.setData({ showReport:false }) wx.showToast({ title: '已举报' }) }, deleteConfirm:function(e){ this.setData({ showDelete:false, }) this.deletePost(this.data.commandId) wx.showToast({ title: '已删除' }) setTimeout(function () { var pages = getCurrentPages(); var prevPage = pages[pages.length - 2]; prevPage.setData({ reload: true, }); wx.navigateBack({ delta: 0, }) }, 1500) }, /** * 根据postId删除帖子 * @param {string} postId */ deletePost:function(postId){ console.log("进入deletePost",postId) posts.doc(postId).remove({ success: function(res){ console.log(res) } }) }, /** * 点击图片触发事件 * @param {object}} e * e.currentTarget.dataset.index 为帖子在posts中的所属下标 * e.currentTarget.dataset.imageindex 为image在post中的所属下标 */ imgTap: function (e) { console.log(this.data); var url = this.data.post.images[e.currentTarget.dataset.imageindex]; var urls = []; urls['urls'] = []; urls['urls'] = urls['urls'].concat(url); this.previewImage(url, this.data.post.images) }, /** * 大图预览图片 * @param {array} url 当前显示图片的http链接 * @param {array} urls 需要预览的图片http链接列表 */ previewImage: function (url, urls) { wx.previewImage({ current: url, // 当前显示图片的http链接 urls: urls // 需要预览的图片http链接列表 }) }, })<file_sep>const app = getApp() const db = wx.cloud.database() const notice = db.collection('Notice') //系统通知表 const users = db.collection('Users') //用户表 const posts = db.collection('Posts') //帖子表 const sorts = db.collection('Sorts') //分类表 Page({ /** * 页面的初始数据 */ data: { navbarData: { title: "系统通知", show: 0, back: 1 }, noRead: true, notices: [] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { this.setData({ height: (app.globalData.height) * 2 }) this.setData({ notices: [] }) var that = this notice.orderBy("createTime", "desc").where({ openid: app.globalData.openid, }).get({ success: function (res) { var notices = that.data.notices for (let i = 0; i < res.data.length; i++) { var notice = {} notice.content = res.data[i].content notice.postId = res.data[i].postId notice.isRead = res.data[i].isRead notices.push(notice) } that.setData({ notices: notices }) } }) setTimeout(function () { notice.where({ openid: app.globalData.openid }).update({ data: { isRead: true }, success: function (res) { console.log(res) } }) }, 1000) }, itemTap: function (e) { let postId = e.currentTarget.dataset.postid var that = this; posts.doc(postId).get({ success: function (res) { console.log(res.data) var post = { openid: "", //1 nickname: "", //1 profile: "", //1 createTime: "", //1 sortName: "", //1 content: "", //1 images: [], //1 praisesCount: 0, //1 commentsCount: 0, //1 isPraise: false, //1 isMe: false, //1, postId: "" //1 } let createTime = new Date(res.data.createTime); let time = (new Date() - createTime) / 1000 if (time < 60) { post.createTime = "1分钟前" } else if (time < 60 * 60) { post.createTime = parseInt((time / 60)) + "分钟前" } else if (time < 60 * 60 * 24) { post.createTime = parseInt((time / 60 / 60)) + "小时前" } else if (time < 60 * 60 * 24 * 30) { post.createTime = parseInt((time / 60 / 60 / 24)) + "天前" } else { if (createTime.getFullYear() == new Date().getFullYear()) { post.createTime = (createTime.getMonth() + 1) + "月" + createTime.getDay() + "日"; } else { post.createTime = createTime.getFullYear() + "年" + (createTime.getMonth() + 1) + "月" + createTime.getDay() + "日"; } } //填入发帖内容到post post.content = res.data.content; post.postId = res.data._id; //通过云开发函数换取图片临时访问地址 wx.cloud.getTempFileURL({ fileList: res.data.images, success: res => { for (let j = 0; j < res.fileList.length; j++) post.images.push(res.fileList[j].tempFileURL) //填入帖子图片url到post }, }) //填入发帖人(本人)openid、昵称、头像 post.openid = app.globalData.openid post.nickname = app.globalData.User[2] post.profile = app.globalData.User[1] post.isMe = true; //获取帖子分类对应名称 sorts.where({ _id: res.data.sortId }).get({ success: function (res) { post.sortName = res.data.name } }) console.log(post) wx.showToast({ icon:'loading', title: '正在加载' }) setTimeout(function(){ let str = JSON.stringify(post) console.log(str) wx.navigateTo({ url: "../postDetails/postDetails?str=" + str }) },500) } }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>// pages/userConsole/userConsole.js const app = getApp() const openid = "0" const db = wx.cloud.database() const notice = db.collection('Notice') //系统通知表 Page({ data: { openid: '', nickname: '', profile: '', navbarData: { title: "个人中心", show: 0, back: 0 }, noRead:false }, onLoad: function (options) { }, onShow: function (options) { var that = this; var count = 0; var load = setInterval(function () { if (count > 50 || typeof (app.globalData.User[2]) != "undefined") { that.setData({ openid: app.globalData.openid, profile: app.globalData.User[1], nickname: app.globalData.User[2], height: (app.globalData.height) * 2 }) count++; clearInterval(load) } }, 100) var that = this notice.where({ openid:app.globalData.openid, isRead:false }).count({ success:function(res){ console.log(res.total) if(res.total > 0){ that.setData({ noRead:true }) }else{ that.setData({ noRead:false }) } } }) }, noticeTap:function(){ wx.navigateTo({ url: "../notice/notice" }) } })
f98a27396ae39383ae2fcf16815a91062c73342f
[ "Markdown", "JavaScript" ]
5
Markdown
evendevil66/tgwsq
7688e0e679e41f66a037f976f1c6b7927dc772f8
872e48e7e96b7edac687b3a63e0d325d322b2ff8
refs/heads/master
<repo_name>Jososke/System_Monitor<file_sep>/ProcessParser.h #include <algorithm> #include <iostream> #include <math.h> #include <thread> #include <chrono> #include <iterator> #include <string> #include <stdlib.h> #include <stdio.h> #include <vector> #include <fstream> #include <sstream> #include <stdexcept> #include <cerrno> #include <cstring> #include <dirent.h> #include <time.h> #include <unistd.h> #include "constants.h" using namespace std; using std::string; class ProcessParser{ private: std::ifstream stream; public: static string getCmd(string pid); static vector<string> getPidList(); static string getVmSize(string pid); static string getCpuPercent(string pid); static long int getSysUpTime(); static string getProcUpTime(string pid); static string getProcUser(string pid); static vector<string> getSysCpuPercent(string coreNumber = ""); static float getSysRamPercent(); static string getSysKernelVersion(); static int getNumberOfCores(); static int getTotalThreads(); static int getTotalNumberOfProcesses(); static int getNumberOfRunningProcesses(); static string getOSName(); static string PrintCpuStats(std::vector<string> values1, std::vector<string>values2); static bool isPidExisting(string pid); }; // Function for breaking the line into a vector of strings by space vector<string>splitByWhiteSpace(string stringToSplit){ istringstream buf(stringToSplit); istream_iterator<string> beg(buf),end; return vector<string>(beg,end); } string ProcessParser::getVmSize(string pid) { string line; //Declaring search attribute for file string name = "VmData"; string value; float result; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + pid + Path::statusPath(), stream); //loop over the lines until name is accesed while(std::getline(stream, line)){ //Seraching line by line if(line.compare(0, name.size(), name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); //conversion kB to gB //The format of this line is "VmData: N”, so the second element (index [1])... //contains the desired memory usage data result = (stof(values[1])/ float(pow(1024,2))); break; } } return to_string(result); } string ProcessParser::getCpuPercent(string pid) { //declaring variables string line; string value; float result; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + pid + "/" + Path::statPath(), stream); getline(stream, line); string str = line; vector<string>values = splitByWhiteSpace(line); float utime = stof(ProcessParser::getProcUpTime(pid)); float stime = stof(values[14]); float cutime = stof(values[15]); float cstime = stof(values[15]); float starttime = stof(values[21]); float uptime = ProcessParser::getSysUpTime(); float freq = sysconf(_SC_CLK_TCK); float total_time = utime + stime + cutime + cstime; // seconds in clock ticks float seconds = uptime - (starttime / freq); //convert cpu clock tick to seconds result = 100.0 * ((total_time / freq) / seconds); return to_string(result); } string ProcessParser::getProcUpTime(string pid) { //declaring variables string line; string value; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + pid + "/" + Path::statPath(), stream); //get the first line of the input stream std::getline(stream, line); //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); //getting the clock ticks of the host machine to get the process up time return to_string(float(stof(values[13]) / sysconf(_SC_CLK_TCK))); } long int ProcessParser::getSysUpTime() { //declaring variables string line; string value; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + Path::upTimePath(), stream); //get the first line of the input stream std::getline(stream, line); //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); //getting the system up time value from the vector return stoi(values[0]); } string ProcessParser::getProcUser( string pid) { //declaring variables string line; string value; string result; string name = "Uid:"; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + pid + Path::statusPath(), stream); //loop over the lines until name is accesed while(std::getline(stream, line)){ //Seraching line by line if(line.compare(0, name.size(), name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); //first value from Uid result = values[1]; break; } } // closing stream for specific file stream.close(); // Fill stream with a valid stream Util::getStream("/etc/passwd", stream); string name2 = ("x:" + result); //loop over the lines until name is accesed while (std::getline(stream, line)) { if (line.find(name2) != std::string::npos) { result = line.substr(0, line.find(":")); return result; } } return ""; } vector<string> ProcessParser::getPidList() { DIR* dir; // Basically, we are scanning /proc dir for all directories with numbers as their names // If we get valid check we store dir names in vector as list of machine pids vector<string> container; if(!(dir = opendir("/proc"))) throw std::runtime_error(std::strerror(errno)); while (dirent* dirp = readdir(dir)) { // is this a directory? if(dirp->d_type != DT_DIR) continue; // Is every character of the name a digit? if (all_of(dirp->d_name, dirp->d_name + std::strlen(dirp->d_name), [](char c){ return std::isdigit(c); })) { container.push_back(dirp->d_name); } } //Validating process of directory closing if(closedir(dir)) throw std::runtime_error(std::strerror(errno)); return container; } string ProcessParser::getCmd(string pid) { string line; std::ifstream stream; Util::getStream(Path::basePath() + pid + Path::cmdPath(), stream); std::getline(stream, line); return line; } int ProcessParser::getNumberOfCores() { // Get the number of host cpu cores string line; string name = "cpu cores"; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + "cpuinfo", stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); return stoi(values[3]); } } return 0; } vector<string> ProcessParser::getSysCpuPercent(string coreNumber) { // Get the number of host cpu cores string line; string name = "cpu" + coreNumber; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + Path::statPath(), stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); return values; } } return (vector<string>()); } float getSysActiveCpuTime(vector<string> values) { // Add the active CPU time for getSysCpuPercent output return (stof(values[S_USER]) + stof(values[S_NICE]) + stof(values[S_SYSTEM]) + stof(values[S_IRQ]) + stof(values[S_SOFTIRQ]) + stof(values[S_STEAL]) + stof(values[S_GUEST]) + stof(values[S_GUEST_NICE])); } float getSysIdleCpuTime(vector<string> values) { // Adding the idle time from getSysCpuPercent output return (stof(values[S_IDLE]) + stof(values[S_IOWAIT])); } string ProcessParser::PrintCpuStats(vector<string> values1, vector<string> values2) { /* Because CPU stats can be calculated only if you take measures in two different time, this function has two parameters: two vectors of relevant values. We use a formula to calculate overall activity of processor. */ float activeTime = getSysActiveCpuTime(values2) - getSysActiveCpuTime(values1); float idleTime = getSysIdleCpuTime(values2) - getSysIdleCpuTime(values1); float totalTime = activeTime + idleTime; float result = 100.0*(activeTime / totalTime); return to_string(result); } float ProcessParser::getSysRamPercent() { string line; string name1 = "MemAvailable:"; string name2 = "MemFree:"; string name3 = "Buffers:"; string value; int result; // Opening stream for specific file // Fill stream with a valid stream std::ifstream stream; Util::getStream(Path::basePath() + Path::memInfoPath(), stream); float total_mem = 0; float free_mem = 0; float buffers = 0; while (std::getline(stream, line)) { if (total_mem != 0 && free_mem != 0) break; if (line.compare(0, name1.size(), name1) == 0) { vector<string>values = splitByWhiteSpace(line); total_mem = stof(values[1]); } if (line.compare(0, name2.size(), name2) == 0) { vector<string>values = splitByWhiteSpace(line); free_mem = stof(values[1]); } if (line.compare(0, name3.size(), name3) == 0) { vector<string>values = splitByWhiteSpace(line); buffers = stof(values[1]); } } //calculating usage: return float(100.0*(1-(free_mem/(total_mem-buffers)))); } string ProcessParser::getSysKernelVersion() { string line; string name = "Linux version "; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + Path::versionPath(), stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); return values[2]; } } } string ProcessParser::getOSName() { // Get the number of host cpu cores string line; string name = "PRETTY_NAME="; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream("/etc/os-release", stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { std::size_t found = line.find("="); found++; string result = line.substr(found); result.erase(std::remove(result.begin(), result.end(), '"'), result.end()); return result; } } } int ProcessParser::getTotalThreads() { string line; string name = "Threads:"; vector<string> list_of_threads = ProcessParser::getPidList(); int total_thread = 0; //looping through the number of threads for (int i = 0; i<list_of_threads.size(); i++) { // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + list_of_threads[i] + Path::statusPath(), stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); total_thread += stoi(values[1]); break; } } } return total_thread; } int ProcessParser::getTotalNumberOfProcesses() { string line; string name = "processes"; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + Path::statPath(), stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); return stoi(values[1]); } } } int ProcessParser::getNumberOfRunningProcesses() { string line; string name = "procs_running"; // Opening stream for specific file std::ifstream stream; // Fill stream with a valid stream Util::getStream(Path::basePath() + Path::statPath(), stream); //loop over the lines until name is accesed while (std::getline(stream, line)) { //Seraching line by line if (line.compare(0, name.size(),name) == 0) { //slices the string based on white space and stores in vector<string> values vector<string>values = splitByWhiteSpace(line); return stoi(values[1]); } } } bool ProcessParser::isPidExisting(std::string pid) { for(auto& valid_pid : ProcessParser::getPidList()) { if(valid_pid.compare(pid) == 0) return true; } return false; }
668534f0374044fef400bb2133e78eda450f73b7
[ "C++" ]
1
C++
Jososke/System_Monitor
9113518a4940d0ebaf455aea3103f6ab895a994e
d50aafebe9738d4ed913ea365699d9c2ac098607
refs/heads/main
<repo_name>bjwmills/SCION<file_sep>/README.md # SCION ## Spatial Continuous Integration - Earth Evolution Model ### Current version v1.1.6 - March 2023 SCION is a global climate-biogeochemical model that runs over geological timescales. It runs forwards in time and computes the Earth’s major elemental cycles and surface climate. It also predicts the values of a suite of geochemical tracers to aid in hypothesis testing. Requies MATLAB. For more information on model derivation and running the model, see the Guidebook in the documentation folder. This code is free to use. The model is under continual revision/extension by my research group and collaborators. For any queries or collaboration ideas please email <EMAIL> <file_sep>/SCION_shell.sh # Run with current environment #$ -V # Set a time limit #$ -l h_rt=48:00:00 #Request some memory per core #$ -l h_vmem=1G # Ask for lots of smp cores (insert $ after # to comment this in) #$ -pe smp 40 #Get email at start and end of the job #$ -m be # Load matlab module module add matlab # run matlab using command file # -nodisplay flag should be given to suppress graphics matlab -nodisplay < SCION_sens.m
1359c525b12b350a7ff135f26cff7bbcc05e9a10
[ "Markdown", "Shell" ]
2
Markdown
bjwmills/SCION
2049be3cd1a40704f220fb48bf42fca73a8d3b16
55f0b515b12e1b6023a92a7ba60f540035e02ca6
refs/heads/master
<file_sep>using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Service.Abstract { public interface ITedarikciService { List<Tedarikci> GetAll(); void Add(Tedarikci tedarikci); void Update(Tedarikci tedarikciId); void Delete(int tedarikciId); Tedarikci GetById(int tedarikciId); } } <file_sep>using Emir.Service.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Emir.Entities.Concrete; using Emir.Dal.Abstract; namespace Emir.Service.Concrete { public class TedarikciManager : ITedarikciService { private ITedarikciDal _tedarikciDal; public TedarikciManager(ITedarikciDal tedarikciDal) { _tedarikciDal = tedarikciDal; } public void Add(Tedarikci tedarikci) { _tedarikciDal.Add(tedarikci); } public void Delete(int tedarikciId) { _tedarikciDal.Delete(new Tedarikci { TedarikciId = tedarikciId }); } public List<Tedarikci> GetAll() { return _tedarikciDal.GetList(); } public Tedarikci GetById(int tedarikciId) { return _tedarikciDal.Get(x => x.TedarikciId == tedarikciId); } public void Update(Tedarikci tedarikciId) { _tedarikciDal.Update(tedarikciId); } } } <file_sep>using Emir.Core.CoreEntityFramework; using Emir.Dal.Abstract; using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Dal.EntityFramework { public class EfKategoryDal: EfEntityRepositoryBase<Kategori, EFDatabaseContext>, IKategoriDal { } } <file_sep>using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Service.Abstract { public interface IKullaniciService { List<Kullanici> GetAll(); void Add(Kullanici kullanici); void Update(Kullanici kullanici); void Delete(int kullaniciId); Kullanici GetById(int kullaniciId); } } <file_sep>using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Dal.EntityFramework { public class EFDatabaseContext : DbContext { public EFDatabaseContext() : base(@"Data Source=.;Database=NORTHWND;User ID=sa;Password=123;") { } public DbSet<Urun> Urunler { get; set; } public DbSet<Kategori> Kategoriler { get; set; } public DbSet<Kullanici> Kullanicilar { get; set; } public DbSet<Tedarikci> Tedarikciler { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } } <file_sep>using Emir.Core.CoreEntityFramework; using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Dal.Abstract { public interface IUrunDal:IEntityRepository<Urun> { } } <file_sep>using Emir.Core; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Entities.Concrete { [Table("Kategoriler")] public class Kategori : IEntity { [Key] public int KategoriId { get; set; } public DateTime CreatedDate { get; set; } public bool IsActive { get; set; } [Required(ErrorMessage ="Gerekli alan"),StringLength(50)] public string Adi { get; set; } [Required(ErrorMessage = "Gerekli alan"), StringLength(150)] public string Aciklamasi { get; set; } public virtual List<Urun> Urunler { get; set; } } } <file_sep>using Emir.Core; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Entities.Concrete { [Table("Kullanicilar")] public class Kullanici : IEntity { [Key] public int KullaniciId { get; set; } public DateTime CreatedDate { get; set; } public bool IsActive { get; set; } [Required(ErrorMessage ="Gerekli Alan"),StringLength(30)] public string Ad { get; set; } [Required(ErrorMessage = "Gerekli Alan"), StringLength(30)] public string Soyad { get; set; } [Required(ErrorMessage = "Gerekli Alan")] [DataType(DataType.EmailAddress), StringLength(30)] public string Email { get; set; } [Required(ErrorMessage = "Gerekli Alan")] [DataType(DataType.Password), StringLength(30)] public string Password { get; set; } [Required(ErrorMessage ="Gerekli Alan"), StringLength(30)] public string KullaniciAdi { get; set; } } } <file_sep>using Emir.Service.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Emir.Entities.Concrete; using Emir.Dal.Abstract; namespace Emir.Service.Concrete { public class KategoriManager : IKategoriService { private IKategoriDal _kategoryDal; public KategoriManager(IKategoriDal kategoriDal) { _kategoryDal = kategoriDal; } public void Add(Kategori kategori) { _kategoryDal.Add(kategori); } public void Delete(int kategoriId) { _kategoryDal.Delete(new Kategori { KategoriId = kategoriId }); } public List<Kategori> GetAll() { return _kategoryDal.GetList(); } public Kategori GetById(int kategoriId) { return _kategoryDal.Get(x => x.KategoriId == kategoriId); } public void Update(Kategori kategori) { _kategoryDal.Update(kategori); } } } <file_sep>using Emir.Core; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Emir.Entities.Concrete { [Table("Tedarikciler")] public class Tedarikci : IEntity { [Key] public int TedarikciId { get; set; } public DateTime CreatedDate { get; set; } public bool IsActive { get; set; } [Required(ErrorMessage = "Gerekli alan"), StringLength(40)] public string TedarikciAdi { get; set; } [Required(ErrorMessage = "Gerekli alan"), StringLength(40)] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Required(ErrorMessage = "Gerekli alan"), StringLength(240)] public string Adres { get; set; } public virtual List<Urun> Urunler { get; set; } } }<file_sep>using Emir.Core; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Entities.Concrete { [Table("Urunler")] public class Urun : IEntity { [Key] public int UrunId { get; set; } public DateTime CreatedDate { get; set; } public bool IsActive { get; set; } [Required(ErrorMessage ="Gerekli alan"),StringLength(40)] public string UrunAdi { get; set; } [Required(ErrorMessage = "Gerekli alan"), StringLength(40)] public string UrunAciklama { get; set; } [Required(ErrorMessage = "Gerekli alan")] public decimal Fiyat { get; set; } [Required(ErrorMessage = "Gerekli alan")] public short Stok { get; set; } public int KategoriId { get; set; } public virtual List<Tedarikci> Tedarikci { get; set; } } } <file_sep>using Emir.Service.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Emir.Entities.Concrete; using Emir.Dal.Abstract; namespace Emir.Service.Concrete { public class KullaniciManager : IKullaniciService { private IKullaniciDal _kullaniciDal; public KullaniciManager(IKullaniciDal kullaniciDal) { _kullaniciDal = kullaniciDal; } public void Add(Kullanici kullanici) { _kullaniciDal.Add(kullanici); } public void Delete(int kullaniciId) { _kullaniciDal.Delete(new Kullanici { KullaniciId = kullaniciId }); } public List<Kullanici> GetAll() { return _kullaniciDal.GetList(); } public Kullanici GetById(int kullaniciId) { return _kullaniciDal.Get(x => x.KullaniciId == kullaniciId && x.IsActive==true); } public void Update(Kullanici kullanici) { _kullaniciDal.Update(kullanici); } } } <file_sep>using Emir.Core.CoreEntityFramework; using Emir.Dal.Abstract; using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Dal.EntityFramework { public class EfTedatikciDal : EfEntityRepositoryBase<Tedarikci, EFDatabaseContext>, ITedarikciDal { } } <file_sep>using Emir.Service.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Emir.Entities.Concrete; using Emir.Dal.Abstract; namespace Emir.Service.Concrete { public class UrunManager : IUrunService { private IUrunDal _uruntDal; public UrunManager(IUrunDal uruntDal) { _uruntDal = uruntDal; } public void Add(Urun urun) { _uruntDal.Add(urun); } public void Delete(int urunId) { _uruntDal.Delete(new Urun { UrunId = urunId }); } public List<Urun> GetAll() { return _uruntDal.GetList(); } public List<Urun> GetByCategory(int kategoryId) { return _uruntDal.GetList(x => x.KategoriId == kategoryId); } public Urun GetById(int urunId) { return _uruntDal.Get(x => x.UrunId == urunId); } public void Update(Urun urun) { _uruntDal.Update(urun); } } } <file_sep>using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Service.Abstract { public interface IKategoriService { List<Kategori> GetAll(); void Add(Kategori kategori); void Update(Kategori kategori); void Delete(int kategoriId); Kategori GetById(int kategoriId); } } <file_sep>using Emir.Core.CoreEntityFramework; using Emir.Dal.Abstract; using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Dal.EntityFramework { public class EfKullaniciDal : EfEntityRepositoryBase<Kullanici, EFDatabaseContext>, IKullaniciDal { } } <file_sep>using Emir.Core.CoreEntityFramework; using Emir.Dal.Abstract; using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Dal.EntityFramework { public class EfUrunDal : EfEntityRepositoryBase<Urun, EFDatabaseContext>,IUrunDal { } } <file_sep>using Emir.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Service.Abstract { public interface IUrunService { List<Urun> GetAll(); List<Urun> GetByCategory(int kategoryId); void Add(Urun urun); void Update(Urun urun); void Delete(int urunId); Urun GetById(int urunId); } } <file_sep># MyStructure more info soon ##<NAME> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Emir.Core { public interface IEntity { } }
43c3ca804e6061b24ed6fd9097aaafc8c8a2fdd3
[ "Markdown", "C#" ]
20
C#
EmirHazir/MyStructure
fc2b348170cf0b24a16927681dd8f63e88d85191
72f84856f764d3a9a78878f55c12082402645838
refs/heads/master
<repo_name>add1ct3d/fundManageR<file_sep>/R/econmagic.R function(url = "http://www.economagic.com/em-cgi/data.exe/treas/pubdebt#Data") { page <- url %>% read_html() raw_data <- page %>% html_nodes('pre') %>% html_text() raw_data <- raw_data %>% stringr::str_split('\n') %>% flatten_chr() %>% str_trim() %>% { .[!. %in% c('')] } data <- raw_data[raw_data %>% str_detect("^[0-9]")] raw_data <- raw_data[raw_data %>% nchar() > 10] page %>% html_nodes("font+ font") %>% html_text() tibble(data) } <file_sep>/R/venture_data_functions.R # ycombinator ------------------------------------------------------------- #' Y Combinator data #' #' This function returns information on #' Y Combinator alumni and active particpants. #' #' @param return_message \code{TRUE} return a message after data import #' includes information about a random YC company #' @param nest_data \code{TRUE} return nested data frame #' @references \href{https://www.ycombinator.com/}{YCombinator} #' @return where \code{nest_data} is \code{TRUE} a nested tibble by batch, #' where \code{nest_data} is \code{FALSE} a tibble #' @export #' @import stringr dplyr readr #' @importFrom jsonlite fromJSON #' @family venture capital #' @family entity search #' @examples #' ycombinator_alumni(nest_data = FALSE) ycombinator_alumni <- function(nest_data = FALSE, return_message = TRUE) { data <- "https://api.ycombinator.com/companies/export.json" %>% fromJSON(simplifyDataFrame = T, flatten = T) %>% as_tibble() %>% set_names( c( 'nameCompany', 'urlCompany', 'batchYC', 'verticalCompany', 'descriptionCompany', 'isDeadCompany', "hasFF", "hasFFAll" ) ) data <- data %>% mutate(yearYC = batchYC %>% readr::parse_number(), idSeasonYC = batchYC %>% substr(1, 1),) %>% mutate_if(is.character, funs(ifelse(. == "", NA, .))) %>% left_join(tibble( idSeasonYC = c('w', 's'), nameSeasonYC = c('Winter', 'Summer') )) %>% mutate( description = descriptionCompany %>% str_to_upper(), isAcquiredCompany = description %>% str_detect("ACQUIRED|WE SOLD|SOLD TO") ) %>% dplyr::select(-description) %>% dplyr::select(-idSeasonYC) %>% dplyr::select( nameCompany, isDeadCompany, isAcquiredCompany, batchYC, yearYC, nameSeasonYC, everything() ) %>% suppressMessages() %>% arrange(desc(yearYC), nameSeasonYC) data <- data %>% mutate_at(data %>% dplyr::select(dplyr::matches("name")) %>% names(), funs(. %>% str_to_upper())) %>% mutate_at(.vars = "urlCompany", funs(ifelse(. == '', NA, .))) %>% mutate_if(is.character, str_trim) if (return_message) { random_company <- data %>% dplyr::filter(!descriptionCompany %>% is.na) %>% sample_n(1) random_company_message <- '\nCheckout ' %>% paste0( random_company$nameCompany, ' from ', random_company$nameSeasonYC, ' ', random_company$yearYC, '\nThey describe themselves as:\n', random_company$descriptionCompany, '\nTheir website is ', random_company$urlCompany ) "You returned " %>% paste0( data %>% nrow() %>% formattable::comma(digits = 0), ' YCombinator Companies from ', data$yearYC %>% min(), ' to ', data$yearYC %>% max(), random_company_message ) %>% cat(fill = T) } if (nest_data) { data <- data %>% nest(-batchYC, .key = dataClass) } gc() data } # cbinsights -------------------------------------------------------------- #' CB Insight data #' #' This function returns information about startups whose valuation #' exceeds $1B as identified by CB Insights. #' #' @param return_message \code{TRUE} return a message after data import #' @return \code{tibble} #' @references \href{https://cbinsights/}{CB Insights} #' @export #' @import dplyr rvest formattable stringr purrr #' @importFrom readr parse_number #' @family venture capital #' @examples #' cb_unicorns(return_message = TRUE) cb_unicorns <- function(return_message = TRUE) { page <- "https://www.cbinsights.com/research-unicorn-companies" %>% read_html() companies <- page %>% html_nodes('td:nth-child(1)') %>% html_text() %>% stringr::str_replace('\n\t','') %>% gsub("^ *|(?<= ) | *$", "", ., perl = TRUE) company_urls <- page %>% html_nodes('td:nth-child(1) a') %>% html_attr('href') %>% str_replace_all('https://www.cbinsights.com/company/https://www.cbinsights.com/company/', 'https://www.cbinsights.com/company/') valuation_billions <- page %>% html_nodes('td:nth-child(2)') %>% html_text() %>% readr::parse_number() %>% formattable::currency(digits = 2) date_joined <- page %>% html_nodes('td:nth-child(3)') %>% html_text() %>% lubridate::mdy() country <- page %>% html_nodes('td:nth-child(4)') %>% html_text() industry <- page %>% html_nodes('td:nth-child(5)') %>% html_text() investors <- page %>% html_nodes('td:nth-child(6)') %>% html_text() unicorn_df <- tibble( nameCompany = companies %>% stringr::str_to_upper(), amountValuationBillions = valuation_billions, dateJoined = date_joined, countryCompany = country %>% stringr::str_to_upper(), nameIndustry = industry %>% stringr::str_to_upper(), nameInvestors = investors %>% stringr::str_to_upper(), urlCompanyCBInsights = company_urls ) if (return_message) { list("You acquired data on ", unicorn_df %>% nrow() %>% formattable::comma(digits = 0), ' unicorns with a total private market valuation of $', unicorn_df$amountValuationBillions %>% sum %>% formattable::currency(), ' Billion') %>% cat(fill = T) } return(unicorn_df) }<file_sep>/R/government_data.R dictionary_fdic_names <- function() { tibble(nameFDIC = c("STNAME", "CERT", "DOCKET", "ACTIVE", "ADDRESS", "ASSET", "BKCLASS", "CHANGEC1", "CHANGEC2", "CHANGEC3", "CHANGEC4", "CHANGEC5", "CHARTER", "CHRTAGNT", "CONSERVE", "CITY", "CLCODE", "CMSA_NO", "CMSA", "COUNTY", "DATEUPDT", "DENOVO", "DEP", "EFFDATE", "ENDEFYMD", "EQ", "ESTYMD", "FDICDBS", "FDICREGN", "FDICSUPV", "FED", "FED_RSSD", "FEDCHRTR", "FLDOFF", "IBA", "INACTIVE", "INSAGNT1", "INSAGNT2", "INSDATE", "INSTCRCD", "INSBIF", "INSCOML", "INSDIF", "INSFDIC", "INSSAIF", "INSSAVE", "MSA_NO", "MSA", "NAME", "NEWCERT", "OAKAR", "OTSDIST", "OTSREGNM", "PROCDATE", "QBPRCOML", "REGAGNT", "REPDTE", "RISDATE", "STCHRTR", "ROA", "ROAQ", "ROE", "ROEQ", "RUNDATE", "SASSER", "LAW_SASSER_FLG", "STALP", "STCNTY", "STNUM", "ZIP", "SUPRV_FD", "OCCDIST", "UNINUM", "ULTCERT", "CFPBEFFDTE", "CFPBENDDTE", "CFPBFLAG", "REGAGENT2", "TE01N528", "TE02N528", "TE03N528", "TE04N528", "TE05N528", "TE06N528", "TE07N528", "TE08N528", "TE09N528", "TE10N528", "TE01N529", "TE02N529", "TE03N529", "TE04N529", "TE05N529", "TE06N529", "WEBADDR", "OFFICES", "CERTCONS", "PARCERT", "CITYHCR", "DEPDOM", "FORM31", "HCTMULT", "INSTAG", "MUTUAL", "NAMEHCR", "NETINC", "NETINCQ", "OFFDOM", "OFFFOR", "OFFOA", "RSSDHCR", "STALPHCR", "STMULT", "SUBCHAPS", "ROAPTX", "ROAPTXQ", "TRUST", "SPECGRP", "SPECGRPN", "TRACT", "CSA", "CSA_NO", "CSA_FLG", "CBSA", "CBSA_NO", "CBSA_METRO_NAME", "CBSA_METRO", "CBSA_METRO_FLG", "CBSA_MICRO_FLG", "CBSA_DIV", "CBSA_DIV_NO", "CBSA_DIV_FLG", "CB"), nameActual = c("nameState", "idCertificate", "idDocket", "isActiveBank", "addressStreet", "amountAssetsMillions", "classCharterFDIC", "codeChange1", "codeChange2", "codeChange3", "codeChange4", "codeChange5", "idCharter", "agencyCharter", "isConservatorship", "city", "idCLCode", "idCMSA", "nameCMSA", "county", "dateUpdated", "isDenovo", "amountDepositsMillions", "dateChangeMostRecent", "dateLastEvent", "amountEquityMillions", "dateEstablished", "idFDICRegion", "nameFDICRegion", "nameFDICSupervisor", "idFederalReserveRegion", "idFederalReserve", "hasFedCharter", "idFDICFieldOffice", "isInsuredForeignBankOffice", "isInactive", "codeInsuranceFundMembership", "codeInsuranceFundMembership2", "dateDepositInsurance", "isCreditCardIssuer", "isBankInsuranceFund", "idInsuredCommercialBank", "isDepositFundMember", "isFDICInsured", "isSAAMember", "isSAIFInsured", "idMSA", "nameMSA", "nameInstitution", "idNewCertification", "isOakarInstitution", "idOTS", "nameOTSRegion", "dateLastProcessChange", "idQuarterlyBankingProfile", "codeRegulator", "dateReportingLast", "dateReport", "hasStateCharter", "pctReturnOnAssets", "pctReturnOnAssetsQuarter", "pctReturnOnEquity", "pctReturnOnEquityQuarter", "dateInformationUpdated", "isSasserInstitution", "hasSasserFlag", "codeStateHeadQuarters", "idFIPSHeadQuarters", "idFIPSStateHeadQuarters", "zipcodeHeadQUarters", "idFDICSupervisory", "idOCCSupervisory", "idFDIC", "idCertificatePurchaser", "dateCPFBSecondarySupervision", "dateCPFBSecondarySupervisionEnd", "hasCPFBSUpervision", "remove", "urlDepositTaker", "urlDepositTaker2", "urlDepositTaker3", "urlDepositTaker4", "urlDepositTaker5", "urlDepositTaker6", "urlDepositTaker7", "urlDepositTaker8", "urlDepositTaker9", "urlDepositTaker10", "nameTradeInstitution", "nameTradeInstitution1", "nameTradeInstitution2", "nameTradeInstitution3", "nameTradeInstitution4", "nameTradeInstitution5", "urlInstitution", "countOffices", "countBanksOwned", "countSubsidiaries", "cityHeadQuarters", "amountDepositsDomesticMillions", "isForm31Filer", "isMultiBankHolingCompany", "isAgriculturalLendingInstitution", "isMutualOwned", "nameBankHoldingCompany", "amountNetIncomeMillions", "amountNetIncomeMillionsQuarter", "OFFDOM", "countOfficesDomestic", "countOfficesUSA", "idFederalReserveHoldingParent", "stateHeadQuarters", "isInterstateBank", "isSubChapterS", "pctPreTaxReturnOnAsset", "pctPreTaxReturnOnAssetQuarter", "hasTrustPowers", "idAssetTotalCode", "typeAssetCode", "hasTractPowers", "nameCSA", "idCSA", "hasCSAFlag", "nameCBSA", "idCBSA", "nameCBSA2", "idCBSAMetro", "hasCBSA", "hasCBSAMicroFlag", "nameCBSADiv", "idCBSADiv", "hasCBSADiv", "isCommunityBank") ) } .assign_fdic_names <- function(data) { fdic_names <- names(data) df_gov_names <- dictionary_fdic_names() all_names <- fdic_names %>% map_chr(function(fdic_name) { no_name <- df_gov_names %>% filter(fdic_name == nameFDIC) %>% nrow() == 0 if (no_name) { glue::glue("Missing {fdic_name} in dictionary") %>% message() return(UNINUM) } df_gov_names %>% filter(nameFDIC == fdic_name) %>% pull(nameActual) %>% unique() %>% .[[1]] }) data %>% set_names(all_names) } .munge_fdic <- function(data) { is_has <- data %>% dplyr::select(dplyr::matches("^is|^has")) %>% names() data <- data %>% mutate_at(is_has, list(function(x) { x %>% as.character() %>% str_replace_all("Y", "1") %>% str_replace_all("N", "0") %>% as.numeric() %>% as.logical() })) date_cp <- data %>% dplyr::select(dplyr::matches("dateCPFB")) %>% names() data <- data %>% mutate_at(date_cp, list(function(x){ x %>% str_replace_all("9999", "1999") %>% dmy() })) data <- data %>% mutate_if(is.numeric, list(function(x) { ifelse(x == 0, NA_real_, x) })) websites <- data %>% dplyr::select(dplyr::matches("url")) %>% names() data <- data %>% mutate_at(websites, list(function(x) { x %>% str_remove_all("\\http://|\\https://|https://|http://") %>% str_to_lower() })) %>% mutate_at(websites, list(function(x) { str_c("https://", x) })) %>% mutate_at(websites, list(function(x) { ifelse(x == "https://0", NA_character_, x) })) amount_cols <- data %>% dplyr::select(dplyr::matches("amount")) %>% names() data <- data %>% mutate_at(amount_cols, list(function(x){ x %>% formattable::currency(digits = 0) })) pct_cols <- data %>% dplyr::select(dplyr::matches("pct")) %>% names() data <- data %>% mutate_at(pct_cols, list(function(x){ (as.numeric(x) / 100 ) })) %>% mutate_at(pct_cols, list(function(x){ x %>% percent(digits = 2) })) count_cols <- data %>% dplyr::select(dplyr::matches("^count[A-Z]")) %>% dplyr::select(-dplyr::matches("county")) %>% names() data <- data %>% mutate_at(count_cols, list(function(x){ comma(x, digits = 0) })) data <- data %>% mutate_if(is.character, list(function(x){ ifelse(x == "0", NA_character_, x) }) ) data <- data %>% mutate_at( data %>% select_if(is.character) %>% dplyr::select(-dplyr::matches("url")) %>% names(), str_to_upper ) data %>% dplyr::select( idFDIC, idFederalReserve, nameBankHoldingCompany, nameTradeInstitution, urlInstitution, dplyr::matches("amount|pct"), everything() ) data } #' United States Bank #' #' @return #' @export #' #' @examples us_banks <- function() { data <- "https://cg-8f5302ff-11ad-4d26-a9b9-7c7ebcd6f322.s3-us-gov-west-1.amazonaws.com/downloads/institutions.csv" %>% read_csv() %>% .assign_fdic_names() data }<file_sep>/R/markit.R .extract_date_time <- function(x = "Mon Nov 12 10:42:35 UTC-05:00 2018") { total_chars <- x %>% nchar() year_time <- x %>% substr(total_chars -3 , total_chars) non_year <- x %>% substr(1, total_chars -4) %>% str_trim() %>% str_split("\\ UTC") %>% flatten_chr() %>% .[[1]] md <- non_year %>% substr(4, nchar(non_year)) %>% str_trim() x <- glue::glue("{year_time} {md}") %>% lubridate::ymd_hms() x } .get_data_ticker_trade <- function(ticker = "bxp" , return_message = TRUE) { json_url <- stringr::str_c('http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=', ticker) json_data <- json_url %>% jsonlite::fromJSON() if ("Message" %in% names(json_data)) { stop(str_c("No MARKIT ticker data for ", ticker)) } df_ticker <- json_data %>% flatten_df() %>% purrr::set_names( c( 'statusSearch', 'nameCompany', 'idTicker', 'priceLast', 'priceChange', 'pctChange', 'datetimeTradeLast', 'dateMS', 'amountMarketCapitalization', 'countVolumeShares', 'priceYearStart', 'pctChangeYTD', 'priceHigh', 'priceLow', 'priceOpen' ) ) %>% dplyr::select(-c(dateMS, statusSearch)) %>% mutate(datetimeTradeLast = datetimeTradeLast %>% str_replace_all(" UTC-04:00 ", ' ')) date_time_price <- df_ticker$datetimeTradeLast %>% .extract_date_time() df_ticker <- df_ticker %>% mutate(datetimeTradeLast = date_time_price) %>% mutate(countSharesOutstanding = amountMarketCapitalization / priceLast) %>% select(datetimeTradeLast, everything()) if (return_message) { glue::glue("Parsed trades for {str_to_upper(ticker)}") %>% cat(fill = T) } df_ticker } #' Tickers trades #' #' @param tickers #' @param return_message #' #' @return #' @export #' @import dplyr curl jsonlite stringr dplyr purrr lubridate #' #' @examples #' tickers_trades(tickers = c("VNO", "BXP", "FB")) #' tickers_trades <- function(tickers = c("PEI","bxp") , return_message = TRUE) { .get_data_ticker_trade_safe <- purrr::possibly(.get_data_ticker_trade, tibble()) all_data <- tickers %>% future_map_dfr(function(x){ .get_data_ticker_trade_safe(ticker = x, return_message = return_message) }) all_data <- all_data %>% mutate_at(all_data %>% dplyr::select(dplyr::matches("^price")) %>% names(), funs(. %>% formattable::currency(digits = 2))) %>% mutate_at(all_data %>% dplyr::select(dplyr::matches("^pct")) %>% names(), funs((. / 100) %>% formattable::percent(digits = 3))) %>% mutate_at(all_data %>% dplyr::select(dplyr::matches("^count")) %>% names(), funs(. %>% formattable::comma(digits = 0))) %>% mutate_at(all_data %>% dplyr::select(dplyr::matches("^amount")) %>% names(), funs(. %>% formattable::currency(digits = 0))) %>% mutate( priceYearStart = priceLast / (1 + pctChangeYTD) , amountMarketCapitalizationYearStart = amountMarketCapitalization / (1 + pctChangeYTD) ) %>% dplyr::select(datetimeTradeLast, everything()) %>% suppressWarnings() return(all_data) } .companies_tickers <- function(company = "Netflix", return_message = TRUE) { json_url <- stringr::str_c("http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=", company) data <- json_url %>% jsonlite::fromJSON() %>% data.frame(stringsAsFactors = FALSE) %>% as_tibble() %>% purrr::set_names(c('idTicker', 'nameCompany', 'nameExchange')) %>% mutate(nameCompanySearch = company) %>% dplyr::select(nameCompanySearch, everything()) if (return_message) { list("Found ", nrow(data) %>% formattable::comma(digits = 0), ' ticker(s) matching ', company) %>% purrr::reduce(paste0) %>% cat(fill = T) } return(data) } #' Companies ticker symbols #' #' Company ticker data #' #' @param companies vector of comapnies #' @param include_trades if \code{TRUE} includes trade data #' @references \href{http://markit.com}{MARKIT} #' @return a \code{date_frame} #' @export #' @import dplyr curl jsonlite stringr dplyr purrr lubridate #' @examples companies_tickers <- function(companies = c("Vornado", "Snap"), include_trades = TRUE, return_message = TRUE) { .companies_tickers_safe <- purrr::possibly(.companies_tickers, tibble()) all_data <- companies %>% future_map_dfr(function(x) { .companies_tickers_safe(company = x) }) if (include_trades) { tickers <- all_data$idTicker %>% unique() tickers_trades_safe <- purrr::possibly(tickers_trades, tibble()) df_trades <- tickers %>% tickers_trades(return_message = return_message) %>% suppressMessages() all_data <- all_data %>% left_join(df_trades) %>% suppressMessages() } return(all_data) } # ocr --------------------------------------------------------------------- function(url = "http://www.markit.com/Company/Files/DownloadFiles?CMSID=f8c7fb31019e421a8b5d3d0a9980211c") { }
3c847095bebdb93180bbac69ab78088da9695524
[ "R" ]
4
R
add1ct3d/fundManageR
5402f2020853a40cf16627626aa5f4cbcb87c521
8136f541af3ddacd2719836dae7159ca32b2a59f
refs/heads/master
<file_sep>function getRandomNum(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) } export function shuffle(arr) { let _arr = arr.slice() for (let i = 0; i < _arr.length; i++) { let r = getRandomNum(0, i) let t = _arr[i] _arr[i] = _arr[r] _arr[r] = t } return _arr } // 搜索节流 高阶函数 export function debounce(func, delay) { let timer return function (...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, delay) } }<file_sep>import storage from 'good-storage' const SEARCH_KEY = '__search__' const SEARCH_MAX_LENGTH = 15 const PLAY_KEY = '__play__' const PLAY_MAX_LENGTH = 200 const FAVORITE_KEY = '__favorite__' const FAVORITE_MAX_LENGTH = 200 // 插入搜索历史到数组 function insertArray(arr, val, compare, maxLen) { const index = arr.findIndex(compare) // 如果搜索历史恰好第一位 不需要处理 if (index === 0) { return } // 如果列表中有记录且不在第一位 则先删除 if (index > 0) { arr.splice(index, 1) } // 将记录放在列表首位 arr.unshift(val) // 如果列表输超过最大存储容量 则将后面的数据删除 if (maxLen && arr.length > maxLen) { arr.pop() } } export function saveSearch(query) { // 从localStorage中拿到search列表 没有则返回空数组 let searches = storage.get(SEARCH_KEY, []) // 插入记录到列表 insertArray(searches, query, (item) => { return item === query }, SEARCH_MAX_LENGTH) // 将记录保存到localStorage storage.set(SEARCH_KEY, searches) return searches } export function loadSearch() { return storage.get(SEARCH_KEY, []) } function deleteFromArray(arr, compare) { let index = arr.findIndex(compare) if (index > -1) { arr.splice(index, 1) } } export function deleteSearch(oneItem) { let searches = storage.get(SEARCH_KEY, []) deleteFromArray(searches, (item) => { return item === oneItem }) storage.set(SEARCH_KEY, searches) return searches } export function clearSearch() { storage.remove(SEARCH_KEY) return [] } // 存储播放记录 export function savePlay(song) { // 从缓存中读取play列表 没有则返回空数组 let play = storage.get(PLAY_KEY, []) // 将song插入到play列表 insertArray(play, song, (item) => { return item.id === song.id }, PLAY_MAX_LENGTH) // 将play存入缓存 storage.set(PLAY_KEY, play) return play } // 读取播放记录 export function loadPlay() { return storage.get(PLAY_KEY, []) } // 将歌曲保存到收藏列表 export function saveFavorite(song) { let favorites = storage.get(FAVORITE_KEY, []) insertArray(favorites, song, (item) => { return item.id === song.id }, FAVORITE_MAX_LENGTH) storage.set(FAVORITE_KEY, favorites) return favorites } // 将歌曲从收藏列表中删除 export function deleteFavorite(song) { let favorites = storage.get(FAVORITE_KEY, []) deleteFromArray(favorites, (item) => { return item.id === song.id }) storage.set(FAVORITE_KEY, favorites) return favorites } export function loadFavorite() { return storage.get(FAVORITE_KEY, []) }
603030f36f18513dce993dd0787849d7b84a5103
[ "JavaScript" ]
2
JavaScript
cnelf/music-player
595c8a32f40311b2e1e7677ad6d7ebf974808047
1e4b0d9f7c3c07b32ac013814bdb897dcc960c3b
refs/heads/master
<file_sep>Demonstration app built on node.js and using trestle, mongodb, express, tablesorter, bootstrap, and jade It only takes a few commands to generate this app. ##Basics 1. Install mongodb, node.js, express 2. npm install trestle -g 3. trestle app ninjas 4. cd ninjas 5. npm install 6. trestle scaffold scaffold ninjago name color power weapon found turns 7. node app.js If everything has gone right then now you can go to localhost:3000 in your browser and voila you have a completely functioning and easily customizable CRUD application. <file_sep>var Ninjago = require('../models/ninjago'), mapper = require('../lib/model-mapper'); module.exports = function(app) { app.param('ninjagoId', function(req, res, next, id) { Ninjago.findById(id, function(err, ninjago) { if (err) { next(err); } else { res.locals.ninjago = ninjago; next(); } }); }); app.get('/ninjagos', function(req, res) { Ninjago.find({}, function(err, ninjagos) { res.render('ninjago/index', { ninjagos : ninjagos }); }); }); app.get('/ninjagos/create', function(req, res) { res.render('ninjago/create', { ninjago : new Ninjago() }); }); app.post('/ninjagos/create', function(req, res) { var ninjago = new Ninjago(req.body); ninjago.save(function(err) { if (err) { res.render('ninjago/create', { ninjago : ninjago }); } else { res.redirect('/ninjagos'); } }); }); app.get('/ninjagos/:ninjagoId/edit', function(req, res) { res.render('ninjago/edit'); }); app.post('/ninjagos/:ninjagoId/edit', function(req, res) { mapper.map(req.body).to(res.locals.ninjago); res.locals.ninjago.save(function(err) { if (err) { res.render('ninjago/edit'); } else { res.redirect('/ninjagos'); } }); }); app.get('/ninjagos/:ninjagoId/detail', function(req, res) { res.render('ninjago/detail'); }); app.get('/ninjagos/:ninjagoId/delete', function(req, res) { res.render('ninjago/delete'); }); app.post('/ninjagos/:ninjagoId/delete', function(req, res) { Ninjago.remove({ _id : req.params.ninjagoId }, function(err) { res.redirect('/ninjagos'); }); }); } // Used to build the index page. Can be safely removed! module.exports.meta = { name : 'Ninjago', route : '/ninjagos' } <file_sep>var mongoose = require('mongoose'), Schema = mongoose.Schema; var Ninjago = new Schema({ name: { type: String }, color: { type: String }, power: { type: String }, weapon: { type: String }, found: { type: String }, turns: { type: String } }); module.exports = mongoose.model('Ninjago', Ninjago);
ae80a2caa98f91c4f7c81daf35ee938ce5aa5f4f
[ "Markdown", "JavaScript" ]
3
Markdown
ahmad-nasikin/ninjas
debb59f80bce6b01d841f84adb98eb575916722a
167f64a23a7c0dc1f8543de0a57fca2ee3eaa771
refs/heads/main
<file_sep>import { Component } from '@angular/core' interface List { id: number name: string } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { search: string = "" list: List[] = [] add() { this.list.push({ id: this.list.length, name: this.search }) } delete(index: number) { console.log(index) this.list.splice(index, 1) } identify(index: number, item: List){ return item.id } }
e2e567f85c8de7c72c55a436318a366281409b1e
[ "TypeScript" ]
1
TypeScript
vocing/fed-e-task-04-06-master
36f0e9db5e9f821a18c38d43b2f57be3b934d082
2155db898ac9ed7d494757153dfc58c8ac80ae6f
refs/heads/master
<file_sep>#include "prsim.h" std::vector<PRCPU*> procs; RAM *ram; PRassembler *assem; std::string simfile; int firstadd; int p; //number of processors int CLOCK; PRsim::PRsim(std::string filename, int _p) { ram = new RAM(2000); //cpu = new PRCPU(32,32,32,ram); ram->RAM_info(); simfile = filename; firstadd = 100; p = _p; for(int i = 0; i<p; i++){ procs.push_back(new PRCPU(32,32,ram,i)); std::cout << "Added proc "<< procs[i]->getID() <<"\n"; } assem = new PRassembler(procs[0]->getInstructionDesc()); CLOCK = 0; } void PRsim::assembleAndLoad(){ //std::cout << "Assemble and Load\n"; std::vector<std::tuple<int,std::string>> assembled = assem->assemble(simfile,firstadd); if(assembled.size() == 0){ std::cout << "UWsim: Error assembling file \n"; }else{ for(unsigned int i = 0; i < assembled.size(); i++){ ram->set(std::get<0>(assembled[i]), std::get<1>(assembled[i])); } } } int PRsim::executeProgram(){ //set starting PC for all processors for(int i =0; i<p; i++){ procs[i]->setPC(firstadd); } //finish when p0 halts bool finished = false; while(!finished){ std::tuple<int,std::string> check; for(unsigned int i = 0; i<procs.size(); i++){ if(procs[i]->isHalted()){ continue; } procs[i]->updateIR(); int npc = procs[i]->getPC() +1; procs[i]->setPC(npc); //std::cout<< "proc "<<i<<" sent to handle instruction. \n"; check = procs[i]->handleInstruction(); if(std::get<0>(check) != 0){ std::cout<< "ERROR: " <<"P"<<i<<": "<< procs[i]->getPC() << " , " << std::get<1>(check)<< "\n"; return CLOCK; } } CLOCK++; if(procs[0]->isHalted()){ finished = true; } } return CLOCK; } void PRsim::runSimulation(){ assembleAndLoad(); int clock = executeProgram(); std::cout<<"Number of instructions: " <<clock<<"\n"; } void PRsim::printFromRAM(int from, int to){ ram->print_range(from,to); } void PRsim::printRegister(int proc,int i){ procs[proc]->printRegister(i); } PRsim::~PRsim(){ for(int i = 0; i<p; i++){ delete(procs[i]); } delete ram; delete assem; } <file_sep>#include "ram.h" int first_ram_add; int last_ram_add; RAM::RAM(int _size) { SIZE = _size; first_ram_add = 100; last_ram_add = first_ram_add + SIZE; for(int i=first_ram_add; i<last_ram_add; i++){ ram.insert(std::make_pair(i,"")); } } std::string RAM::get(int memloc){ if((memloc>=first_ram_add) & (memloc<=last_ram_add)){ return ram.at(memloc); } std::cout<<"memloc out of range"; return "ERROR"; } void RAM::set(int memloc, std::string content){ std::cout <<"RAM: " << memloc<< " , "<<content<< "\n"; if((memloc>=first_ram_add) & (memloc<=last_ram_add)){ ram.at(memloc) = content; return; }else{ std::cout<<"memloc out of range: "<<memloc<<": "<<content<<"\n"; } } void RAM::RAM_info(){ std::cout << "SIZE: " << SIZE << "\n"; std::cout << "RAM: " << first_ram_add << " - " << last_ram_add << "\n"; } void RAM::print_range(int from, int to){ if((from >= first_ram_add) & (to <= last_ram_add) & (from <= to)){ for(int i = from; i<= to; i++){ std::cout << i << " : " << ram[i] << "\n"; } }else{ std::cout<<"print_range: invalid range provided \n"; } } <file_sep>#include <map> #include <string> #include <vector> #include <iostream> // std::cout #include <fstream> #include <sstream> #include <tuple> #include "ram.h" #include "prcpu.h" #include "prassembler.h" #include "prsim.h" int main(int argc, char *argv[]) { std::string fname = "C://Users//cmpgt//OneDrive//Documentos//code//pramsim//zerocomp.prasm"; std::string fname2 = "C://Users//cmpgt//OneDrive//Documentos//code//pramsim//simplest.prasm"; std::cout<< "about to create sim\n"; int numregs = 8; PRsim sim(fname2,numregs); sim.runSimulation(); for(int i =0; i<numregs; i++){ sim.printRegister(i,3); } return 0; } <file_sep>#ifndef RAM_H #define RAM_H #include <iostream> #include <map> #include <string> #include <cmath> class RAM { public: //number of words int SIZE; //the RAM (stores strings for rep purposes) std::map<int,std::string> ram; RAM(int _size); std::string get(int memloc); void set(int memloc, std::string content); void RAM_info(); void print_range(int from, int to); }; #endif // RAM_H <file_sep>#ifndef PRCPU_H #define PRCPU_H #include <vector> #include <string> #include <map> #include <tuple> #include <limits> #include <bitset> #include "ram.h" class PRCPU { public: PRCPU(int _wordsize, int _regs, RAM *_ram, int id); std::map<std::string,std::string> *getInstructionDesc(); //instructions std::tuple<int,std::string> ADD(int rd, int r1, int r2); std::tuple<int,std::string> ADDI(int rd, int r1, int imm); std::tuple<int,std::string> ADDU(int rd, int r1, int r2); std::tuple<int,std::string> AND(int rd, int r1, int r2); std::tuple<int,std::string> ANDI(int rd, int r1, int imm); std::tuple<int,std::string> BEQ(int r1, int r2, int add); std::tuple<int,std::string> BNE(int r1, int r2, int add); std::tuple<int,std::string> J(int add); std::tuple<int,std::string> JR(int r1); std::tuple<int,std::string> LI(int rd, int imm); std::tuple<int,std::string> LID(int rd); std::tuple<int,std::string> LW(int rd, int r1, int off, RAM *_ram); std::tuple<int,std::string> NOT(int rd, int r1); std::tuple<int,std::string> OR(int rd, int r1, int r2); std::tuple<int,std::string> ORI(int rd, int r1, int imm); std::tuple<int,std::string> SL(int rd, int r1, int r2); std::tuple<int,std::string> SLI(int rd, int r1, int imm); std::tuple<int,std::string> SLT(int rd, int r1, int r2); std::tuple<int,std::string> SLTI(int rd, int r1, int imm); std::tuple<int,std::string> SR(int rd, int r1, int r2); std::tuple<int,std::string> SRI(int rd, int r1, int imm); std::tuple<int,std::string> SUB(int rd, int r1, int r2); std::tuple<int,std::string> SUBU(int rd, int r1, int r2); std::tuple<int,std::string> SW(int r1, int r2, int off, RAM *_ram); std::tuple<int,std::string> XOR(int rd, int r1, int r2); std::tuple<int,std::string> XORI(int rd, int r1, int imm); void printRegister(int i); std::vector<std::string> tokenize(std::string str, std::string separator); std::tuple<int,std::string> handleInstruction(); bool isHalted(); void setPC(int _pc); int getPC(); int getID(); void updateIR(); private: //CONSTANTS int WORD_SIZE; int NUM_REGS; int ID; //REGISTERS std::vector<int> REG; int PC= 0; std::string IR; int OVF; int CAR; //OTHER std::map<std::string,std::string> INSTRUCTIONS; RAM *ramm; bool halt; void fillInstructionDescriptions(); int validr(int r); }; #endif // PRCPU_H <file_sep>#ifndef PRSIM_H #define PRSIM_H #include <map> #include <string> #include <vector> #include <iostream> // std::cout #include <fstream> #include <sstream> #include <tuple> #include "prcpu.h" #include "ram.h" #include "prassembler.h" class PRsim { public: PRsim(std::string filename, int _p); void assembleAndLoad(); int executeProgram(); void runSimulation(); void printFromRAM(int from, int to); void printRegister(int proc, int i); ~PRsim(); }; #endif // PRSIM_H <file_sep>#include "prassembler.h" int LC; std::map<std::string,int> labels; std::map<std::string,std::string>* instructions; int errcode = 0; std::string errmessage = ""; PRassembler::PRassembler(std::map<std::string, std::string>* inst) { instructions = inst; } std::vector<std::string> PRassembler::tokenize(std::string str, std::string separator){ std::vector<std::string> ret; int index = 0; while(index!=-1){ if(str.size()==0){ return ret; } index = str.find(separator); if(index==-1){ ret.push_back(str); return ret; }else{ if(index==0){ str = str.substr(index+separator.size()); continue; }else{ std::string seg = str.substr(0,index); str = str.substr(index+separator.size()); ret.push_back(seg); } } } return ret; } std::vector<std::string> PRassembler::fileToList(std::string filename){ std::ifstream input; std::vector<std::string> lines; std::string line; input.open(filename); while(input) { std::getline(input, line); lines.push_back(line); } input.close(); return lines; } std::string PRassembler::fileToString(std::string filename){ std::ifstream in(filename); std::string s((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); return s; } // !!!! ERRORS NOT HANDLED YET !!!! void PRassembler::getDataAndCode(std::string &text,std::string &data, std::string &code){ int iofdata = 0; int iofcode = 0; std::string sdata = ".data"; std::string scode = ".code"; iofdata = text.find(sdata); iofcode = text.find(scode); std::cout << "iofdata: " <<iofdata <<"\n"; std::cout << "iofcode: " <<iofcode <<"\n"; if(iofcode==-1){ //error in code. std::cout << "ERROR: \n"; return; } if(iofdata>iofcode){ //error in code layout std::cout << "ERROR: \n"; return; } if(iofdata!=-1){ int start = iofdata+sdata.length(); data = text.substr(start,(iofcode-start)); }else{ data = ""; } code = text.substr(iofcode+scode.length()); } std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> PRassembler::first_pass(std::string &code){ std::cout << "Starting first pass\n"; std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> res; std::map<char,std::regex> paramform; paramform['u'] = std::regex("\\$u[0-9]+"); paramform['r'] = std::regex("\\$r[0-9]+"); paramform['i'] = std::regex("[0-9]+"); std::regex label("[a-zA-Z][a-zA-Z0-9]*"); labels.clear(); int tindex = -1; std::istringstream iss(code); for (std::string line; std::getline(iss,line);){ //std::cout<<"Original line: "<<line<<"\n"; boost::trim(line); if(line.size()==0){//empty line continue; } //HANDLE COMMENTS tindex = line.find("#"); if(tindex!=-1){ //there are comments //std::cout<<"Comments found "<<"\n"; if(tindex == 0){//whole line is a comment, ignore //std::cout<<"Line is a comment"<<"\n"; continue; }else{//ignore everything after comment symbol line = line.substr(0,line.size()-(line.size()-tindex)); //std::cout<<"Comments removed: "<<line<<"\n"; } } //HANDLE LEADING LABELS //labels have to be at the beginning of the line, there can be an instruction after. boost::trim(line); tindex = line.find(":"); if(tindex!=-1){//there's a label std::vector<std::string> split = tokenize(line,":"); if(split.size()>2){ errcode = 1; errmessage = line.append(" , too many labels in a line"); return res; } if(regex_match(split[0],label)==false){ errcode = 1; errmessage = line.append(" , bad label"); return res; } if(instructions->find(split[0])!=instructions->end()){ errcode = 1; errmessage = line.append(" , bad label"); return res; } auto insert = labels.insert(std::pair<std::string,int>(split[0],LC)); if(insert.second==false){ errcode = 1; errmessage = line.append(" , repeated label"); return res; }else{ //std::cout<<"Label inserted!!\n"; } if(split.size()==1){ continue; }else{ line = split[1]; } } //HANDLE INSTRUCTION std::vector<std::string> empty; bool labelinparams = false; boost::trim(line); std::string spaces = " \t"; tindex = line.find_first_of(spaces); if(tindex == -1){ //instruction with no params or bad syntax auto it = instructions->find(line); if(it != instructions->end()){ //instruction exists std::string sec = it->second; if(sec.size() !=0){ errcode = 1; errmessage = line.append(" , missing parameters"); return res; }else{//0 parameters //std::tuple<int,std::string,std::vector<std::string>,bool> res.push_back(std::make_tuple(LC,line,empty,false)); LC++; continue; } }else{//instruction doesn't exist errcode = 1; errmessage = line.append(" , instruction does not exist"); return res; } }else{//there is a space! std::string first = line.substr(0,tindex); //std::cout<<"first: "<<first<<"\n"; std::string second = line.substr(tindex+1); //std::cout<<"second: "<<second<<"\n"; boost::trim(first); auto it = instructions->find(first); if(it != instructions->end()){ //instruction exists //param descriptor string std::string parstr = it->second; std::vector<std::string> params = tokenize(second,","); if(parstr.size() != params.size()){ errcode = 1; errmessage = line.append(" , parameter mismatch"); return res; }else{// number of parameters match for(unsigned int i = 0; i<parstr.size(); i++){ //will return in any error case, if it passes this stage, params are fine boost::trim(params[i]); if(parstr[i]=='i'){ if(regex_match(params[i],paramform[parstr[i]])==false){ if(regex_match(params[i],label)==false){ errcode = 1; errmessage = line.append(" , bad parameter format"); return res; }else{ labelinparams = true; //std::cout<<"There is a label in the parameters!\n"; continue; } }else continue; }else{ if(regex_match(params[i],paramform[parstr[i]])==false){ errcode = 1; errmessage = line.append(" , bad parameter format"); return res; }else{ //remove dollar signs and register type params[i] = params[i].substr(2); continue; } } }// params are fine //std::tuple<int,std::string,std::vector<std::string>,bool> res.push_back(std::make_tuple(LC,first,params,labelinparams)); LC++; } }else{//instruction doesn't exist errcode = 1; errmessage = line.append(" , instruction does not exist"); return res; } } }//line finished return res; } //FOR NOW, ENTIRE DATA DEFINITION MUST BE IN A SINGLE LINE std::vector<std::tuple<int,std::string>> PRassembler::handleDataSection(std::string &data){ std::cout << "Handling data section\n"; LC++; std::vector<std::tuple<int,std::string>> res; // line number, word data if(data.size()==0){ std::cout<<"No data section\n"; return res; } std::istringstream iss(data); std::regex label("[a-zA-Z][a-zA-Z0-9]*"); int tindex; //general purpose index for (std::string line; std::getline(iss,line);){ //std::cout<<"Original line: "<<line<<"\n"; boost::trim(line); //HANDLE COMMENTS if(line.size()==0){//empty line continue; } tindex = line.find("#"); if(tindex!=-1){ //there are comments //std::cout<<"Comments found "<<"\n"; if(tindex == 0){//whole line is a comment, ignore continue; }else{//ignore everything after comment symbol line = line.substr(0,line.size()-(line.size()-tindex)); } } tindex = line.find(":"); if(tindex == -1){ errcode = 1; errmessage = line.append(" , label missing"); return res; }else{//label found std::vector<std::string> split = tokenize(line,":"); if(split.size()>2){ errcode = 1; errmessage = line.append(" , too many labels in a line"); return res; } //data definition should be on the same line as the label if(split.size() == 1){ errcode = 1; errmessage = line.append(" , data definition should be on the same line as the label"); return res; } if(regex_match(split[0],label)==false){ errcode = 1; errmessage = line.append(" , bad label"); return res; } if(instructions->find(split[0])!=instructions->end()){ errcode = 1; errmessage = line.append(" , bad label"); return res; } auto insert = labels.insert(std::pair<std::string,int>(split[0],LC)); if(insert.second==false){ errcode = 1; errmessage = line.append(" , repeated label"); return res; }else{//label inserted //HANDLE DATA line = split[1]; boost::trim(line); std::string spaces = " \t"; tindex = line.find_first_of(spaces); if(tindex == -1){ errcode = 1; errmessage = line.append(" , format error"); return res; }else{ std::string first = line.substr(0,tindex); std::string second = line.substr(tindex+1); boost::trim(first); boost::trim(second); std::cout << "first: " << first <<"\n"; std::cout << "second: " << second <<"\n"; std::cout << "equals: " << (first==".ascii")<<"\n"; if(first==".word"){ std::regex number("[0-9]+"); std::vector<std::string> nums = tokenize(second,","); for(unsigned int j = 0; j<nums.size(); j++){ boost::trim(nums[j]); if(regex_match(nums[j],number)==false){ errcode = 1; errmessage = line.append(" , bad data"); return res; } res.push_back(std::make_tuple(LC,nums[j])); LC++; } }else if(first==".ascii"){ //each word will store a single character std::regex str("\".*\""); boost::trim(second); if(regex_match(second,str)){ second.pop_back(); second = second.substr(1); for(unsigned int j = 0; j<second.size(); j++){ int t = (int)second[j]; res.push_back(std::make_tuple(LC,std::to_string(t))); LC++; } }else{ errcode = 1; errmessage = line.append(" , bad data format"); return res; } }else if(first==".space"){ std::regex number("[0-9]+"); boost::trim(second); if(regex_match(second,number)){ for(int j = 0; j<atoi(second.c_str());j++){ res.push_back(std::make_tuple(LC,"0")); LC++; } }else{ errcode = 1; errmessage = line.append(" , bad data format"); return res; } }else{ errcode = 1; errmessage = line.append(" , unknown data type"); return res; } } } } }//finished all lines return res; } std::vector<std::tuple<int,std::string>> PRassembler::second_pass( std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> &fp){ std::cout << "Starting second pass\n"; std::vector<std::tuple<int,std::string>> res; //std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> fp for(unsigned int i = 0; i<fp.size(); i++){ std::regex label("[a-zA-Z][a-zA-Z0-9]*"); auto line = fp[i]; std::vector<std::string> params = std::get<2>(line); if(std::get<3>(line) == true){ std::string nln = std::get<1>(line); nln.append(" "); for(unsigned int j = 0; j<params.size();j++){ if(regex_match(params[j],label)){//at this point, param is either a valid label or a valid number if(labels.find(params[j])==labels.end()){//label does not exist errcode = 1; errmessage = params[j].append(" , invalid label"); return res; }else{ int mapped = labels[params[j]]; std::string str = std::to_string(mapped); nln.append(str); } }else{ nln.append(params[j]); } nln.append(","); } nln.pop_back(); res.push_back(std::make_tuple(std::get<0>(line),nln)); }else{ std::string nln = std::get<1>(line); nln.append(" "); for(unsigned int j = 0; j<params.size();j++){ nln.append(params[j]); nln.append(","); } //remove trailing comma nln.pop_back(); res.push_back(std::make_tuple(std::get<0>(line),nln)); } } return res; } std::vector<std::tuple<int,std::string>> PRassembler::assemble(std::string filename, int memstart){ LC = memstart; std::vector<std::tuple<int,std::string>> final; //first get file as a string std::string text = fileToString(filename); //separate code and data sections std::string data = " "; std::string code = " "; getDataAndCode(text,data,code); //first pass code section std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> linesfp = first_pass(code); if(errcode!=0){ std::cout<<"ASSEM: "<<errmessage<<"\n"; return final; }else{/* std::cout<<"FIRST PASS: \n"; for(unsigned int i = 0; i<linesfp.size(); i++){ std::cout << "LINE: " << std::get<0>(linesfp[i]) << "\n"; std::cout << "INSTRUCTION: " << std::get<1>(linesfp[i]) << "\n"; std::vector<std::string> params = std::get<2>(linesfp[i]); std::cout<< "PARAMS: "; for(unsigned int j = 0; j<params.size(); j++){ std::cout << params[j] <<", "; } std::cout<<"\n"; std::cout << "HAS LABEL: " << std::get<3>(linesfp[i]) << "\n"; }*/ } //handle data section //std::vector<std::tuple<int,std::string>>handleDataSection(std::string &data) std::vector<std::tuple<int,std::string>> linesds = handleDataSection(data); if(errcode!=0){ std::cout<<"ASSEM: "<<errmessage<<"\n"; return final; }else{ //print out label content for(auto it = labels.cbegin(); it !=labels.cend(); ++it){ std::cout << it->first << " , " <<it->second << "\n"; } } //second pass code section std::vector<std::tuple<int,std::string>> linessp = second_pass(linesfp); if(errcode!=0){ std::cout<<"ASSEM: "<<errmessage<<"\n"; return final; }else{/* std::cout << "L I N E S\n"; for(unsigned int i =0; i<linessp.size(); i++){ std::cout << std::get<0>(linessp[i]) << " : "<< std::get<1>(linessp[i]) << "\n"; }*/ } final.reserve(linessp.size() + linesds.size()); final.insert(final.end(),linessp.begin(),linessp.end()); final.insert(final.end(),linesds.begin(),linesds.end()); /* std::cout << "L I N E S + D A T A\n"; for(unsigned int i =0; i<final.size(); i++){ std::cout << std::get<0>(final[i]) << " : "<< std::get<1>(final[i]) << "\n"; }*/ std::cout << "Assemble complete\n"; return final; } <file_sep>#ifndef PRASSEMBLER_H #define PRASSEMBLER_H #include <map> #include <string> #include <vector> #include <iostream> // std::cout #include <fstream> #include <sstream> #include <tuple> #include <regex> #include <boost/algorithm/string.hpp> class PRassembler { public: PRassembler(std::map<std::string, std::string>* inst); std::vector<std::string> tokenize(std::string str, std::string separator); std::vector<std::string> fileToList(std::string filename); std::string fileToString(std::string filename); void getDataAndCode(std::string &text, std::string &data, std::string &code); std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> first_pass(std::string &code); std::vector<std::tuple<int, std::string> > handleDataSection(std::string &data); std::vector<std::tuple<int,std::string>> second_pass( std::vector<std::tuple<int,std::string,std::vector<std::string>,bool>> &fp); std::vector<std::tuple<int,std::string>> assemble(std::string filename, int memstart); }; #endif // PRASSEMBLER_H <file_sep>#include "prcpu.h" void PRCPU::fillInstructionDescriptions(){ /* * r: w sized register * i: immediate value, offset, address or base. can be replaced by a label. */ INSTRUCTIONS["add"] = "rrr"; INSTRUCTIONS["addi"] = "rri"; INSTRUCTIONS["addu"] = "rrr"; INSTRUCTIONS["and"] = "rrr"; INSTRUCTIONS["andi"] = "rri"; INSTRUCTIONS["beq"] = "rri"; INSTRUCTIONS["bne"] = "rri"; INSTRUCTIONS["j"] = "i"; INSTRUCTIONS["jr"] = "r"; INSTRUCTIONS["li"] = "ri"; INSTRUCTIONS["lid"] = "r"; INSTRUCTIONS["lw"] = "rri"; INSTRUCTIONS["not"] = "rr"; INSTRUCTIONS["or"] = "rrr"; INSTRUCTIONS["ori"] = "rri"; INSTRUCTIONS["sl"] = "rrr"; INSTRUCTIONS["sli"] = "rri"; INSTRUCTIONS["slt"] = "rrr"; INSTRUCTIONS["slti"] = "rri"; INSTRUCTIONS["sr"] = "rrr"; INSTRUCTIONS["sri"] = "rri"; INSTRUCTIONS["sub"] = "rrr"; INSTRUCTIONS["subu"] = "rrr"; INSTRUCTIONS["sw"] = "rri"; INSTRUCTIONS["xor"] = "rrr"; INSTRUCTIONS["xori"] = "rri"; INSTRUCTIONS["halt"] = ""; } PRCPU::PRCPU(int _wordsize, int _regs, RAM *_ram, int id) { WORD_SIZE = _wordsize; NUM_REGS = _regs; ID = id; ramm = _ram; fillInstructionDescriptions(); for(int i = 0; i<NUM_REGS; i++){ REG.push_back(0); } halt = false; } std::map<std::string, std::string> *PRCPU::getInstructionDesc(){ return &INSTRUCTIONS; } //1 if register number is valid int PRCPU::validr(int r){ if((r>=0) & (r<NUM_REGS)){ return 1; } return 0; } //UTILITIES std::string intToBits(int x){ std::bitset<32> _x(x); return _x.to_string(); } //INSTRUCTIONS //ADD $rd, $r1, $r2 : $rd = $r1 + $r2; std::tuple<int,std::string> PRCPU::ADD(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(ADD): Invalid register(s)"; return std::make_tuple(1,msg); } //overflow if(((REG[r2]>0) & (REG[r1] > (std::numeric_limits<float>::max()-REG[r2]))) | ((REG[r1]>0) & (REG[r2] > (std::numeric_limits<float>::max()-REG[r1])))){ OVF = 1; msg = "(ADD): Overflow detected"; } //underflow if(((REG[r2]<0) & (REG[r1] < (std::numeric_limits<float>::min()-REG[r2]))) | ((REG[r1]<0) & (REG[r2] < (std::numeric_limits<float>::max()-REG[r1])))){ OVF = 1; msg = "(ADD): Underflow detected"; } REG[rd] = REG[r1] + REG[r2]; return std::make_tuple(0,msg); } //ADDI $rd, $r1, imm : $rd = $r1 + imm; std::tuple<int,std::string> PRCPU::ADDI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(ADDI): Invalid register(s)"; return std::make_tuple(1,msg); } //overflow if(((imm>0) & (REG[r1] > (std::numeric_limits<float>::max()-imm))) | ((REG[r1]>0) & (imm > (std::numeric_limits<float>::max()-REG[r1])))){ OVF = 1; msg = "(ADDI): Overflow detected"; } //underflow if(((imm<0) & (REG[r1] < (std::numeric_limits<float>::min()-imm))) | ((REG[r1]<0) & (imm < (std::numeric_limits<float>::max()-REG[r1])))){ OVF = 1; msg = "(ADDI): Underflow detected"; } REG[rd] = REG[r1] + imm; return std::make_tuple(0,msg); } //ADDU $rd, $r1, $r2 : $rd = $r1 + $r2; (unsigned, no overflow) std::tuple<int,std::string> PRCPU::ADDU(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(ADDU): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = (unsigned int)REG[r1] + (unsigned int)REG[r2]; return std::make_tuple(0,msg); } //AND $rd, $r1, $r2 : $rd = $r1 & $r2; std::tuple<int,std::string> PRCPU::AND(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(AND): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] & REG[r2]; return std::make_tuple(0,msg); } //ANDI $rd, $r1, imm : $rd = $r1 & imm; std::tuple<int,std::string> PRCPU::ANDI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(ANDI): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] & imm; return std::make_tuple(0,msg); } //BEQ $r1, $r2, off : if($r1 == $r2) then branch to off; std::tuple<int,std::string> PRCPU::BEQ(int r1, int r2, int add){ std::string msg = ""; if((validr(r1)==0) | (validr(r2)==0)){ msg = "(BEQ): Invalid register(s)"; return std::make_tuple(1,msg); } if(REG[r1] == REG[r2]){ PC = add; } return std::make_tuple(0,msg); } //BNE $r1, $r2, off : if($r1 != $r2) then branch to off; std::tuple<int,std::string> PRCPU::BNE(int r1, int r2, int add){ std::string msg = ""; if((validr(r1)==0) | (validr(r2)==0)){ msg = "(BNE): Invalid register(s)"; return std::make_tuple(1,msg); } if(REG[r1] != REG[r2]){ PC = add; } return std::make_tuple(0,msg); } //J add: PC = add std::tuple<int,std::string> PRCPU::J(int add){ std::string msg = ""; PC = add; return std::make_tuple(0,msg); } //JR add: PC = $r1 std::tuple<int,std::string> PRCPU::JR(int r1){ std::string msg = ""; if(validr(r1)==0){ msg = "(BNE): Invalid register(s)"; return std::make_tuple(1,msg); } PC = REG[r1]; return std::make_tuple(0,msg); } //LI $rd, imm: $rd = imm std::tuple<int,std::string> PRCPU::LI(int rd, int imm){ std::string msg = ""; if(validr(rd)==0){ msg = "(LI): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = imm; return std::make_tuple(0,msg); } //LID $rd: $rd = ID std::tuple<int,std::string> PRCPU::LID(int rd){ std::string msg = ""; if(validr(rd)==0){ msg = "(LUW): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = ID; return std::make_tuple(0,msg); } //LW $rd, $r1, off : $rd = MEM[$r1 + off]; std::tuple<int,std::string> PRCPU::LW(int rd, int r1, int off, RAM *_ram){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(LW): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = atoi((_ram->get(REG[r1]+off)).c_str()); return std::make_tuple(0,msg); } //NOT $rd,$r1: $rd = ~$r1 std::tuple<int,std::string> PRCPU::NOT(int rd, int r1){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(UWNOT): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = ~(REG[r1]); return std::make_tuple(0,msg); } //OR $rd, $r1, $r2 : $rd = $r1 | $r2; std::tuple<int,std::string> PRCPU::OR(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(OR): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] | REG[r2]; return std::make_tuple(0,msg); } //ORI $rd, $r1, imm : $rd = $r1 | imm; std::tuple<int,std::string> PRCPU::ORI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(ORI): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] | imm; return std::make_tuple(0,msg); } //SL $rd, $r1, $r2 : $rd = $r1 << $r2; std::tuple<int,std::string> PRCPU::SL(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(SL): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] << REG[r2]; return std::make_tuple(0,msg); } //SLI $rd, $r1, imm : $rd = $r1 << imm; std::tuple<int,std::string> PRCPU::SLI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(SLI): Invalid register(s)"; return std::make_tuple(1,msg); } if(imm >= WORD_SIZE){ msg = "(SLI): Shift larger than WORD_SIZE is invalid"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] << imm; return std::make_tuple(0,msg); } //SLT $rd, $r1, $r2 : $rd = ($r1 == $r2); std::tuple<int,std::string> PRCPU::SLT(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(SLT): Invalid register(s)"; return std::make_tuple(1,msg); } if(REG[r1] == REG[r2]){ REG[rd] = 1; }else{ REG[rd] = 0; } return std::make_tuple(0,msg); } //SLTI $rd, $r1, imm : $rd = ($r1 == imm); std::tuple<int,std::string> PRCPU::SLTI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(SLTI): Invalid register(s)"; return std::make_tuple(1,msg); } if(REG[r1] == imm){ REG[rd] = 1; }else{ REG[rd] = 0; } return std::make_tuple(0,msg); } //SRV $rd, $r1, $r2 : $rd = $r1 >> imm; std::tuple<int,std::string> PRCPU::SR(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(SR): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] >> REG[r2]; return std::make_tuple(0,msg); } //SRI $rd, $r1, imm : $rd = $r1 >> imm; std::tuple<int,std::string> PRCPU::SRI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(SRI): Invalid register(s)"; return std::make_tuple(1,msg); } if(imm >= WORD_SIZE){ msg = "(SRI): Shift larger than WORD_SIZE is invalid"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] >> imm; return std::make_tuple(0,msg); } //SUB $rd, $r1, $r2 : $rd = $r1 - $r2; std::tuple<int,std::string> PRCPU::SUB(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(SUB): Invalid register(s)"; return std::make_tuple(1,msg); } //overflow if(((REG[r2]<0) & (REG[r1] > (std::numeric_limits<float>::max()+REG[r2]))) | ((REG[r1]<0) & (REG[r2] > (std::numeric_limits<float>::max()+REG[r1])))){ OVF = 1; msg = "(SUB): Overflow detected"; } //underflow if(((REG[r2]>0) & (REG[r1] < (std::numeric_limits<float>::min()+REG[r2]))) | ((REG[r1]>0) & (REG[r2] < (std::numeric_limits<float>::min()+REG[r1])))){ OVF = 1; msg = "(SUB): Underflow detected"; } REG[rd] = REG[r1] - REG[r2]; return std::make_tuple(0,msg); } //SUBU $rd, $r1, $r2 : $rd = $r1 - $r2; (unsigned, no overflow) std::tuple<int,std::string> PRCPU::SUBU(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(SUBU): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] - REG[r2]; return std::make_tuple(0,msg); } //SW $r1, $r2, off : MEM[$r2 + off] = $r1; std::tuple<int,std::string> PRCPU::SW(int r1, int r2, int off, RAM *_ram){ std::string msg = ""; if((validr(r1)==0) | (validr(r2)==0)){ msg = "(SW): Invalid register(s)"; return std::make_tuple(1,msg); } _ram->set(REG[r2]+off, std::to_string(REG[r1])); return std::make_tuple(0,msg); } //XOR $rd, $r1, $r2 : $rd = $r1 ^ $r2; std::tuple<int,std::string> PRCPU::XOR(int rd, int r1, int r2){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0) | (validr(r2)==0)){ msg = "(XOR): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] ^ REG[r2]; return std::make_tuple(0,msg); } //XORI $rd, $r1, imm : $rd = $r1 ^ imm; std::tuple<int,std::string> PRCPU::XORI(int rd, int r1, int imm){ std::string msg = ""; if((validr(rd)==0) | (validr(r1)==0)){ msg = "(ORI): Invalid register(s)"; return std::make_tuple(1,msg); } REG[rd] = REG[r1] ^ imm; return std::make_tuple(0,msg); } void PRCPU::printRegister(int i){ if(validr(i)==0){ std::cout<< "(printRegister): Invalid register number"; return; } std::cout <<"P"<<ID<< " : R"<<i<<": "<<"\n"; std::cout << intToBits(REG[i]) << "\n"; return; } // PROGRAM EXECUTION AND INSTRUCTION HANDLING std::vector<std::string> PRCPU::tokenize(std::string str, std::string separator){ std::vector<std::string> ret; int index = 0; while(index!=-1){ if(str.size()==0){ return ret; } index = str.find(separator); if(index==-1){ ret.push_back(str); return ret; }else{ if(index==0){ str = str.substr(index+separator.size()); continue; }else{ std::string seg = str.substr(0,index); str = str.substr(index+separator.size()); ret.push_back(seg); } } } return ret; } //EXECUTE SINGLE INSTRUCTION CURRENTLY IN IR std::tuple<int,std::string> PRCPU::handleInstruction(){ std::string instructionline = IR; std::cout <<"Handling: "<<ID<<": "<<instructionline<<"\n"; //at this point we are sure instructions exist and parameters are the correct format if(instructionline.empty()){ halt = true; return std::make_tuple(0,""); } std::vector<std::string> sepinst = tokenize(instructionline," "); std::string instruction = sepinst[0]; std::vector<std::string> params; if (sepinst.size() > 1){ params = tokenize(sepinst[1],","); } std::tuple<int,std::string> ret; //Giant if-else to find instruction if(instruction == "add"){ ret = ADD(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "addi"){ ret = ADDI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "addu"){ ret = ADDU(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "and"){ ret = AND(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "andi"){ ret = ANDI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "beq"){ ret = BEQ(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "bne"){ ret = BNE(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "j"){ ret = J(atoi(params[0].c_str())); return ret; }else if(instruction == "jr"){ ret = JR(atoi(params[0].c_str())); return ret; }else if(instruction == "li"){ ret = LI(atoi(params[0].c_str()),atoi(params[1].c_str())); return ret; }else if(instruction == "lid"){ ret = LID(atoi(params[0].c_str())); return ret; }else if(instruction == "lw"){ ret = LW(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str()),ramm); return ret; }else if(instruction == "not"){ ret = NOT(atoi(params[0].c_str()),atoi(params[1].c_str())); return ret; }else if(instruction == "or"){ ret = OR(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "ori"){ ret = ORI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "sl"){ ret = SL(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "sli"){ ret = SLI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "slt"){ ret = SLT(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "slti"){ ret = SLTI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "sr"){ ret = SR(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "sri"){ ret = SRI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "sub"){ ret = SUB(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "subu"){ ret = SUBU(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "sw"){ ret = SW (atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str()),ramm); return ret; }else if(instruction == "xor"){ ret = XOR(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "xori"){ ret = XORI(atoi(params[0].c_str()),atoi(params[1].c_str()),atoi(params[2].c_str())); return ret; }else if(instruction == "halt"){ halt = true; return std::make_tuple(0,""); } return ret; } bool PRCPU::isHalted(){ return halt; } void PRCPU::setPC(int _pc){ PC = _pc; } int PRCPU::getPC(){ return PC; } int PRCPU::getID(){ return ID; } void PRCPU::updateIR(){ IR = ramm->get(PC); }
6284a7a27d697cb176e233809053f0983fb23f89
[ "C++" ]
9
C++
cmperezg/PRAMSIM
4f4da74cb1d4c0f200296fcff8aee77a3d6bde14
ef26d7a0188ac7b2b615c6ae132dbdf8a81e2dcf
refs/heads/main
<file_sep>#include<stdio.h> intmain(){ int } <file_sep>#include<stdio.h> int main(){ unsigned int n,i,j,k=0,l=1; scanf("%d",&n); for(i=0;i<n;i++){ if((l%2==0||l%3==0||l%5==0||l==1)&&l%7!=0){ k++; } else{ i--; k++; } l++; } printf("%d",k); return 0; } <file_sep>#include<stdio.h> int main(){ int i,j,k=0,l,n=1; if(n<=1000&&n>=1) scanf("%d",&n); if(n%2==0){ n--; k++; l=((n+k)/2)-1; } else{ l=((n+k)/2); } for(i=0;i<(n+k)/2;i++){ for(j=0;j<n;j++){ if(j==(n/2)-i||j==(n/2)+i) printf("*"); else printf("_"); } printf("\n"); } for(i=0;i<=l;i++){ for(j=0;j<n;j++){ if(j==i||j==(n-1)-i) printf("*"); else printf("_"); } printf("\n"); } return 0; } <file_sep>#include<stdio.h> int main(){ int n,i,j,k,l=1; scanf("%d",&n); for(i=0;i<n;i++){ if((l%2==0||l%3==0||l%5==0||l%7==0||l==1||l==2||l==5)&&(l!=7)){ l++; } else{ i--; l++; } } printf("%d",l); return 0; } <file_sep>#include<stdio.h> int main(){ int n,m,i,j,l=0,k,h,w,i1,j1,l1=0,w1; scanf("%d",&n); scanf("%d",&m); int a[n][n]={}; int c[20]={}; for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); w=m,w1=m; i1=0,j1=0; while(1){ for(i=i1;i<w1;i++){ for(j=j1;j<w;j++){ c[l]+=a[i][j]; printf("%d ",a[i][j]); } l1++; } w++,l++,j1++; if(l1%m==0){ i1++; w=m; w1++; j1=0; } if((i+1)*(j+1)==n*n) break; } /*k=c[0]; for(i=0;i<l;i++){ if(k<c[i]){ k=c[i]; h=i; } } printf("%d",c[h]);*/ return 0; }
681838e71af672c9c2da61c5fa0752e5837c1099
[ "C++" ]
5
C++
b6320502517/123_lab5
85a199dca1454ab9fd17f1e722c382ddf75310be
f2414d7ced2dcd6ba66cf4d9c36a29976f96b75c
refs/heads/master
<repo_name>gxd523/PluginDemo<file_sep>/app/src/main/java/com/demo/sample/ProxyService.java package com.demo.sample; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import com.demo.plugin.IProxyService; public class ProxyService extends Service { private IProxyService pluginService; @Override public ClassLoader getClassLoader() { return PluginManager.getInstance().getDexClassLoader(); } private void initPluginService(Intent intent) { String className = intent.getStringExtra("className"); try { Class pluginServiceClass = getClassLoader().loadClass(className); pluginService = (IProxyService) pluginServiceClass.newInstance(); pluginService.attachProxy(this); pluginService.onProxyCreate(); } catch (Exception e) { e.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { Log.d("gxd", "ProxyService.onBind-->"); initPluginService(intent); pluginService.onProxyBind(intent); return null; } @Override public boolean onUnbind(Intent intent) { pluginService.onProxyUnbind(intent); return super.onUnbind(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("gxd", "ProxyService.onStartCommand-->"); initPluginService(intent); pluginService.onProxyStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { pluginService.onProxyDestroy(); super.onDestroy(); } } <file_sep>/app/src/main/java/com/demo/sample/Func1.java package com.demo.sample; /** * Created by guoxiaodong on 2020-02-23 10:28 */ public interface Func1<T> { void call(T t); } <file_sep>/plugin/src/main/java/com/demo/plugin/sample/base/BasePluginActivity.java package com.demo.plugin.sample.base; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import com.demo.plugin.IProxyActivity; /** * Created by guoxiaodong on 2020-02-22 17:22 */ public abstract class BasePluginActivity extends Activity implements IProxyActivity { protected Activity that; @Override public void attachProxy(Activity proxyActivity) { that = proxyActivity; } @Override public void onProxyCreate(Bundle savedInstanceState) { } @Override public void onProxyStart() { } @Override public void onProxyResume() { } @Override public void onProxyPause() { } @Override public void onProxyStop() { } @Override public void onProxyDestroy() { } @Override public void onProxySaveInstanceState(Bundle outState) { } @Override public boolean onProxyTouchEvent(MotionEvent event) { return false; } @Override public void onProxyBackPressed() { } @Override public void setContentView(int layoutResID) { that.setContentView(layoutResID); } @Override public <T extends View> T findViewById(int id) { return that.findViewById(id); } @Override public void startActivity(Intent intent) { Intent intent1 = new Intent(); intent1.putExtra("className", intent.getComponent().getClassName()); that.startActivity(intent1); } @Override public ComponentName startService(Intent service) { Intent intent = new Intent(); intent.putExtra("className", service.getComponent().getClassName()); return that.startService(intent); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { return that.registerReceiver(receiver, filter); } @Override public void sendBroadcast(Intent intent) { that.sendBroadcast(intent); } } <file_sep>/plugin/src/main/java/com/demo/plugin/sample/AnotherPluginActivity.java package com.demo.plugin.sample; import android.os.Bundle; import com.demo.plugin.sample.base.BasePluginActivity; /** * Created by guoxiaodong on 2020-02-22 17:21 */ public class AnotherPluginActivity extends BasePluginActivity { @Override public void onProxyCreate(Bundle savedInstanceState) { super.onProxyCreate(savedInstanceState); setContentView(R.layout.activity_another_plugin); } } <file_sep>/plugin/src/main/java/com/demo/plugin/sample/StaticPluginReceiver.java package com.demo.plugin.sample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by guoxiaodong on 2020-02-24 16:15 */ public class StaticPluginReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("gxd", "StaticPluginReceiver-->" + intent.getAction()); context.sendBroadcast(new Intent("com.demo.plugin.static.broadcast")); } } <file_sep>/plugin/src/main/java/com/demo/plugin/sample/base/BasePluginService.java package com.demo.plugin.sample.base; import android.app.Service; import android.content.Intent; import android.content.res.Configuration; import android.os.IBinder; import com.demo.plugin.IProxyService; /** * Created by guoxiaodong on 2020-02-23 16:09 */ public abstract class BasePluginService extends Service implements IProxyService { private Service that; @Override public void attachProxy(Service proxyService) { that = proxyService; } @Override public void onProxyCreate() { } @Override public void onProxyStart(Intent intent, int startId) { } @Override public int onProxyStartCommand(Intent intent, int flags, int startId) { return 0; } @Override public void onProxyDestroy() { } @Override public void onProxyConfigurationChanged(Configuration newConfig) { } @Override public void onProxyLowMemory() { } @Override public void onProxyTrimMemory(int level) { } @Override public IBinder onProxyBind(Intent intent) { return null; } @Override public boolean onProxyUnbind(Intent intent) { return false; } @Override public void onProxyRebind(Intent intent) { } @Override public void onProxyTaskRemoved(Intent rootIntent) { } @Override public IBinder onBind(Intent intent) { return null; } } <file_sep>/plugin/src/main/java/com/demo/plugin/sample/base/BasePluginReceiver.java package com.demo.plugin.sample.base; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.demo.plugin.IProxyBroadcastReceiver; /** * Created by guoxiaodong on 2020-02-24 13:09 */ public abstract class BasePluginReceiver extends BroadcastReceiver implements IProxyBroadcastReceiver { @Override public void attachProxy(Context context) { } @Override public void onProxyReceive(Context context, Intent intent) { } @Override public void onReceive(Context context, Intent intent) { } } <file_sep>/library/src/main/java/com/demo/plugin/IProxyService.java package com.demo.plugin; import android.app.Service; import android.content.Intent; import android.content.res.Configuration; import android.os.IBinder; /** * Created by guoxiaodong on 2020-02-23 16:02 */ public interface IProxyService { void attachProxy(Service proxyService); void onProxyCreate(); void onProxyStart(Intent intent, int startId); int onProxyStartCommand(Intent intent, int flags, int startId); void onProxyDestroy(); void onProxyConfigurationChanged(Configuration newConfig); void onProxyLowMemory(); void onProxyTrimMemory(int level); IBinder onProxyBind(Intent intent); boolean onProxyUnbind(Intent intent); void onProxyRebind(Intent intent); void onProxyTaskRemoved(Intent rootIntent); }
5c6dcc5ff00ceb73f1e140df7095fa3a62dad415
[ "Java" ]
8
Java
gxd523/PluginDemo
6ec6776398f0fc77e80da54ba3675b9856114c42
e2c87152bab35c9434dd92e4e5421b537ce5c7bd
refs/heads/master
<repo_name>jdthorne/squirrel<file_sep>/README.md # Squirrel A silly odyssey. Play it via rawgit: https://ghcdn.rawgit.org/jdthorne/squirrel/master/squirrel.html ## Controls Left side of the screen: drag to move Right side of the screen: tap to jump Also supports gamepads. <file_sep>/character/combat/combat.js import Fall from '../movement/fall.js'; const INVUNERABILITY_PERIOD = 40.0; class Combat { constructor(character, options) { this.character = character; this.dead = false; options = options || {}; this.healthMax = options.health || 0; this.health = options.health || 0; this.iframes = 0; this.aggrivation = 0; } show(group) { let showSprite = (asset) => { let sprite = new PIXI.Sprite( PIXI.loader.resources[asset].texture ); sprite.position.y = 30; sprite.scale.x = 0.075 * 0.75; sprite.scale.y = 0.075 * 0.5; sprite.anchor.x = 0.5; sprite.anchor.y = 0.5; sprite.visible = false; group.addChild(sprite); return sprite; }; this.healthBar = showSprite("assets/health-bar.svg"); this.healthBox = showSprite("assets/health-box.svg"); } updateHealthBar() { if (!this.healthMax) { return; } if (this.health < 0) { this.healthBar.visible = false; this.healthBox.visible = false; return; } let healthFraction = this.health / this.healthMax; this.healthBar.visible = true; // this.healthBox.visible = true; this.healthBar.scale.x = this.healthBox.scale.x * healthFraction; } hit(damage) { if (!this.vulnerable()) { return; } if (this.iframes > 0) { return; } this.iframes = INVUNERABILITY_PERIOD; this.health -= damage; this.updateHealthBar(); if (this.health < 0) { this.die(); } } aggro(amount) { this.aggrivation += amount; } die() { this.dead = true; this.character.die(); if (this.character.movements && this.character.movements.fall) { this.character.movements.fall.activate(); } else { this.character.movement = new Fall(this.character, this.character.world.ground); this.character.movement.activate(); } } heal() { this.health += 1; if (this.health >= 0) { this.resurrect(); } } resurrect() { this.dead = false; if (this.character.movements && this.character.movement == this.character.movements.fall) { this.character.movements.soar.activate(); } } vulnerable() { return !this.dead; } tick() { if (this.iframes > 0) { this.iframes -= 1; } if (this.aggrivation > 0) { this.aggrivation -= 1; } } // TODO: Fix this? enemies() { if (window.player) { return [window.player]; } return []; } enemiesWithin(distance, position) { return this.enemies().filter((e) => { let d = e.position.minus(position).length(); return (d < distance); }); } } export default Combat; <file_sep>/world/ground.js import Layer from './layer.js' import Vector from '../util/vector.js' class Ground extends Layer { load(data) { super.load(data); this.paths.forEach((path) => { path.splitDownTo(25); }); } show(app) { let graphics = new PIXI.Graphics(); this.paths.forEach((path) => { path.links.forEach((link) => { graphics.lineStyle(path.width, 0xFFFFFF, 1); graphics.moveTo(link.start.x, link.start.y); graphics.lineTo(link.end.x, link.end.y); }); }); app.stage.addChild(graphics); } enforce(point) { // => [success, point, normal, tangent] var normal = null; var tangent = null; var snapped = false; this.paths.forEach((path) => { path.links.forEach((link) => { let startToPoint = point.minus(link.start); let t = startToPoint.dot(link.direction); if (t < 0) { t = 0; } if (t > link.length) { t = link.length; } let linkPoint = new Vector( link.start.x + (link.direction.x * t), link.start.y + (link.direction.y * t) ); let linkPointToPoint = point.minus(linkPoint); if (linkPointToPoint.length() < path.halfWidth) { snapped = true; linkPointToPoint.normalize().multiplyBy(path.halfWidth); point = linkPoint.add(linkPointToPoint); normal = linkPointToPoint; tangent = link.end.minus(link.start); } }); }); return [snapped, point, normal]; } } export default Ground;<file_sep>/character/movement/soar.js import Fall from './fall.js'; const MIN_SLIDE_SPEED = 10; const SPEED_X = 0.35; const SPEED_Y = 0.2; class Soar extends Fall { // Soar: fall, but in a controlled arc constructor(character, navigation, ground) { super(character, ground); this.navigation = navigation; } control(input) { // push this.character.velocity.x += input.move.x * SPEED_X; this.character.velocity.y += input.move.y * SPEED_Y; } animate() { this.character.animations.soar.activate(); this.aim(this.character.velocity); } slip() { let speed = this.character.velocity.length(); if (speed < MIN_SLIDE_SPEED) { this.character.velocity.multiplyBy(MIN_SLIDE_SPEED / speed); if (this.character.velocity.y < 0) { this.character.velocity.multiplyBy(-1); } } this.character.velocity.multiplyBy(0.95); } } export default Soar; <file_sep>/world/world.js import Debug from '../util/debug.js' import Navigation from './navigation.js' import Enemies from './enemies.js' import Layer from './layer.js' import Objects from './objects.js' import Ground from './ground.js' import Artwork from './artwork.js' import Triggers from './triggers.js' import Fade from './fade.js' class World { constructor() { this.artwork = new Artwork(); this.navigation = new Navigation(); this.ground = new Ground(); this.enemies = new Enemies(this); this.objects = new Objects(this); this.triggers = new Triggers(this); this.fade = new Fade(this); } show(app) { this.artwork.show(app, 'back'); this.enemies.show(app); this.objects.show(app); this.player.show(app.stage); this.artwork.show(app, 'front'); this.fade.show(app); // this.navigation.show(app); } reset() { this.enemies.reset(); } tick() { this.enemies.tick(); this.objects.tick(); } load(done) { fetch("assets/world.svg") .then(response => response.text()) .then(response => { let dom = new DOMParser().parseFromString(response, 'image/svg+xml'); let groups = Array.prototype.slice.call( dom.getElementsByTagName("g") ); groups.forEach((group) => { let id = group.getAttribute("id"); if (!/^[A-Z]-/.test(id)) { return; } let loadInto = { A: this.artwork, N: this.navigation, E: this.enemies, G: this.ground, T: this.triggers }[id[0]]; if (loadInto) { loadInto.load(group); } }); if (done) { done(); } }) .catch(error => { console.error("Failed to load world"); console.error(error); }); } } export default World;<file_sep>/objects/effect.js import Thing from './thing.js'; class Effect extends Thing { constructor(options = {}) { super(options); this.lifespan = options.lifespan || 15; this.life = this.lifespan; this.spin = 0.5 - Math.random(); this.alpha = options.alpha || 1; } tick() { super.tick(); this.life -= 1; this.sprite.rotation += 0.2 * this.spin; this.sprite.alpha = (this.life / this.lifespan) * this.alpha; let scale = 0.75 + (((this.lifespan - this.life) / this.lifespan) * 0.25); this.sprite.scale.x = 0.075 * scale * this.scale; this.sprite.scale.y = 0.075 * scale * this.scale; if (this.life <= 0) { this.remove(); } } } export default Effect;<file_sep>/character/animation/frames.js import Animation from './animation.js'; class Frames extends Animation { constructor(character, sprites, options = {}) { super(character, sprites, options); this.progress = 0; this.length = options.length || 1; this.repeat = options.repeat || false; } animate(progress) { this.animateTo(this.progress + progress); } animateTo(progress) { if (this.repeat) {progress = progress % 1; } let currentFrame = Math.floor(progress * this.sprites.length); if (currentFrame >= this.sprites.length) { currentFrame = this.sprites.length - 1; } this.sprites.forEach((sprite, index) => { sprite.visible = (index == currentFrame); }); this.progress = progress; } reset() { this.animateTo(0); } } export default Frames; <file_sep>/world/enemies.js import Layer from './layer.js' import SnailSlug from '../character/snail-slug.js' import Pigeon from '../character/pigeon.js' const ENEMY_CLASSES = { SnailSlug: SnailSlug, Pigeon: Pigeon }; class Enemies extends Layer { constructor(world) { super(); this.world = world; this.enemies = []; } show(app) { this.app = app; let group = new PIXI.Container(); this.group = group; app.stage.addChild(group); this.enemies.forEach((enemy) => { enemy.show(group); }); } reset() { this.enemies = this.enemies.map((enemy) => { enemy.hide(this.group); enemy = new enemy.constructor(this.world, enemy.path); enemy.show(this.group); return enemy; }); } tick() { this.enemies.forEach((enemy) => { enemy.tick(); }); } load(dom) { this.paths = []; super.load(dom); this.paths.forEach((path) => { path.splitDownTo(25); }); let id = dom.getAttribute("id"); let type = id.substr(2); let enemyClass = ENEMY_CLASSES[type]; if (!enemyClass) { return; } this.paths.forEach((path) => { this.enemies.push(new enemyClass(this.world, path)); }); } } export default Enemies;<file_sep>/character/combat/weapons/weapon.js class Weapon { constructor(character, options) { this.character = character; this.damage = options.damage; this.animations = options.animations || {}; this.options = options; } activate() { } deactivate() { } ready() { return true; } } export default Weapon; <file_sep>/util/aabb.js import Vector from './vector.js'; class AABB { constructor(points) { if (points) { this.addPoints(points); } } addPoints(points) { if (!this.anyPoints) { this.x1 = points[0].x; this.x2 = points[0].x; this.y1 = points[0].y; this.y2 = points[0].y; this.anyPoints = true; } points.forEach((point) => { if (point.x < this.x1) { this.x1 = point.x; } if (point.y < this.y1) { this.y1 = point.y; } if (point.x > this.x2) { this.x2 = point.x; } if (point.y > this.y2) { this.y2 = point.y; } }); this.center = new Vector({ x: (this.x2 + this.x1) / 2, y: (this.y2 + this.y1) / 2 }); } contains(point) { if (this.x1 > point.x) { return false; } if (this.y1 > point.y) { return false; } if (this.x2 < point.x) { return false; } if (this.y2 < point.y) { return false; } return true; } } export default AABB; <file_sep>/character/combat/leap-combat.js import Combat from './combat.js'; class LeapCombat extends Combat { constructor(character, options) { super(character); this.weapons = options.weapons || {}; } vulnerable() { if (this.weapon && this.weapon.ready()) { return false; } return this.character.movement == this.character.movements.climb || this.character.movement == this.character.movements.soar || this.character.movement == this.character.movements.fall; } arm() { this.armed = true; } disarm() { if (this.weapon) { this.weapon.deactivate(); this.weapon = null; } this.armed = false; } attack(weapon) { if (!this.armed) { return; } if (this.weapon && this.weapon != weapon) { this.weapon.deactivate(); } this.weapon = weapon; this.weapon.activate(); } hold() { if (this.weapon) { this.weapon.deactivate(); this.weapon = null; } } enemies() { return this.character.world.enemies.enemies || []; } tick() { super.tick(); if (this.weapon) { this.weapon.tick(); } } } export default LeapCombat; <file_sep>/character/snail-slug.js import Character from './character.js'; import Patrol from './movement/patrol.js'; import Frames from './animation/frames.js'; import TouchCombat from './combat/touch-combat.js'; import Debris from '../objects/debris.js'; import Vector from '../util/vector.js'; const SPEED = 0.5; const COMBAT_RANGE = 50.0; class SnailSlug extends Character { constructor(world, path) { super(world, { acorns: 1 }); this.path = path; this.animations = { patrol: new Frames(this, ["assets/snail-slug.svg"]), fall: new Frames(this, ["assets/snail-slug-dead.svg"]) }; this.animations.patrol.activate(); this.movement = new Patrol(this, path, SPEED); this.combat = new TouchCombat(this, { health: 100, range: COMBAT_RANGE }); } die() { super.die(); this.world.objects.add(new Debris({ asset: "assets/snail-slug-shell.svg", position: this.position.clone(), velocity: new Vector(5 * this.world.player.scale.x, -2) })); } } export default SnailSlug; <file_sep>/character/character.js import Vector from '../util/vector.js'; import Fall from './movement/fall.js'; import Pickup from '../objects/pickup.js'; class Character { constructor(world, options = {}) { this.world = world; this.position = new Vector(); this.velocity = new Vector(); this.scale = new Vector(1, 1); this.rotation = 0; this.acorns = options.acorns; } show(app) { this.app = app; let group = new PIXI.Container(); this.group = group; app.addChild(group); if (this.animations) { Object.keys(this.animations).forEach((a) => { this.animations[a].setup(group); }); this.animation.activate(); } else if (this.animation) { this.animation.setup(group); } if (this.combat) { this.combat.show(group); } } hide(app) { app.removeChild(this.group); } tick() { if (this.movement) { this.movement.tick(); } if (this.combat) { this.combat.tick(); } if (this.group) { this.group.position.x = this.position.x; this.group.position.y = this.position.y; this.group.scale.x = this.scale.x; this.group.scale.y = this.scale.y; this.group.rotation = this.rotation; } } die() { if (!this.acorns) { return; } // distribute acorns amongst up to 10 drops let drops = []; for (; this.acorns > 0; this.acorns--) { if (drops.length < 10) { let drop = new Pickup({ asset: "assets/acorn.svg", position: this.position.clone(), velocity: new Vector( (5 * Math.random()) + (2 * this.world.player.scale.x), (5 * Math.random()) - 5 ), value: 1 }); drops.push(drop); this.world.objects.add(drop); } else { drops[Math.floor(Math.random() * 10)].value += 1; } } } } export default Character;<file_sep>/util/debug.js var logs = { messages: ["loading..."] }; var debug = { log: function(item, value = null) { if (value != null) { logs[item] = value; } else { if (!logs.messages) { logs.messages = []; } logs.messages.push(item); } document.getElementById("debug").innerText = JSON.stringify(logs, null, 2); } }; window.Debug = debug; export default debug;<file_sep>/objects/projectile.js import Thing from './thing.js'; import Effect from './effect.js'; const TRIGGER_RANGE = 50.0; const DAMAGE_RANGE = 200.0; class Projectile extends Thing { constructor(options = {}) { super(options); this.combat = options.combat; this.lifespan = options.lifespan || 240; this.life = this.lifespan; this.velocity = options.velocity; this.damage = options.damage; this.rotation = options.rotation; this.spin = 0.5 - Math.random(); } tick() { super.tick(); this.life -= 1; if (this.life <= 0) { this.remove(); } this.sprite.rotation += this.spin; if (this.rotation) { this.sprite.rotation = this.rotation; } this.position = this.position.plus(this.velocity); let triggers = this.combat.enemiesWithin(TRIGGER_RANGE, this.position); if (triggers.length > 0) { this.hit(); } let [ground, _] = this.world.ground.enforce(this.position); if (ground) { this.hit(); } } hit() { let world = this.world; for (let i = 0; i < 3; i++) { world.objects.add(new Effect({ asset: "assets/explosion.svg", position: this.position, scale: 5, alpha: 0.6, lifespan: 60 })); } this.combat.enemiesWithin(DAMAGE_RANGE, this.position).forEach((enemy) => { if (enemy.combat.dead) { return; } if (enemy.combat.iframes > 0) { return; } enemy.combat.hit(this.damage); enemy.combat.aggro(240); world.objects.add(new Effect({ asset: "assets/explosion.svg", position: enemy.position, lifespan: 30 })); }); this.remove(); } /* if (enemy.combat.vulnerable() && enemy.combat.iframes <= 0 && distance < this.range) { enemy.world.objects.add(new Effect({ asset: "assets/nom.svg", position: enemy.position })); enemy.combat.hit(40); } */ } export default Projectile;<file_sep>/character/combat/weapons/pinecone.js import Ranged from './ranged.js' class Pinecone extends Ranged { constructor(character, animations) { super(character, { animations: animations, minimumCharge: 40.0, damage: 22.0 }); } } export default Pinecone;<file_sep>/world/navigation.js import Layer from './layer.js' import Vector from '../util/vector.js' const LINK_WIDTH = 4; class Navigation extends Layer { load(data) { super.load(data); this.paths.forEach((path) => { path.splitDownTo(12); }); } show(app) { let graphics = new PIXI.Graphics(); this.paths.forEach((path) => { path.links.forEach((link) => { graphics.lineStyle(path.width, 0xFF00FF, 1); graphics.moveTo(link.start.x, link.start.y); graphics.lineTo(link.end.x, link.end.y); }); }); app.stage.addChild(graphics); } snap(point, maxDistance) { // => [success, point] var closestPoint = null; var closestPath = null; var closestDistance = null; var closestT = null; var distances = []; this.paths.forEach((path) => { path.links.forEach((link) => { let startToPoint = point.minus(link.start); let t = startToPoint.dot(link.direction); if (t < 0) { t = 0; } if (t > link.length) { t = link.length; } let thisPoint = new Vector( link.start.x + (link.direction.x * t), link.start.y + (link.direction.y * t) ); let thisDistance = thisPoint.minus(point).length() - path.halfWidth; if (!closestPoint || thisDistance < closestDistance) { closestPoint = thisPoint; closestDistance = thisDistance; closestPath = path; closestT = t; } }); }); if (!closestPoint) { return [false, point]; } if (closestDistance > maxDistance) { return [false, point]; } if (closestDistance > 0) { let closestPointToPoint = point.minus(closestPoint); closestPointToPoint.normalize(); closestPointToPoint.multiplyBy(closestPath.halfWidth); return [true, closestPoint.plus(closestPointToPoint)]; } return [true, point]; } } export default Navigation;<file_sep>/objects/pickup.js import Thing from './thing.js'; import Vector from '../util/vector.js'; const GRAVITY = 0.5; const DRAW_RANGE = 100.0; const PICKUP_RANGE = 30.0; class Pickup extends Thing { constructor(options = {}) { options.assets = { highlight1: "assets/pickup.svg", highlight2: "assets/pickup.svg", sprite: options.asset } super(options); this.sleeping = false; this.velocity = options.velocity || new Vector(0, 0); this.iframes = 60; this.draw = 0; this.value = options.value; } tick() { super.tick(); this.sprite.rotation += 0.05; this.spin(this.sprites.highlight1, 1); this.spin(this.sprites.highlight2, -1); if (this.iframes > 0) { this.iframes -= 1; } else { this.pickup(); } if (this.sleeping) { return; } this.velocity.y += GRAVITY; this.position.x += this.velocity.x; this.position.y += this.velocity.y; let [hit, ground] = this.world.ground.enforce(this.position); if (hit) { this.position = ground; this.velocity.x = 0; this.velocity.y = 0; this.sleeping = true; } if (this.velocity.y < 0) { return; } let [snap, nav] = this.world.navigation.snap(this.position, 0); if (snap) { this.position = nav; this.velocity.x = 0; this.velocity.y = 0; this.sleeping = true; } } spin(sprite, direction) { sprite.rotation += 0.1 * direction; sprite.alpha = 0.3; sprite.scale.x = this.sprite.scale.x * 0.75 * (1.5 + (0.25 * Math.sin(sprite.rotation / 2))); sprite.scale.y = this.sprite.scale.y * 0.75 * (1.5 + (0.25 * Math.sin(sprite.rotation / 2))); } pickup() { let player = this.world.player; let towardPlayer = player.position.minus(this.position); let distance = towardPlayer.length(); if (distance > DRAW_RANGE && !this.draw) { return; } this.draw += 0.5; let direction = towardPlayer.normalize(); this.position.add(direction.multipliedBy(this.draw)); if (distance > PICKUP_RANGE) { return; } player.collect(this); this.remove(); } } export default Pickup; <file_sep>/util/array.js export function flatten(array, result = []) { for (var i = 0; i < array.length; i++) { const value = array[i]; if (Array.isArray(value)) { flatten(value, result); } else { result.push(value); } } return result; } export function sum(array) { return array.reduce((a, b) => a + b, 0); }<file_sep>/objects/thing.js class Thing { constructor(options = {}) { this.assets = options.assets || { sprite: options.asset }; this.position = options.position; this.scale = options.scale || 1; this.sprites = {}; } show(layer, group, world) { this.layer = layer; this.group = group; this.world = world; this.sprites = {} Object.keys(this.assets).forEach((name) => { let sprite = new PIXI.Sprite( PIXI.loader.resources[this.assets[name]].texture ) sprite.scale.x = 0.075 * this.scale; sprite.scale.y = 0.075 * this.scale; sprite.anchor.x = 0.5; sprite.anchor.y = 0.5; sprite.position.x = this.position.x; sprite.position.y = this.position.y; sprite.rotation = 2 * Math.random() * Math.PI; this.group.addChild(sprite); this.sprites[name] = sprite; }); this.sprite = this.sprites.sprite; this.tick(); } remove() { Object.keys(this.sprites).forEach((name) => { this.group.removeChild(this.sprites[name]); }); this.layer.remove(this); } tick() { Object.keys(this.sprites).forEach((name) => { this.sprites[name].position = this.position; }); } } export default Thing;<file_sep>/character/combat/weapons/claws.js import Melee from './melee.js' class Claws extends Melee { constructor(character, animations) { super(character, { animations: animations, minimumCharge: 0.0, damage: 40 }); } } export default Claws;<file_sep>/character/player.js import Character from './character.js'; import Climb from './movement/climb.js'; import Soar from './movement/soar.js'; import Fall from './movement/fall.js'; import LeapCombat from './combat/leap-combat.js'; import Sword from './combat/weapons/sword.js'; import Claws from './combat/weapons/claws.js'; import Pinecone from './combat/weapons/pinecone.js'; import Frames from './animation/frames.js'; import Vector from '../util/vector.js' import Debug from '../util/debug.js' const WALK_SPEED = 6; const JUMP_SPEED = -4; const GRAB_DISTANCE = 10; class Player extends Character { constructor(world, input) { super(world); this.movements = { climb: new Climb(this, world.navigation, world.ground), soar: new Soar(this, world.navigation, world.ground), fall: new Fall(this, world.ground) } this.movements.climb.activate(); this.animations = { stand: new Frames(this, ["assets/squirrel-standing.svg"], { scale: 1.2 }), soar: new Frames(this, ["assets/squirrel-running1.svg"], { scale: 1.2 }), fall: new Frames(this, ["assets/squirrel-running2.svg"], { scale: 1.2 }), run: new Frames(this, [ "assets/squirrel-running0.svg", "assets/squirrel-running1.svg", "assets/squirrel-running2.svg", "assets/squirrel-running3.svg", "assets/squirrel-running4.svg", ], { scale: 1.2, repeat: true }), swordCharge: new Frames(this, ["assets/squirrel-sword-charging.svg"], { scale: 1.2 }), swordAttack: new Frames(this, ["assets/squirrel-sword-attacking.svg"], { scale: 1.2 }), clawsAttack: new Frames(this, ["assets/squirrel-claws-attacking.svg"], { scale: 1.2 }), pineconeCharge: new Frames(this, [ "assets/squirrel-pinecone-charging0.svg", "assets/squirrel-pinecone-charging1.svg" ], { scale: 1.2, repeat: false }), } this.animations.stand.activate(); this.combat = new LeapCombat(this, { weapons: { sword: new Sword(this, { charging: this.animations.swordCharge, attacking: this.animations.swordAttack }), claws: new Claws(this, { attacking: this.animations.clawsAttack }), pinecone: new Pinecone(this, { charging: this.animations.pineconeCharge }), } }); this.input = input; this.world = world; this.world.player = this; this.acorns = 0; this.triggers = []; } tick() { super.tick(); this.movement.control(this.input); // this.stayInsideWorld(); this.jump(this.input); this.grab(this.input); this.attack(this.input); this.recover(); this.trigger(); Debug.log("player.position", this.position); Debug.log("player.velocity", this.velocity); Debug.log("player.health", this.combat.health); Debug.log("player.acorns", this.acorns); if (this.combat.enemies) { Debug.log("enemies", this.combat.enemies().filter((e) => !e.combat.dead).length); } } stayInsideWorld() { if (this.position.y <= 2500) { return; } this.position.x = 675 this.position.y = 1435; this.velocity = new Vector(0, 0); } jump(input) { if (this.movement != this.movements.climb) { return; } if (!input.jump) { return; } if (this.movement.cooldown > 0) { return; } this.velocity.x = (input.move.x * WALK_SPEED); this.velocity.y = (input.move.y * WALK_SPEED) + JUMP_SPEED; this.movements.soar.activate(); this.combat.arm(); } grab(input) { if (this.movement != this.movements.soar) { return; } if (input.jump && !this.movement.sliding) { return; } let [grabbed, position] = this.world.navigation.snap( this.position, GRAB_DISTANCE ); if (grabbed) { this.position = position; this.movements.climb.activate(); } } attack(input) { if (this.movement != this.movements.soar) { this.combat.disarm(); return; } if (this.combat.armed && input.jump) { let weapon = this.combat.weapons.claws; if (input.light) { weapon = this.combat.weapons.sword; } if (input.heavy) { weapon = this.combat.weapons.pinecone; } this.combat.attack(weapon); } else { this.combat.hold(); this.animations.soar.activate(); return; } } recover() { if (this.combat.health >= 0) { return; } this.combat.heal(); } hit() { if (this.movement == this.movements.attack) { return; } this.movements.fall.activate(); } collect(acorn) { this.acorns += acorn.value; } trigger() { this.triggers = this.world.triggers.filter((t) => { return t.aabb().contains(this.position); }); Debug.log("triggers", this.triggers.map((t) => { return t.id; })); } feeder() { return; let feeder = this.world.triggers.find("Feeder"); let feeding = feeder.aabb().contains(this.position); if (feeding) { this.world.fade.darken(); } else { this.world.fade.lighten(); } } } export default Player;<file_sep>/character/animation/animation.js class Animation { constructor(character, assets, options) { this.character = character; this.assets = assets; this.options = options || {}; } activate() { this.character.animation = this; Object.keys(this.character.animations).forEach((animationName) => { let animation = this.character.animations[animationName]; if (animation === this) { animation.show(); } else { animation.hide(); } }); } show() { if (!this.sprites) { return; } this.sprites[0].visible = true; } hide() { if (!this.sprites) { return; } this.sprites.forEach((s) => { s.visible = false }); } setup(group) { this.sprites = this.assets.map((asset) => { let sprite = new PIXI.Sprite( PIXI.loader.resources[asset].texture ) let scale = this.options.scale || 1.0; sprite.scale.x = 0.075 * scale; sprite.scale.y = 0.075 * scale; sprite.anchor.x = 0.5; sprite.anchor.y = 0.675; sprite.visible = false; group.addChild(sprite); return sprite; }); this.sprites[0].visible = true; } animate(progress) { Debug.log("Animation.animate()", "not implemented") } } export default Animation;<file_sep>/player/input.js import Vector from '../util/vector.js' import Debug from '../util/debug.js'; const STICK_RADIUS = 64; class TouchStick { constructor(detector) { this.detector = detector; this.touch = null; this.value = new Vector(0, 0); this.start = null; } handle(touches) { if (this.touch) { this.touch = touches.find((t) => t.identifier == this.touch.identifier); } if (!this.touch) { let touch = touches.find((t) => { return this.detector(t); }); if (touch) { this.start = new Vector(touch.pageX, touch.pageY); this.touch = touch; } } if (!this.touch) { this.present = false; this.value = new Vector(0, 0); return; } let point = new Vector(this.touch.pageX, this.touch.pageY); let offset = point.minus(this.start); let push = offset.length() / STICK_RADIUS; let direction = offset.normalized(); if (push > 1) { push = 1; } this.present = true; this.value = direction.multipliedBy(push); } } class Gamepad { constructor() { this.reset(); } reset() { this.left = { value: new Vector(0, 0) }; this.right = { value: new Vector(0, 0) }; this.a = false; this.b = false; this.x = false; this.y = false; this.l1 = false; this.l2 = false; this.r1 = false; this.r2 = false; this.status = "not connected"; } tick() { if (!navigator.getGamepads) { this.reset(); this.status = "not supported"; return; } let gamepad = navigator.getGamepads()[0]; if (!gamepad) { this.reset(); this.status = "not connected"; return; } // this.debug(gamepad); this.status = "connected"; this.left.value.x = gamepad.axes[0]; this.left.value.y = -gamepad.axes[1]; this.right.value.x = gamepad.axes[2]; this.right.value.y = -gamepad.axes[3]; this.a = gamepad.buttons[0].value; this.b = gamepad.buttons[1].value; this.x = gamepad.buttons[2].value; this.y = gamepad.buttons[3].value; this.l1 = gamepad.buttons[4].value; this.l2 = gamepad.buttons[6].value; this.r1 = gamepad.buttons[5].value; this.r2 = gamepad.buttons[7].value; } debug(gamepad) { for (var i = 0; i < gamepad.axes.length; i++) { Debug.log("axes[" + i + "]", gamepad.axes[i]); } for (var i = 0; i < gamepad.buttons.length; i++) { Debug.log("buttons[" + i + "]", gamepad.buttons[i].value); } } } class Input { constructor(app) { // setup this.app = app; app.view.addEventListener("touchstart", (e) => this.touch(e), false); app.view.addEventListener("touchmove", (e) => this.touch(e), false); app.view.addEventListener("touchend", (e) => this.touch(e), false); window.addEventListener("gamepadconnected", (e) => { }); window.addEventListener("gamepaddisconnected", (e) => { }); // touches this.touches = { left: new TouchStick((t) => { return t.pageX < window.innerWidth / 2 }), right: new TouchStick((t) => { return t.pageX > window.innerWidth / 2 }), } // gamepad this.gamepad = new Gamepad(); // outputs this.move = new Vector(0, 0); this.jump = false; this.light = false; this.heavy = false; } touch(event) { let touches = Array.prototype.slice.call(event.touches); this.touches.left.handle(touches); this.touches.right.handle(touches); } tick() { this.gamepad.tick(); this.move = this.touches.left.value.plus(this.gamepad.left.value); this.jump = this.touches.right.present || this.gamepad.a; this.light = this.touches.right.value.y < -0.5 || this.gamepad.r1; this.heavy = this.touches.right.value.y > 0.5 || this.gamepad.r2; Debug.log("input", { move: this.move, jump: this.jump, light: this.light, heavy: this.heavy, gamepad: this.gamepad.status }); } } export default Input;<file_sep>/character/animation/squish.js import Animation from './animation.js'; class Squish extends Animation { constructor(character, sprite, options) { super(character, [sprite], options); } animate(progress) { this.character.group.scale.y = 1 + (Math.sin(progress) * 0.1); } } export default Squish;<file_sep>/player/camera.js import Vector from '../util/vector.js' class Camera { constructor(app, player, world) { this.app = app; this.player = player; this.world = world; this.zoom = 1.0; this.position = new Vector(); } tick() { // zoom let zoom = 2.0 - (this.player.velocity.length() * 0.1); if (zoom > 2.0) { zoom = 2.0; } if (zoom < 1.0) { zoom = 1.0; } let zoomTrigger = this.player.triggers.find((t) => { return t.id.startsWith("zoom "); }); if (zoomTrigger) { zoom = parseFloat(zoomTrigger.id.split(" ")[1]) } this.zoom = (zoom * 0.01) + (this.zoom * 0.99); this.app.stage.scale.x = this.zoom; this.app.stage.scale.y = this.zoom; // pan let target = new Vector( -this.player.position.x, -this.player.position.y ); this.position.interpolate(target, 0.1); // bound let viewportSize = { width: window.innerWidth / this.zoom, height: window.innerHeight / this.zoom }; /* let worldSize = this.world.artwork.layers["0"].sprite.texture; // width and height let viewportSize = { width: window.innerWidth / this.zoom, height: window.innerHeight / this.zoom }; let xMin = -worldSize.width + (viewportSize.width / 2); let xMax = 0 - (viewportSize.width / 2); if (this.position.x < xMin) { this.position.x = xMin; } if (this.position.x > xMax) { this.position.x = xMax; } let yMin = -worldSize.height + (viewportSize.height / 2); if (this.position.y < yMin) { this.position.y = yMin; } */ // apply this.app.stage.x = (this.position.x * this.app.stage.scale.x) + (window.innerWidth / 2); this.app.stage.y = (this.position.y * this.app.stage.scale.y) + (window.innerHeight / 2); // render artwork this.world.artwork.render(this.position, viewportSize); // this.world.fade.center(this.position); } } export default Camera;<file_sep>/world/objects.js class Objects { constructor(world) { this.world = world; } show(app) { let group = new PIXI.Container(); this.group = group; app.stage.addChild(group); this.objects = []; } add(object) { object.show(this, this.group, this.world); this.objects.push(object); } remove(object) { this.objects = this.objects.filter((o) => o != object); } tick() { this.objects.forEach((o) => { o.tick(); }); } } export default Objects;<file_sep>/world/layer.js import Path from './path.js' import Link from './link.js' import Vector from '../util/vector.js' import Debug from '../util/debug.js' var measure = null; function parseColor(name) { if (name[0] == '#') { name = name.substr(1); if (name.length == 3) { name = name.replace(/[a-fA-F0-9]/ig, '$1$1'); } return parseInt(name, 16); } if (!measure) { measure = document.createElement("div"); } measure.style.color = name; document.body.appendChild(measure); const rgb = window.getComputedStyle(measure).color .match(/\d+/g) .map((a) => parseInt(a, 10)) document.body.removeChild(measure); return (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]; } class Layer { constructor() { this.doms = []; this.paths = []; } show(app) { let preamble = ` <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" viewBox="0 0 512 512" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5;"> `.replace(/\n/g, '').replace(/^ */g, ''); let postamble = '</svg>'; let uri = "data:image/svg+xml;utf8," + preamble + this.doms.map((d) => d.outerHTML).join("") + postamble; uri = uri.replace(/\n/g, ''); let sprite = new PIXI.Sprite( new PIXI.Texture.from(uri) ); this.sprite = sprite; app.stage.addChild(sprite); } scale(value) { this.sprite.scale.x = value; this.sprite.scale.y = value; } load(dom) { this.doms.push(dom); let domPaths = Array.prototype.slice.call( dom.getElementsByTagName("path") ); domPaths.forEach((domPath) => { var path = new Path( domPath.getAttribute("serif:id") || domPath.getAttribute("id") || domPath.parentNode.getAttribute("serif:id") || domPath.parentNode.getAttribute("id") ); var domLinks = domPath. getAttribute("d"). split(/(?=[A-Z])/); var previousPoint = new Vector(); domLinks.forEach((domLink) => { var command = domLink[0]; var data = domLink .substring(1) .split(/[, ]+/) .map(v => parseFloat(v)); if (command == "M") { var [x, y] = data; var point = new Vector(x, y); } else if (command == "C") { var [ c1x, c1y, c2x, c2y, x, y ] = data; var point = new Vector(x, y); path.links.push(new Link([ previousPoint, new Vector(c1x, c1y), new Vector(c2x, c2y), point ])); } else if (command == "L") { var [x, y] = data; var point = new Vector(x, y); var midpoint = point.minus(previousPoint); midpoint.multiplyBy(0.5); /* path.links.push(new Link([ previousPoint, midpoint, midpoint, point ])); */ } previousPoint = point; }); if (domPath.getAttribute("style")) { let pathStyle = domPath.getAttribute("style").split(";"); pathStyle.forEach((element) => { let [key, value] = element.split(':'); switch (key) { case "stroke-width": path.width = parseFloat(value); path.halfWidth = path.width / 2; break; } // path.style[key] = value; }); } this.paths.push(path); }); } } export default Layer;<file_sep>/world/path.js import { flatten, sum } from '../util/array.js' import AABB from '../util/aabb.js'; class Path { constructor(id) { this.id = id; this.links = []; this.width = 1; } splitDownTo(maxLength) { this.links = this.links.map((link) => { return link.splitDownTo(maxLength); }); this.links = flatten(this.links); } length() { return sum(this.links.map((l) => l.length)); } center() { return this.aabb().center; } aabb() { if (!this._aabb) { this._aabb = new AABB(); this.links.forEach((link) => { this._aabb.addPoints(link.points); }); } return this._aabb; } pointAtLength(length) { var point = null; for (var linkIndex = 0; linkIndex < this.links.length; linkIndex++) { var link = this.links[linkIndex]; if (length <= link.length) { return link.pointAtLength(length); } length -= link.length; } return this.links[this.links.length - 1].end; } } export default Path;<file_sep>/squirrel.js import Debug from './util/debug.js'; let app = new PIXI.Application({ width: 256, height: 256, backgroundColor: 0x62B5E2 }); app.renderer.autoResize = true; app.renderer.resize(window.innerWidth, window.innerHeight); document.body.appendChild(app.view); import World from './world/world.js'; import Player from './character/player.js'; import Input from './player/input.js'; import Camera from './player/camera.js'; PIXI.loader.add([ "assets/squirrel-standing.svg", "assets/squirrel-running0.svg", "assets/squirrel-running1.svg", "assets/squirrel-running2.svg", "assets/squirrel-running3.svg", "assets/squirrel-running4.svg", "assets/squirrel-pinecone-charging0.svg", "assets/squirrel-pinecone-charging1.svg", "assets/squirrel-sword-charging.svg", "assets/squirrel-sword-attacking.svg", "assets/squirrel-claws-attacking.svg", "assets/pinecone.svg", "assets/explosion.svg", "assets/snail-slug.svg", "assets/snail-slug-dead.svg", "assets/snail-slug-shell.svg", "assets/pigeon-flying0.svg", "assets/pigeon-flying1.svg", "assets/slash.svg", "assets/nom.svg", "assets/acorn.svg", "assets/pickup.svg", "assets/health-bar.svg", "assets/health-box.svg", "assets/fade.svg" ]).load(() => { let world = new World(); world.load(() => { let input = new Input(app); let player = new Player(world, input); let camera = new Camera(app, player, world); world.player = player; world.show(app, player); window.player = player; window.world = world; player.position = world.triggers.find("start").center(); let msAverage = 0; function time(fn) { let start = (new Date()).getTime(); fn(); let end = (new Date()).getTime(); let ms = end - start; msAverage = (0.9 * msAverage) + (0.1 * ms); Debug.log("ms", Math.round(msAverage)); } function render() { time(() => { world.tick(); input.tick(); camera.tick(); player.tick(); app.renderer.render(app.stage); requestAnimationFrame(render); }); } render(); Debug.log("startup complete"); }); }); document.addEventListener("DOMContentLoaded", () => { let welcome = document.querySelector("#welcome"); let dismiss = () => { welcome.style.display = 'none'; }; welcome.addEventListener("click", dismiss); welcome.addEventListener("touchstart", dismiss); // ---- function resetAllEnemies() { window.world.reset(); world.fade.firstRest = false; world.fade.menu.style.opacity = 0; } let rest = document.getElementById("rest"); rest.addEventListener("click", () => { resetAllEnemies(); }); rest.addEventListener("touchstart", () => { resetAllEnemies(); }); });<file_sep>/character/pigeon.js import Character from './character.js'; import Patrol from './movement/patrol.js'; import Direct from './movement/direct.js'; import Frames from './animation/frames.js'; import TouchCombat from './combat/touch-combat.js'; const SPEED = 2; const COMBAT_RANGE = 50.0; const ESCAPE_DISTANCE = 200.0; class Pigeon extends Character { constructor(world, path) { super(world, { acorns: Math.round(Math.random()) }); this.path = path; this.animation = new Frames(this, [ "assets/pigeon-flying0.svg", "assets/pigeon-flying1.svg", ], { scale: 1.5, repeat: true }); this.movements = { patrol: new Patrol(this, path, SPEED, { level: true }), escape: new Direct(this, SPEED * 3), attack: new Direct(this, SPEED), cruise: new Direct(this, SPEED), }; this.movements.patrol.activate(); this.combat = new TouchCombat(this, { health: 25, range: COMBAT_RANGE }); } tick() { super.tick(); if (this.combat.dead) { return; } let enemy = this.combat.closestEnemy; if (!enemy) { return; } if (this.combat.aggrivation > 0) { this.attack(enemy, this.movements.escape); } else if (this.combat.closestEnemyDistance > ESCAPE_DISTANCE) { // do nothing } else if (enemy.combat.vulnerable() && !enemy.combat.dead) { this.attack(enemy, this.movements.attack); } else { this.runAwayFrom(enemy); } } attack(enemy, movement) { movement.activate( enemy.position, () => { this.returnToPatrol(); } ) } runAwayFrom(enemy) { let runAway = this.position.minus(enemy.position).normalized().multipliedBy(ESCAPE_DISTANCE * 2); let runAwayTarget = this.position.plus(runAway); this.movements.escape.activate( runAwayTarget, () => { this.returnToPatrol(); } ); } returnToPatrol() { this.movements.cruise.activate( this.movements.patrol.point, () => { this.movements.patrol.activate(); } ); } } export default Pigeon; <file_sep>/character/movement/direct.js import Vector from '../../util/vector.js'; import Movement from './movement.js'; class Direct extends Movement { // Direct: move directly to a target constructor(character, speed) { super(character); this.speed = speed; } activate(target, onArrival) { super.activate(); this.target = target; let movement = target.minus(this.character.position); this.distance = movement.length(); this.direction = movement.normalized(); this.onArrival = onArrival; } tick() { this.character.position.x += this.direction.x * this.speed; this.character.position.y += this.direction.y * this.speed; let [hit, ground] = this.character.world.ground.enforce(this.character.position); if (hit) { this.character.position = ground; this.onArrival(); return; } this.distance -= this.speed; if (this.distance < 0 && !this.character.combat.dead) { this.onArrival(); return; } this.aim(this.direction); if (this.character.animation) { this.character.animation.animate(0.02 * this.speed); } } } export default Direct;<file_sep>/character/combat/weapons/melee.js import Weapon from './weapon.js'; import Effect from '../../../objects/effect.js'; const TRIGGER_RANGE = 50.0; const DAMAGE_RANGE = 75.0; const INVUNERABILITY_PERIOD = 40.0; class Melee extends Weapon { constructor(character, options) { super(character, options); this.minimumCharge = options.minimumCharge || 0.0; this.charge = 0; } activate() { super.activate(); this.charge += 1; if (this.ready()) { this.animations.attacking.activate(); } else { this.animations.charging.activate(); } } ready() { return (this.charge >= this.minimumCharge); } tick() { if (!this.ready()) { return; } this.fire(); } fire() { let combat = this.character.combat; // find enemies let triggers = combat.enemiesWithin(TRIGGER_RANGE, this.character.position); if (triggers.length == 0) { return; } let world = this.character.world; // do damage combat.enemies().forEach((enemy) => { if (enemy.combat.iframes > 0) { return; } if (enemy.combat.dead) { return; } let distance = enemy.position.minus(this.character.position).length(); if (distance < DAMAGE_RANGE) { world.objects.add(new Effect({ asset: "assets/slash.svg", position: enemy.position })); enemy.combat.hit(this.damage); combat.iframes = INVUNERABILITY_PERIOD; } }); if (!this.options.staysArmed) { combat.disarm(); } } deactivate() { super.deactivate(); this.charge = 0; } } export default Melee;<file_sep>/world/artwork.js import Tileset from './tiles/tileset.js' const PARALLAX_STRENGTH = 0.75 * 0.1; class Artwork { constructor() { this.layers = {}; } show(app, set) { let layerKeys = Object.keys(this.layers); layerKeys = layerKeys.map((k) => parseFloat(k)); layerKeys.sort((a, b) => a - b); layerKeys = layerKeys.map((k) => k.toString()); layerKeys.forEach((k) => { let layer = this.layers[k]; let index = parseFloat(k); let isBack = (index <= 0); let showBack = (set == 'back'); if (showBack != isBack) { return; } layer.show(app.stage); }); } load(svgData) { let id = svgData.getAttribute("serif:id"); let regex = /\[([+-][.\d]+)\]/; let parallax = 0; if (regex.test(id)) { parallax = parseFloat(regex.exec(id)[1]) * PARALLAX_STRENGTH; } let key = parallax.toString(); if (!this.layers[key]) { this.layers[key] = new Tileset(parallax); } this.layers[key].load(svgData); } render(position, viewport) { let tileCount = 0; let budget = { tilesRendered: 1, tilePaddingLoad: 0, tilePaddingUnload: 4 }; Object.keys(this.layers).forEach((index) => { let layer = this.layers[index]; layer.render(position, viewport, budget); tileCount += layer.tileCount; }); Debug.log("artwork.memory", tileCount + "MB"); } } export default Artwork;<file_sep>/world/triggers.js import Layer from './layer.js' import Vector from '../util/vector.js' class Triggers extends Layer { load(data) { super.load(data); } find(id) { return this.paths.find((p) => { return p.id == id; }); } filter(f) { return this.paths.filter(f); } } export default Triggers;
efe02e62eb18213201629f45a08d6a0b587cbf05
[ "Markdown", "JavaScript" ]
35
Markdown
jdthorne/squirrel
1d38e84006558dfebe27bb53034ae8b249097828
2acd52284e55db024397db6c9f267c454c73bc15
refs/heads/master
<file_sep>package main import ( _ "myLittleBear/routers" _"github.com/go-sql-driver/mysql" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "fmt" ) func init() { path := beego.AppConfig.String("mysqluser") + ":" + beego.AppConfig.String("mysqlpass") + "@tcp(" + beego.AppConfig.String("mysqlhost") + ":" + beego.AppConfig.String("mysqlport") + ")/" + beego.AppConfig.String("mysqldb") + "?charset=utf8" orm.RegisterDriver("mysql", orm.DRMySQL) maxIdle := 30 maxConn := 30 orm.RegisterDataBase("default", "mysql", path, maxIdle, maxConn) fmt.Println("****") } func main() { beego.SetStaticPath("/static", "static") beego.Run() } <file_sep>$(document).ready(function() { var isClick = true; var width = $(window).width; $(".navbar-toggler").click(function () { if (isClick) { $(".container").animate({height: 350}); // $(".ml-auto").show(); $(".ml-auto").css('display', 'flex'); $(".navbar-toggler").css({ "background": "url('/static/img/cross.svg')", "background-repeat": "no-repeat", "background-position": "center" }); isClick = false; } else { $(".container").animate({height: 80}); // $(".ml-auto").hide(); $(".ml-auto").css('display', 'none'); $(".navbar-toggler").css({ "background": "url('/static/img/threeBars.svg')", "background-repeat": "no-repeat", "background-position": "center" }); isClick = true; } }); $(window).resize(function(){ width = $(window).width(); if(width > 800){ // $(".container").animate('height',40); $('.container').css('height',80); // $(".ml-auto").show(); $(".ml-auto").css('display','flex') }else{ if(!isClick){ // $(".container").animate('height',350); $('.container').css('height',350); // $(".ml-auto").show(); $(".ml-auto").css('display','flex'); }else { // $(".ml-auto").hide(); $(".ml-auto").css('display','none'); } } }); // $(window).onload(function(){ // var oDiv = document.getElementById('home-sec-div'); // var oUl = document.getElementsByTagName('ul')[0]; // var Li = oUl.getElementsByTagName('li');//获取ul下的所有li // oUl.innerHTML = oUl.innerHTML+oUl.innerHTML;//li下的内容进行想加 // oUl.style.width = Li[0].offsetWidth*Li.length+'px';//ul的宽度等于每个li的宽度乘以所有li的长度 // var speed = 2 // // //主方法 // function move(){ // //如果左边横向滚动了长度一半之后,回到初始位置 // // if(oUl.offsetLeft<-oUl.offsetWidth/speed){ // oUl.style.left = '0' // } // //如果右边横向滚动的距离大于0 就让他的位置回到一半 // if(oUl.offsetLeft>0){ // oUl.style.left = -oUl.offsetWidth/speed+'px'; // } // //oUl.style.left = oUl.offsetLeft-2+'px';//进行左横向滚动 // oUl.style.left = oUl.offsetLeft+speed+'px';//进行右横向滚动 // } // //调用方法 // var timer = setInterval(move,30) // //鼠标指向的时候 暂停 // oDiv.onmouseover=function(){ // clearInterval(timer); // } // //鼠标离开之后 继续滚动 // oDiv.onmouseout=function(){ // timer = setInterval(move,30) // } // }); // window.onload=function(){ // var oDiv = document.getElementById('home-sec-div'); // var oUl = document.getElementsByTagName('ul')[0]; // var Li = oUl.getElementsByTagName('li');//获取ul下的所有li // oUl.innerHTML = oUl.innerHTML+oUl.innerHTML;//li下的内容进行想加 // oUl.style.width = Li[0].offsetWidth*Li.length+'px';//ul的宽度等于每个li的宽度乘以所有li的长度 // var speed = 2 // // //主方法 // function move(){ // //如果左边横向滚动了长度一半之后,回到初始位置 // // if(oUl.offsetLeft<-oUl.offsetWidth/speed){ // oUl.style.left = '0' // } // //如果右边横向滚动的距离大于0 就让他的位置回到一半 // if(oUl.offsetLeft>0){ // oUl.style.left = -oUl.offsetWidth/speed+'px'; // } // //oUl.style.left = oUl.offsetLeft-2+'px';//进行左横向滚动 // oUl.style.left = oUl.offsetLeft+speed+'px';//进行右横向滚动 // } // //调用方法 // var timer = setInterval(move,30) // //鼠标指向的时候 暂停 // oDiv.onmouseover=function(){ // clearInterval(timer); // } // //鼠标离开之后 继续滚动 // oDiv.onmouseout=function(){ // timer = setInterval(move,30) // } // } });<file_sep>package controllers import ( _"github.com/astaxie/beego" "fmt" "myLittleBear/models" "time" "myLittleBear/utils" //"encoding/json" ) type MainController struct { //beego.Controller BaseController } type User struct { Id string `json:"id"` Username string `json:"username"` } func (c *MainController) Get() { //c.Data["Website"] = "beego.me" //c.Data["Email"] = "<EMAIL>" //c.TplName = "index.tpl" c.TplName = "index.html" } func (c *MainController) LoginGet() { c.TplName = "login.html" } func (c *MainController) LoginPost() { //获取表单信息 username := c.GetString("user_name") password := c.GetString("password") repassword := c.GetString("repassword") fmt.Println(username, password, repassword) //注册之前先判断该用户名是否已经被注册,如果已经注册,返回错误 num,err := models.SelectUserByUserName(username) if err != nil { c.Data["json"] = map[string]interface{}{"code":0,"message":"查询错误"} c.ServeJSON() return } fmt.Println("num:",num) if num > 0 { c.Data["json"] = map[string]interface{}{"code":0,"message":"用户名已经存在"} c.ServeJSON() return } password = utils.MD5(password) fmt.Println("md5后:",password) user := models.User{ UserName:username, Password:<PASSWORD>, Status:"1", CreateTime:time.Now().Format("2006-01-02 15:04:05"), } _,err =models.InsertUser(user) if err != nil{ c.Data["json"] = map[string]interface{}{"code":0,"message":"注册失败"} }else{ c.Data["json"] = map[string]interface{}{"code":1,"message":"注册成功"} } c.ServeJSON() } // @Title test1 // @Description test1 // @Param id path string true "id" // @Success 200 {object} model.RespResult {"id":id} // @Failure 403 body is empty // @router /test1 [get] func (c *MainController) Test1() { var id = c.Ctx.Input.Param(":id") c.Data["json"] = map[string]interface{}{"id":id} c.ServeJSON() } // @Title test2 // @Description test2 // @Param id query string true "id" // @Param username query string true "username" // @Success 200 {object} model.RespResult {"id":id,"username":username} // @Failure 403 body is empty // @router /test2 [get] func (c *MainController) Test2() { var params = c.Ctx.Input.Params() id := params["id"] username := params["username"] fmt.Println("id:", id, "username:", username) //var user User = User{Id:"0",Username:"yang"} //err := json.Unmarshal(c.Ctx.Input.RequestBody,&user) //if err != nil { // c.Data["json"] = map[string]interface{}{"err":err} // c.ServeJSON() // return //} //c.Data["json"] = map[string]interface{}{"id":user.Id,"username":user.Username} //下面这样写是可以的 //id = c.GetString("id") //username = c.GetString("username") id = c.Ctx.Input.Query("id") username = c.Ctx.Input.Query("username") fmt.Println(id,username) c.Data["json"] = map[string]interface{}{"id":id,"username":username} c.ServeJSON() } // @Title test3 // @Description test3 // @Param id query string true "id" // @Param username query string true "username" // @Success 200 {object} model.RespResult {"id":id,"username":username} // @Failure 403 body is empty // @router /test3 [get] func (c *MainController) Test3() { id := c.Ctx.Input.Query("id") username := c.Ctx.Input.Query("username") fmt.Println(id,username) c.Data["json"] = map[string]interface{}{"id":id,"username":username} c.ServeJSON() }<file_sep>package routers import ( "myLittleBear/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{},"get:Get") beego.Router("/login",&controllers.MainController{},"get:LoginGet;post:LoginPost") ns := beego.NewNamespace("/v1", beego.NSNamespace("/test1", beego.NSInclude( &controllers.MainController{}, ), ), beego.NSNamespace("/test2", beego.NSInclude( &controllers.MainController{}, ), ), beego.NSNamespace("/test3", beego.NSInclude( &controllers.MainController{}, ), ), ) beego.AddNamespace(ns) } <file_sep>package models import ( "github.com/astaxie/beego/orm" "fmt" ) type User struct { Id int `orm:"column(id);pk;auto"json:"id" description:"主键"` UserName string `orm:"column(user_name);"json:"user_name" description:"用户名"` Password string `orm:"column(password);"json:"password" description:"密码"` Status string `orm:"column(status);"json:"status" description:"状态"` CreateTime string `orm:"column(create_time);"json:"create_time" description:"创建注册时间"` } func init() { orm.RegisterModel(new(User)) } func (r *User) TableName() string { return "users" } func InsertUser(user User)(string, error) { o := orm.NewOrm() err := o.Begin() //num,err := SelectUserById(user.Id) //if err == nil && num > 0 { // return "已存在该用户", nil //} id, err := o.Insert(&user) if err != nil { err = o.Rollback() return "插入失败", err } fmt.Println("id:",id) err = o.Commit() return "插入成功", nil } func SelectUserById(id int)(int64, error) { o:=orm.NewOrm() num,err := o.Raw("select * from users where id=?", id).QueryRows() fmt.Println(num) if err != nil { fmt.Println("查询失败:",err) return 0, err } return num, nil } func SelectUserByUserName(user_name string)(int64, error) { o:=orm.NewOrm() var maps []orm.Params num,err := o.Raw("select * from users where user_name=?", user_name).Values(&maps) fmt.Println(num) if err != nil { fmt.Println("查询失败:",err) return 0, err } return num, nil }
114239a64f65824306311aaadb53b75420e8eeb2
[ "JavaScript", "Go" ]
5
Go
chengpi/myLittleBear
dfa1fc6704718acd91d67e9125385e457568298d
ee45147a75353ea7362f317c7e222266326a24fc
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; namespace Sharpmon { /// <summary> /// Attack class /// --> setTheSelfSharpmon() and setTheEnemy() methods must be initialized before to attack another sharpmon. /// </summary> public class Attack : Effect { public Sharpmon TheEnemy { get; set; } public Sharpmon SelfSharpmon { get; set; } public Attack(string name, int damage, PropertieIsActivated damageIsActivated, int power, PropertieIsActivated powerIsActivated, PropertieEvolution powerEvolution, Target powerTarget, int defense, PropertieIsActivated defenseIsActivated, PropertieEvolution defenseEvolution, Target defenseTarget, int dodge, PropertieIsActivated dodgeActivated, PropertieEvolution dodgeEvolution, Target dodgeTarget, int accuracy, PropertieIsActivated accuracyIsActivated, PropertieEvolution accuracyEvolution, Target accuracyTarget, int speed, PropertieIsActivated speedIsActivated, PropertieEvolution speedEvolution, Target speedTarget) { Name = name; Damage = damage; DamageIsActivated = damageIsActivated; Power = power; PowerIsActivated = powerIsActivated; PowerTarget = powerTarget; PowerEvolution = powerEvolution; Defense = defense; DefenseIsActivated = defenseIsActivated; DefenseTarget = defenseTarget; DefenseEvolution = defenseEvolution; Dodge = dodge; DodgeIsActivated = dodgeActivated; DodgeTarget = dodgeTarget; DodgeEvolution = dodgeEvolution; Accuracy = accuracy; AccuracyIsActivated = accuracyIsActivated; AccuracyTarget = accuracyTarget; AccuracyEvolution = accuracyEvolution; Speed = speed; SpeedIsActivated = speedIsActivated; SpeedTarget = speedTarget; SpeedEvolution = speedEvolution; } public void setTheEnemy(Sharpmon targetSharpmon) { TheEnemy = targetSharpmon; } public void setTheSelfSharpmon(Sharpmon selfSharpmon) { SelfSharpmon = selfSharpmon; } /// <summary> /// Check if float value get numbers under comma. /// </summary> /// <param name="value"></param> /// <returns></returns> private bool ValueIsPure(float value) { var intConv = (int)value; // = XX var floatConv = (float) intConv; // XX.0 var final = (value - floatConv); if (final == 0.0) { return true; } else { return false; } } public string GetAttackName() { return Name; } /// <summary> /// Attack method, /// Attack Formula: LauncherPower * Damage / TargetDefense /// Dodge Formula: (PlayerSharpmon Acc / (PlayerSharpmon Acc + EnemySharpmon Dodge)) + 0.1% chance /// </summary> public void LaunchAttack() { if (DamageIsActivated == PropertieIsActivated.YES) { int result; //final result var probaDodge = (float) ((SelfSharpmon.GetAccuracy()/(SelfSharpmon.GetAccuracy() + TheEnemy.GetDodge())) + 0.1); var tmpResult = (Power*Damage)/TheEnemy.GetDefense() + 1; result = tmpResult; Console.Beep(); //Beep sound TheEnemy.ReduceHp(result); if (SelfSharpmon.GetExperience() == 10) { Console.WriteLine("This sharpmon Level Up !"); SelfSharpmon.IncrementLevel(); SelfSharpmon.ClearExperience(); } } if (PowerIsActivated == PropertieIsActivated.YES) { if (PowerEvolution == PropertieEvolution.DOWN) { if (PowerTarget == Target.ENEMY) { TheEnemy.ReducePower(1); Console.WriteLine("This sharpmon reduced -1 Power to her enemy."); } else if (PowerTarget == Target.SELF) { SelfSharpmon.ReducePower(1); Console.WriteLine("This sharpmon lost -1 Power."); } } else if (PowerEvolution == PropertieEvolution.UP) { if (PowerTarget == Target.ENEMY) { TheEnemy.AddPower(1); Console.WriteLine("This sharpmon win +1 Power to her enemy."); } else if (PowerTarget == Target.SELF) { SelfSharpmon.AddPower(1); Console.WriteLine("This sharpmon win +1 Power."); } } } if (DefenseIsActivated == PropertieIsActivated.YES) { if (DefenseEvolution == PropertieEvolution.DOWN) { if (DefenseTarget == Target.ENEMY) { TheEnemy.ReduceDefense(1); Console.WriteLine("This sharpmon reduced -1 Defense to her enemy."); } else if (DefenseTarget == Target.SELF) { SelfSharpmon.ReduceDefense(1); Console.WriteLine("This sharpmon lost -1 Defense."); } } else if (DefenseEvolution == PropertieEvolution.UP) { if (DefenseTarget == Target.ENEMY) { TheEnemy.AddDefense(1); Console.WriteLine("This sharpmon win +1 Defense to her enemy."); } else if (DefenseTarget == Target.SELF) { SelfSharpmon.AddDefense(1); Console.WriteLine("This sharpmon win +1 Defense."); } } } if (DodgeIsActivated == PropertieIsActivated.YES) { if (DodgeEvolution == PropertieEvolution.DOWN) { if (DodgeTarget == Target.ENEMY) { TheEnemy.ReduceDodge(1); Console.WriteLine("This sharpmon reduced -1 Dodge to her enemy."); } else if (DodgeTarget == Target.SELF) { SelfSharpmon.ReduceDodge(1); Console.WriteLine("This sharpmon lost -1 Dodge."); } } else if (DodgeEvolution == PropertieEvolution.UP) { if (DodgeTarget == Target.ENEMY) { TheEnemy.AddDodge(1); Console.WriteLine("This sharpmon win +1 Dodge to her enemy."); } else if (DodgeTarget == Target.SELF) { SelfSharpmon.AddDodge(1); Console.WriteLine("This sharpmon win +1 Dodge."); } } } if (AccuracyIsActivated == PropertieIsActivated.YES) { if (AccuracyEvolution == PropertieEvolution.DOWN) { if (AccuracyTarget == Target.ENEMY) { TheEnemy.ReduceAccuracy(1); Console.WriteLine("This sharpmon reduced -1 Accuracy to her enemy."); } else if (AccuracyTarget == Target.SELF) { SelfSharpmon.ReduceAccuracy(1); Console.WriteLine("This sharpmon lost -1 Accuracy."); } } else if (AccuracyEvolution == PropertieEvolution.UP) { if (AccuracyTarget == Target.ENEMY) { TheEnemy.AddAccuracy(1); Console.WriteLine("This sharpmon win +1 Accuracy to her enemy."); } else if (AccuracyTarget == Target.SELF) { SelfSharpmon.AddAccuracy(1); Console.WriteLine("This sharpmon win +1 Accuracy."); } } } if (SpeedIsActivated == PropertieIsActivated.YES) { if (SpeedEvolution == PropertieEvolution.DOWN) { if (SpeedTarget == Target.ENEMY) { TheEnemy.ReduceSpeed(1); Console.WriteLine("This sharpmon reduced -1 Speed to her enemy."); } else if (SpeedTarget == Target.SELF) { SelfSharpmon.ReduceSpeed(1); Console.WriteLine("This sharpmon lost -1 Speed."); } } else if (SpeedEvolution == PropertieEvolution.UP) { if (SpeedTarget == Target.ENEMY) { TheEnemy.AddSpeed(1); Console.WriteLine("This sharpmon win +1 Speed to her enemy."); } else if (SpeedTarget == Target.SELF) { SelfSharpmon.AddSpeed(1); Console.WriteLine("This sharpmon win +1 Speed."); } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { /* - Name - Level (start at 1) - Experience (start at 0) - HP & MaxHP : Current and maximum Health Points - Power & BasePower: Current and base (beginning of the fight) power. o The more power the sharpmon has, the more damage it does per attack. - Defense & BaseDefense: Same as power, but for defense o The more defense the sharpmon has, the less damage it takes per attack. - Dodge & BaseDodge: Same as power, but for dodge o The more dodge the sharpmon has, the more it can dodge attacks. - Accuracy & BaseAccuracy: Same as power, but for accuracy o The more accuracy the sharpmon has, the less it can miss attacks. - speed: Determines the playing order in fight - A List of Attacks (described below) */ public class Sharpmon { protected String Name = ""; protected int Level = 1; protected int Experience = 1; //HP & MaxHP protected int HP = 0; protected int BaseHP = 0; //Power & BasePower protected int Power = 0; protected int BasePower = 0; //Defense & BaseDefense protected int Defense = 0; protected int BaseDefense = 0; //Dodge & BaseDodge protected int Dodge = 0; protected int BaseDodge = 0; //Accuracy & BaseAccuracy protected int Accuracy = 0; protected int BaseAccuracy = 0; //speed protected int Speed = 0; //Sharpmon Attacks list public List<Attack> Attacks = new List<Attack>(); public Sharpmon() { } public virtual Sharpmon Clone() { var copy = (Sharpmon)MemberwiseClone(); return copy; } public void InitializeProperties(string sharpmonName, int maximumHp, int initialPower, int initialDefense, int initialDodge, int initialAccuracy, int speed) { Name = sharpmonName; if (maximumHp <= 0) { HP = 5; } else { BaseHP = maximumHp; HP = maximumHp; } if (initialPower <= 0) { Power = 1; } else { BasePower = initialPower; Power = initialPower; } if (initialDefense <= 0) { Defense = 1; } else { BaseDefense = initialDefense; Defense = initialDefense; } if (initialDodge <= 0) { Dodge = 1; } else { BaseDodge = initialDodge; Dodge = initialDodge; } if (initialAccuracy <= 0) { Accuracy = 1; } else { BaseAccuracy = initialAccuracy; Accuracy = initialAccuracy; } this.Speed = speed; } public void RestoreProperties() { this.HP = this.BaseHP; this.Power = this.BasePower; this.Defense = this.BaseDefense; this.Dodge = this.BaseDodge; this.Accuracy = this.BaseAccuracy; } public String GetName() { return Name; } public void SetName(string newName) { Name = newName; } public int GetExperience() { return Experience; } public void AddExperience(int value) { Experience += value; } public void ClearExperience() { Experience = 1; } public void setExperience(int exp) { Experience = exp; } public int GetBaseHp() { return BaseHP; } public void AddMaxHp(int value) { BaseHP += value; } public int GetHp() { return HP; } public void AddHp(int value) { HP += value; } public void ReduceHp(int value) { HP -= value; } public void RestoreHp() { HP = BaseHP; } public int GetBasePower() { return BasePower; } public void AddBasePower(int value) { BasePower += value; } public int GetPower() { return Power; } public void ReducePower(int value) { Power -= value; } public void AddPower(int value) { Power += value; } public void RestorePower() { Power = BasePower; } public int GetBaseDefense() { return BaseDefense; } public void AddBaseDefense(int value) { BaseDefense += value; } public int GetDefense() { return Defense; } public void ReduceDefense(int value) { Defense -= value; } public void AddDefense(int value) { Defense += value; } public void RestoreDefense() { Power = BasePower; } public int GetBaseDodge() { return BaseDodge; } public void AddBaseDodge(int value) { BaseDodge += value; } public int GetDodge() { return Dodge; } public void ReduceDodge(int value) { Dodge -= value; } public void AddDodge(int value) { Dodge += value; } public void RestoreDodge() { Dodge = BaseDodge; } public int GetBaseAccuracy() { return BaseAccuracy; } public void AddBaseAccuracy(int value) { BaseAccuracy += value; } public int GetAccuracy() { return Accuracy; } public void ReduceAccuracy(int value) { Accuracy -= value; } public void AddAccuracy(int value) { Accuracy += value; } public void RestoreAccuracy() { Accuracy = BaseAccuracy; } public int GetSpeed() { return Speed; } public void ReduceSpeed(int value) { Speed -= value; } public void AddSpeed(int value) { Speed += value; } public int getLevel() { return Level; } public void IncrementLevel() { Level += 1; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { public class Items { //All Items public List<Item> All = new List<Item>(); public Items() { All.Add(new Item("Potion",100, "Adds 5 HP to the current player’s Sharpmon.",5,0,0,0,0,0,0, null)); All.Add(new Item("Super potion", 300, "Adds 10 HP to the current player’s Sharpmon.", 10, 0, 0, 0, 0, 0, 0, null)); All.Add(new Item("Rare Candy", 700, "Adds one level to the current player’s Sharpmon.", 0, 0, 0, 0, 0, 0, 1, null)); All.Add(new Item("Leppa Berry", 800, "Adds 12 HP to the current player’s Sharpmon.", 12, 0, 0, 0, 0, 0, 0, null)); All.Add(new Item("Blue Berry", 500, "Adds 3 defense to the current player’s Sharpmon.", 0, 0, 3, 0, 0, 0, 1, null)); } /// <summary> /// Allow to get the current sharpmon /// </summary> /// <param name="Target"></param> public void setTarget(Sharpmon Target) { foreach (var item in All) { item.setTarget(Target); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { public class Item { protected Sharpmon Target; public string Name { get; } public int Price { get; } public int SellPrice { get; } public String Description { get; } protected int Hp = 0; protected int Power = 0; protected int Defense = 0; protected int Dodge = 0; protected int Accuracy = 0; protected int Speed = 0; protected int Experience = 0; public Item(string _name, int _price, string _description, int _hp, int _power, int _defense, int _dodge, int _accuracy, int _speed, int _experience, Sharpmon _target) { Name = _name; Price = _price; SellPrice = Price/2; Description = _description; Hp = _hp; Power = _power; Defense = _defense; Dodge = _dodge; Accuracy = _accuracy; Speed = _speed; Experience = _experience; Target = _target; } public void setTarget(Sharpmon target) { Target = target; } public void Use() { if (Hp > 0) { if (Target.GetHp() + Hp > Target.GetBaseHp()) { int val = Target.GetBaseHp() - Target.GetHp(); Target.AddHp(val); } } if (Power > 0) { Target.AddPower(Power); } if (Defense > 0) { Target.AddDefense(Defense); } if (Dodge > 0) { Target.AddDodge(Dodge); } if (Accuracy > 0) { Target.AddAccuracy(Accuracy); } if (Speed > 0) { Target.AddSpeed(Speed); } if (Experience > 0) { Target.AddExperience(Experience); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { class Sharpvidia : Sharpmon { public Sharpvidia() { InitializeProperties("Sharpvidia", 11, 3, 2, 2, 1, 2); Attacks.Add(new Attack("Pound", 2, Effect.PropertieIsActivated.YES, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); Attacks.Add(new Attack("Super Pound", 3, Effect.PropertieIsActivated.YES, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); Attacks.Add(new Attack("Shell", 0, Effect.PropertieIsActivated.NO, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 1, Effect.PropertieIsActivated.YES, Effect.PropertieEvolution.UP, Effect.Target.SELF, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { public class Sharpmender : Sharpmon { public Sharpmender() { InitializeProperties("Sharpmender", 10, 1, 1, 1, 2, 1); Attacks.Add(new Attack("Scratch", 3, Effect.PropertieIsActivated.YES, 0,Effect.PropertieIsActivated.NO,Effect.PropertieEvolution.NULL,Effect.Target.NULL, 0,Effect.PropertieIsActivated.NO,Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0,Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0,Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0,Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); Attacks.Add(new Attack("Grawl", 0, Effect.PropertieIsActivated.NO, 1, Effect.PropertieIsActivated.YES, Effect.PropertieEvolution.UP, Effect.Target.SELF, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mime; using System.Text; using System.Threading.Tasks; namespace Sharpmon { class Program { static void Main(string[] args) { Game myGame = new Game(); // Game Welcoming.. myGame.Welcome(); // Game Start.. myGame.Start(); // Choose first sharpmon.. myGame.FirstSharpmon(); // Game loop RUNNING.. while (true) { myGame.Update(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { class Sharpitle : Sharpmon { public Sharpitle() { InitializeProperties("Sharpitle", 11, 1, 2, 2, 1, 2); Attacks.Add(new Attack("Pound", 2, Effect.PropertieIsActivated.YES, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); Attacks.Add(new Attack("Shell", 0, Effect.PropertieIsActivated.NO, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 1, Effect.PropertieIsActivated.YES, Effect.PropertieEvolution.UP, Effect.Target.SELF, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { public class AllSharpmons { public static List<Sharpmon> Sharpmons = new List<Sharpmon>(); } } <file_sep># Sharpmon a C# console game inspired by Pokémon. <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Media; using System.Net.Mime; using System.Security.Policy; using System.Text; using System.Threading.Tasks; using System.Timers; namespace Sharpmon { class Game { public player thePlayer = new player(); public Items GameItems = new Items(); private System.Media.SoundPlayer Music = new SoundPlayer(); public void Init() { AllSharpmons.Sharpmons.Add(new Sharpasaur()); AllSharpmons.Sharpmons.Add(new Sharpitle()); AllSharpmons.Sharpmons.Add(new Sharpmender()); AllSharpmons.Sharpmons.Add(new Sharpvidia()); AllSharpmons.Sharpmons.Add(new Sharpidgey()); } public void Welcome() { //Console.BackgroundColor = ConsoleColor.DarkYellow; Music.SoundLocation = Directory.GetCurrentDirectory() + @"\music.wav"; Music.PlayLooping(); Console.WriteLine("\n"); Console.WriteLine("---------------------------"); Console.WriteLine(" SHARPMON "); Console.WriteLine("---------------------------"); } public void Start() { //Initialize some datas.. Init(); //------ int choice = 0; while (choice <= 0 || choice >= 3) { Console.WriteLine("Enter your name to start or exit:"); Console.WriteLine("1 - Enter my name"); Console.WriteLine("2 - Exit"); //We handle exception if choice is out of range try { choice = Convert.ToInt32(Console.ReadLine()); } catch (Exception) { Start(); } Console.Clear(); } switch (choice) { case 1: thePlayer.setName(); break; case 2: Environment.Exit(0); break; default: Start(); break; } } public void FirstSharpmon() { //method which allow to choose our first sharpmon int choice; Console.Clear(); Console.WriteLine("----------------------------------"); Console.WriteLine(" FIRST SHARPMON "); Console.WriteLine("----------------------------------"); Console.WriteLine(thePlayer.GetName() + ", Choose your first sharpmon before get starting: "); Console.WriteLine("0: Sharpmender "); Console.WriteLine("1: Sharpasaur "); Console.WriteLine("2: Sharpitle"); //We handle exception if choice is out of range try { choice = Convert.ToInt32(Console.ReadLine()); switch (choice) { case 0: thePlayer.AddSharpmon(new Sharpmender()); break; case 1: thePlayer.AddSharpmon(new Sharpasaur()); break; case 2: thePlayer.AddSharpmon(new Sharpitle()); break; default: FirstSharpmon(); break; } } catch (Exception) { FirstSharpmon(); } Console.WriteLine("You get "+thePlayer.Sharpdex[0].GetName()+"."); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } public void IntoTheWild() { Console.WriteLine("---------------------------------------"); Console.WriteLine(" SEARCHING A SHARPMON... "); Console.WriteLine("---------------------------------------"); Console.WriteLine("Press any key to find a sharpmon.. "); Console.ReadLine(); int val; Random rand = new Random(); val = rand.Next(0, AllSharpmons.Sharpmons.Count); thePlayer.EnemySharpmon = AllSharpmons.Sharpmons[val]; Console.WriteLine("you met a "+AllSharpmons.Sharpmons[val].GetName()+" !"); Console.WriteLine("Choose your sharpmon from your sharpdex: "); for (int i = 0; i < thePlayer.Sharpdex.Count; i++) { Console.WriteLine(i+": "+thePlayer.Sharpdex[i].GetName()); } try { int sharpchoice; sharpchoice = Convert.ToInt32(Console.ReadLine()); if ((sharpchoice >= 0) && (sharpchoice < thePlayer.Sharpdex.Count)) { thePlayer.SetCurrentSharpmon(sharpchoice); GameItems.setTarget(thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()]); } else { Console.WriteLine(AllSharpmons.Sharpmons[val].GetName() + " fled !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); IntoTheWild(); } } catch (Exception) { Console.WriteLine(AllSharpmons.Sharpmons[val].GetName()+" fled !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); IntoTheWild(); } Console.WriteLine("You chose "+thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetName()); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); //Launch fight ! FightSystem(); } public void FightSystem() { Console.Clear(); //If isPlayer = false so it's the enemy sharpmon turn bool isPlayer = false; while ((thePlayer.EnemySharpmon.GetHp() >= 1) && (thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetHp() >=1)) { Console.Clear(); Console.WriteLine("-------------------------"); Console.WriteLine(" FIGHT ! "); Console.WriteLine("-------------------------"); Console.WriteLine("| "+thePlayer.EnemySharpmon.GetName()+" |"); Console.WriteLine("| HP: "+thePlayer.EnemySharpmon.GetHp()+"/"+thePlayer.EnemySharpmon.GetBaseHp() + " Lvl: " + thePlayer.EnemySharpmon.GetExperience()+"|"); Console.WriteLine("| Pow: " + thePlayer.EnemySharpmon.GetPower() + " Def: " + thePlayer.EnemySharpmon.GetDefense() + "|"); Console.WriteLine("| Acc: " + thePlayer.EnemySharpmon.GetAccuracy() + " Dod: " + thePlayer.EnemySharpmon.GetDodge() + "|"); Console.WriteLine("+-----------------------+"); Console.WriteLine("| " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetName() + " |"); Console.WriteLine("| HP: " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetHp() + "/" + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetBaseHp() + " Lvl: " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetExperience() + "|"); Console.WriteLine("| Pow: " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetPower() + " Def: " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetDefense() + "|"); Console.WriteLine("| Acc: " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetAccuracy() + " Dod: " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetDodge() + "|"); Console.WriteLine("+-----------------------+"); if (isPlayer == false) //enemy turn { Console.WriteLine(thePlayer.EnemySharpmon.GetName()+" begin !"); int attackchose; Random rand = new Random(); attackchose = rand.Next(0, thePlayer.EnemySharpmon.Attacks.Count); thePlayer.EnemySharpmon.Attacks[attackchose].TheEnemy = thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()]; thePlayer.EnemySharpmon.Attacks[attackchose].SelfSharpmon = thePlayer.EnemySharpmon; thePlayer.EnemySharpmon.setExperience(thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetExperience()); //Set Enemy's Experience to player's experience. Console.WriteLine(thePlayer.EnemySharpmon.GetName()+" launch "+thePlayer.EnemySharpmon.Attacks[attackchose].GetAttackName()); Console.WriteLine("This sharpmon has attacked."); for (int i = 0; i < thePlayer.EnemySharpmon.Attacks[attackchose].getDamage(); i++) { thePlayer.EnemySharpmon.Attacks[attackchose].LaunchAttack(); } } else //your turn { Console.WriteLine("Your "+thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetName() + " begin !"); int Choice = 0; try { Console.WriteLine("What will you do ?"); Console.WriteLine("0: Attack"); Console.WriteLine("1: Change Sharpmon"); Console.WriteLine("2: Use Object"); Console.WriteLine("3: Capture"); Console.WriteLine("4: Run Away"); Choice = Convert.ToInt32(Console.ReadLine()); switch (Choice) { case 0: Console.WriteLine("Choose your attack: "); for (int i = 0; i < thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks.Count; i++) { Console.WriteLine(i + ": " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks[i].GetAttackName()); } int attackchose = -1; try { attackchose = Convert.ToInt32(Console.ReadLine()); if ((attackchose >= 0) && (attackchose < thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks.Count)) { thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks[attackchose].TheEnemy = thePlayer.EnemySharpmon; thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks[attackchose].SelfSharpmon = thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()]; for (int i = 0; i < thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks[attackchose].getDamage(); i++) { thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].Attacks[attackchose].LaunchAttack(); } } else { Console.WriteLine("You made an error !"); } } catch (Exception) { Console.WriteLine("You made an error !"); } Console.WriteLine(thePlayer.EnemySharpmon.GetName() + " launch " + thePlayer.EnemySharpmon.Attacks[attackchose].GetAttackName()); break; case 1: Console.WriteLine("Choose an other sharpmon: "); for (int i = 0; i < thePlayer.Sharpdex.Count; i++) { Console.WriteLine(i + ": " + thePlayer.Sharpdex[i].GetName()); } try { int sharpchoice; sharpchoice = Convert.ToInt32(Console.ReadLine()); if ((sharpchoice >= 0) && (sharpchoice < thePlayer.Sharpdex.Count)) { thePlayer.SetCurrentSharpmon(sharpchoice); GameItems.setTarget(thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()]); } else { Console.WriteLine("You made an error !"); } } catch (Exception) { Console.WriteLine("You made an error !"); IntoTheWild(); } Console.WriteLine("You chose " + thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetName()); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); break; case 2: if (thePlayer.Items.Count == 0) { Console.WriteLine("You have no Item !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); break; } Console.WriteLine("My Items List:"); for (int i = 0; i < thePlayer.Items.Count; i++) { Console.WriteLine(i + " - " + thePlayer.Items[i].Name+" Description: "+thePlayer.Items[i].Description); } int id; Console.WriteLine("Enter the Item Id:"); try { id = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(thePlayer.Items[id].Name + " is used !"); thePlayer.Items[id].Use(); thePlayer.Items.RemoveAt(id); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } catch (Exception) { Console.WriteLine("You made an error !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } break; case 3: //Capture //(Enemy MaxHP – HP) / 100 – 0.5 % chance float capture = ((float)thePlayer.EnemySharpmon.GetBaseHp() - (float)thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetHp()) / ((float) (100 - 0.5)); if (capture > 0.05) { Sharpmon copySharpmon = null; foreach (var sharp in thePlayer.Sharpdex.Where(sharp => sharp.GetName() == thePlayer.EnemySharpmon.GetName())) { copySharpmon = sharp; } thePlayer.Sharpdex.Add((thePlayer.EnemySharpmon).Clone()); Console.WriteLine("You had capture this sharpmon !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Menu(); } else { Console.WriteLine("You failed to capture this sharpmon."); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } break; case 4: //Run Away //PlayerSharpmon / (PlayerSharpmon + EnemySharpmon) % chance float runAway = (float)((float)(thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetSpeed())/ (float)(thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetSpeed() + thePlayer.EnemySharpmon.GetSpeed())); if (runAway > 0.5) { Console.WriteLine("you fled !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Menu(); } else { Console.WriteLine("you failed to run away."); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } break; default: break; } } catch (Exception) { Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } } Console.ReadLine(); //We change the player turn if (isPlayer == true) isPlayer = false; else isPlayer = true; } //If player loose if (thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].GetHp() <= 0) { Console.WriteLine("You lost the fight.."); Console.WriteLine("Press any key to continue.. "); thePlayer.EnemySharpmon = null; thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].RestoreProperties(); Console.ReadLine(); } else if(thePlayer.EnemySharpmon.GetHp() <= 0) //If computer loose { Console.WriteLine("You win the fight !"); Random rand = new Random(); Random rand2 = new Random(); int earnedMoney = rand.Next(100, 500); thePlayer.AddSharpdollars(earnedMoney); Console.WriteLine("You win +"+earnedMoney+" $"); int EnemyExp = thePlayer.EnemySharpmon.GetExperience(); int earnedExp = 1; thePlayer.Sharpdex[thePlayer.GetCurrentSharpmon()].AddExperience(earnedExp); Console.WriteLine("Your sharpmon win +" + earnedExp + " Experience(s)."); thePlayer.EnemySharpmon = null; Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); } } private void Shop() { Console.Clear(); Console.WriteLine("-------------------------"); Console.WriteLine(" SHOP "); Console.WriteLine("-------------------------"); Console.WriteLine("CREDITS: " + thePlayer.GetSharpdollars() + " $ \n\n"); Console.WriteLine("Catalog: \n"); for (int i = 0; i < GameItems.All.Count; i++) { Console.WriteLine(i+" - "+GameItems.All[i].Name+"\n Price: "+ GameItems.All[i].Price + " $ \n Description: " + GameItems.All[i].Description + "\n Sell Price: " + GameItems.All[i].SellPrice+" $ "); Console.WriteLine("\n"); } Console.WriteLine("-------------------------"); Console.WriteLine("1: Buy an Item"); Console.WriteLine("2: Sale an Item"); Console.WriteLine("3: Return to main menu"); try { int choice; choice = Convert.ToInt32(Console.ReadLine()); switch (choice) { case 1: int id; Console.WriteLine("Enter the product Id:"); try { id = Convert.ToInt32(Console.ReadLine()); if (thePlayer.GetSharpdollars() < GameItems.All[id].Price) { Console.WriteLine("You have not enough money to buy this Item !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Shop(); break; } thePlayer.ReduceSharpdollars(GameItems.All[id].Price); thePlayer.Items.Add(GameItems.All[id]); Console.WriteLine(GameItems.All[id].Name+ " is bought."); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Shop(); } catch (Exception) { Console.WriteLine("You made an error !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Shop(); break; } break; case 2: if (thePlayer.Items.Count == 0) { Console.WriteLine("You have no Item !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Shop(); break; } Console.WriteLine("My Items List:"); for (int i = 0; i < thePlayer.Items.Count; i++) { Console.WriteLine(i + " - " + thePlayer.Items[i].Name +"\n Sell Price: " + thePlayer.Items[i].SellPrice + " $ "); } int id2; Console.WriteLine("Enter the product Id:"); try { id2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(thePlayer.Items[id2].Name + " is sold."); thePlayer.AddSharpdollars(thePlayer.Items[id2].SellPrice); thePlayer.Items.RemoveAt(id2); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Shop(); } catch (Exception) { Console.WriteLine("You made an error !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Shop(); break; } break; case 3: Menu(); break; default: Shop(); break; } } catch (Exception) { Shop(); } } public void Centre() { int choice; Console.Clear(); Console.WriteLine("---------------------------------"); Console.WriteLine(" SHARPMON CENTER "); Console.WriteLine("---------------------------------\n"); for (int i = 0; i < thePlayer.Sharpdex.Count; i++) { Console.WriteLine(i+" - "+thePlayer.Sharpdex[i].GetName()+" HP:"+thePlayer.Sharpdex[i].GetHp()); } Console.WriteLine("\n"); Console.WriteLine("What do you want ?"); Console.WriteLine("0: Heal a sharpmon "); Console.WriteLine("1: Return to main menu "); try { choice = Convert.ToInt32(Console.ReadLine()); switch (choice) { case 0: for (int i = 0; i < thePlayer.Sharpdex.Count; i++) { thePlayer.Sharpdex[i].RestoreProperties(); } Console.WriteLine("All your sharpmons are healthy !"); Console.WriteLine("Press any key to continue.. "); Console.ReadLine(); Centre(); break; case 1: Menu(); break; default: Centre(); break; } } catch (Exception) { Menu(); } Console.ReadLine(); } private void Menu() { int choice; Console.Clear(); Console.WriteLine("-------------------------"); Console.WriteLine(" MENU "); Console.WriteLine("-------------------------"); Console.WriteLine("CREDITS: "+thePlayer.GetSharpdollars()+" $ \n"); Console.WriteLine("Hello " + thePlayer.GetName() + " !"); Console.WriteLine("Welcome in Sharpmon world!\n"); Console.WriteLine("Where do you want to go ?"); Console.WriteLine("0: Into the wild "); Console.WriteLine("1: In the shop"); Console.WriteLine("2: In the Sharpmon Center"); Console.WriteLine("3: Exit game"); //We handle exception if choice is out of range try { choice = Convert.ToInt32(Console.ReadLine()); switch (choice) { case 0: Console.Clear(); IntoTheWild(); break; case 1: Shop(); break; case 2: Centre(); break; case 3: Environment.Exit(0); break; default: Menu(); break; } } catch (Exception) { Menu(); } } public void Update() { Menu(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { /* - Name: His/Her name - A list of Sharpmons - A private property to select the Current Sharpmon - A number of Sharpdollars to buy items - A list of Items */ class player { //Player name private string Name = ""; //List of sharpmons public List<Sharpmon> Sharpdex = new List<Sharpmon>(); //Current sharpmon private int Current_Sharpmon = 0; public Sharpmon EnemySharpmon; //money private int Sharpdollars = 1000; //Items public List<Item> Items = new List<Item>(); //Constructor public player() { } //Set player name public void setName() { Console.Clear(); //We handle exception if choice is out of range try { Console.WriteLine("---------------------------"); Console.WriteLine(" PROFIL "); Console.WriteLine("---------------------------"); Console.WriteLine("Write your name here : "); Name = Console.ReadLine(); } catch (Exception) { setName(); } } //Get player name public String GetName() { return Name; } //Add new sharpmon into Sharpdex public void AddSharpmon(Sharpmon newSharpon) { Sharpdex.Add(newSharpon); } // Total sharpmons of player public int SharpmonCount() { return Sharpdex.Count(); } //Retrieve All sharpmons of player /*public List<Sharpmon> AllSharpmons() { List<Sharpmon> MySharpmons = new List<Sharpmon>(); MySharpmons = (from Asharpmon in Sharpdex select Asharpmon).ToList(); return MySharpmons; }*/ public int GetCurrentSharpmon() { return Current_Sharpmon; } public void SetCurrentSharpmon(int sharpmonIndex) { Current_Sharpmon = sharpmonIndex; } public int GetSharpdollars() { return Sharpdollars; } public void AddSharpdollars(int Addmoney) { Sharpdollars += Addmoney; } public void ReduceSharpdollars(int Addmoney) { Sharpdollars -= Addmoney; } //Add new Item into Items public void AddItem(Item newItem) { Items.Add(newItem); } // Total Items of player public int ItemsCount() { return Items.Count(); } //Retrieve All Items of player public List<Item> AllItems() { List<Item> MyItems = new List<Item>(); MyItems = (from AItem in Items select AItem).ToList(); return MyItems; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace Sharpmon { /// <summary> /// Effect class handle Attack properties. /// </summary> public class Effect { /// <summary> /// Allow to choose the target which will see her propertie modified. /// </summary> public enum Target { NULL, ENEMY, SELF }; /// <summary> /// Allow to choose the way the propertie will be modified. /// </summary> public enum PropertieEvolution { NULL, UP, DOWN }; /// <summary> /// Allow to activate the modification of a propertie. /// </summary> public enum PropertieIsActivated { YES, NO }; protected string Name; protected int Damage; protected int Power; protected int Defense; protected int Dodge; protected int Accuracy; protected int Speed; protected Target PowerTarget; protected Target DefenseTarget; protected Target DodgeTarget; protected Target AccuracyTarget; protected Target SpeedTarget; protected PropertieEvolution PowerEvolution; protected PropertieEvolution DefenseEvolution; protected PropertieEvolution DodgeEvolution; protected PropertieEvolution AccuracyEvolution; protected PropertieEvolution SpeedEvolution; protected PropertieIsActivated DamageIsActivated; protected PropertieIsActivated PowerIsActivated; protected PropertieIsActivated DefenseIsActivated; protected PropertieIsActivated DodgeIsActivated; protected PropertieIsActivated AccuracyIsActivated; protected PropertieIsActivated SpeedIsActivated; public Effect() { } public int getDamage() { return Damage; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sharpmon { class Sharpidgey : Sharpmon { public Sharpidgey() { InitializeProperties("Sharpidgey", 11, 2, 2, 2, 1, 2); Attacks.Add(new Attack("Peeck", 1, Effect.PropertieIsActivated.YES, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); Attacks.Add(new Attack("Gust", 2, Effect.PropertieIsActivated.YES, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); Attacks.Add(new Attack("Sand-Attack", 3, Effect.PropertieIsActivated.NO, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 1, Effect.PropertieIsActivated.YES, Effect.PropertieEvolution.UP, Effect.Target.SELF, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL, 0, Effect.PropertieIsActivated.NO, Effect.PropertieEvolution.NULL, Effect.Target.NULL)); } } }
349694fccf57ba8d078f825e52a9060b396a8ac2
[ "Markdown", "C#" ]
14
C#
aven03/Sharpmon
1e51104f68efd613c742088b970437e79d538535
dae3cb88625e378b8db7f90cfd4e73f543795b54
refs/heads/master
<repo_name>adriankelly/couch-recipe<file_sep>/src/app/recipes/recipe-list/recipe-list.component.ts import { Component, OnInit } from '@angular/core'; import { IRecipe } from '../recipe'; import { RecipeDetailsComponent } from '../recipe-details/recipe-details.component'; import { RecipeService } from '../recipe.service'; @Component({ moduleId: module.id, templateUrl: 'recipe-list.component.html' }) export class RecipeListComponent implements OnInit { recipes: IRecipe[] selectedRecipe: IRecipe rating: number constructor(private recipeService: RecipeService) { } ngOnInit() { this.getRecipeData() } getRecipeData() { this.recipeService .getRecipes() .subscribe((recipes: IRecipe[]) => { this.recipes = recipes.map((recipe) => { return recipe; }); }); } selectRecipe(recipe: IRecipe) { this.selectedRecipe = recipe } onNotify(starIndex: number) { this.rating = starIndex; } updateStar(recipe: IRecipe) { recipe.value.rating = this.rating; this.recipeService .updateRating(recipe) .subscribe(() => { this.getRecipeData() }) } } <file_sep>/src/app/recipes/recipe-details/recipe-details.component.ts import { Component, Input } from '@angular/core'; import { IRecipe } from '../recipe'; import { RecipeService } from '../recipe.service'; @Component({ selector: 'cr-recipe-details', moduleId: module.id, templateUrl: 'recipe-details.component.html' }) export class RecipeDetailsComponent { @Input() recipe: IRecipe; imageWidth: number = 500; imageMargin: number = 2; } <file_sep>/routes/api.js var express = require('express'); var router = express.Router(); // Connect to CouchDB var nano = require('nano')('http://ec2-54-152-93-18.compute-1.amazonaws.com:5984/'); var recipe = nano.db.use('recipe'); router.get('/recipe', function(req, res) { recipe.view('all_recipes', 'all', function(err, body) { if (!err) { res.json(body.rows); } }); }); router.get('/recipe/:id', function(req, res) { recipe.get(req.params.id, function(err, body) { res.status(200).json(body); }) }); router.put('/recipe/:id', function(req, res) { recipe.insert(req.body, function(err, body) { if(!err) { res.send({redirect: '/recipes'}); } else { console.log(err); } }) }); module.exports = router; <file_sep>/src/app/recipes/recipe.ts export interface IRecipe { id: string; rev: string; key: string; value: { name: string; description: string; ingredients: string[]; calories: string; carbos: string; fats: string; proteins: string; rating: number; } }<file_sep>/src/app/shared/star.component.ts import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'cr-star', moduleId: module.id, templateUrl: 'star.component.html', styleUrls: ['star.component.css'] }) export class StarComponent { private ratingRange: number[] = [1, 2, 3, 4, 5] @Input() starRating: number @Output() notify: EventEmitter<number> = new EventEmitter<number>(); onClick(starIndex: number) { this.notify.emit(starIndex + 1); } }<file_sep>/src/app/login/login.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './user'; @Component({ moduleId: module.id, templateUrl: 'login.component.html', styleUrls: ['login.component.css'] }) export class LoginComponent { public pageTitle: string = 'User Login'; constructor( private router: Router ) {} model = new User(); submitted = false; onSubmit() { this.submitted = true; } userLogin() { this.router.navigate(['/recipes']) } }<file_sep>/src/app/recipes/recipe.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { SharedModule } from '../shared/shared.module'; import { RecipeDetailsComponent } from './recipe-details/recipe-details.component'; import { RecipeListComponent } from './recipe-list/recipe-list.component'; import { RecipeService } from './recipe.service'; @NgModule({ declarations: [ RecipeDetailsComponent, RecipeListComponent ], imports: [ RouterModule.forChild([ { path: 'recipes', component: RecipeListComponent } ]), FormsModule, SharedModule ], providers: [ RecipeService ] }) export class RecipeModule {}<file_sep>/readme.md # Couch-Recipe - Example App [Couch-Recipe](http://ec2-54-152-93-18.compute-1.amazonaws.com/) __Goal__: Production of a web application demonstrating an example recipe review area. __Description__: The web app features a login page (doesn't actually log in or register users) and a recipes page. The recipes page retrieves recipe details and star ratings for each recipe from a CouchDB database. The user can update their ratings for each recipe and rating changes are stored in the database for later retrieval. Clicking on a recipe will display the description and ingredients of the recipe. Clicking on the rating stars will update the stars view and store this new rating in the database. __Constraints__: Must use Angular 2, Node.js/Express, and a NoSQL database management system - in this case CouchDB.
26296ba9245148afca1b020b60c55b08ef74f3dc
[ "JavaScript", "TypeScript", "Markdown" ]
8
TypeScript
adriankelly/couch-recipe
2896fae6f3eaf9f8c21e501f2fa330d3eab089a5
ddcf001f11c2d6c7912e2d68e5d1b145bdc2c975
refs/heads/master
<repo_name>RaufERK/react-firstStep<file_sep>/src/components/block1.jsx import React from 'react' import '../App.css' function Block1({ wolfsValue, counter }) { return ( <div className='block1'> {wolfsValue} | {counter} </div> ) } export default Block1
ae32c3b43028cbd3f8ad2c67f1b51aa18d4a982a
[ "JavaScript" ]
1
JavaScript
RaufERK/react-firstStep
9a586d5a0afde8b77a542218111b9094358ac762
76d76a2f9509edcc1417f863b305576889a5f5f0
refs/heads/main
<file_sep>#include <cs50.h> #include <stdio.h> int main(void) { long credit = get_long("Number: "); int result = 0; int digit_length = 0; long first_digit = 0; string answer; //1st validation... for (long n = 10; n < credit; n *= 100) { int temp1 = (((credit / n) % 10) * 2) % 10; int temp2 = (((credit / n) % 10) * 2) / 10; result += temp1 + temp2; digit_length++; } //2nd validation... for (long n = 1; n < credit; n *= 100) { result += (credit / n) % 10; digit_length++; } //printf("%i\n", digit_length); //get first digit first_digit = credit; for (int n = 0; n < digit_length - 2; n++) { first_digit /= 10; } //printf("%li\n", first_digit); //Final validation if (result % 10 == 0) { if (digit_length == 16 && first_digit >= 51 && first_digit <= 55) { answer = "MASTERCARD"; } else if (digit_length == 15 && first_digit >= 34 && first_digit <= 37) { if (first_digit == 34 || first_digit == 37) { answer = "AMEX"; } else { answer = "INVALID"; } } else if (digit_length >= 13 && digit_length <= 16 && first_digit >=40 && first_digit <= 49) { answer = "VISA"; } else { answer = "INVALID"; } } else { answer = "INVALID"; } printf("%s\n", answer); } <file_sep># CS50x-2021 My solutions for CS50x problem sets. <file_sep>#include <ctype.h> #include <cs50.h> #include <stdio.h> #include <string.h> #include <stdlib.h> const string ERROR = "Usage : ./caesar key"; int main(int argc, string argv[]) { string text; int key; if (argc != 2) { printf("%s", ERROR); return 1; } else { for (int i = 0; i < strlen(argv[1]); i++) { if (isdigit(argv[1][i]) == 0) { printf("%s", ERROR); return 1; } } } text = get_string("plaintext: "); key = atoi(argv[1]); string d_text = text; //(p + k) % 26 for (int i = 0; i < strlen(text); i++) { char c_dec = text[i]; if (isalpha(c_dec)) { if(islower(c_dec)) { d_text[i] = (((c_dec -'a') + key) % 26) + 'a'; } else { d_text[i] = (((c_dec -'A') + key) % 26) + 'A'; } } else { d_text[i] = text[i]; } } printf("ciphertext: %s\n", d_text); return 0; } <file_sep>#include <ctype.h> #include <cs50.h> #include <stdio.h> #include <string.h> #include <math.h> int main (void) { string text = get_string("Text: "); int letter = 0; double word = 1; int sentence = 0; for (int i = 0; text[i] != '\0'; i++) { char current = text[i]; if (isalpha(current)) { letter++; } else if (isspace(current)) { word++; } else if (current == '.' || current == '!' || current == '?') { sentence++; } } double L = letter / word * 100; double S = sentence / word * 100; double index = 0.0588 * L - 0.296 * S - 15.8; int result = (int) round(index); if (result >= 16) { printf("Grade 16+\n"); } else if (result < 1) { printf("Before Grade 1\n"); } else { printf("Grade %i\n", result); } }<file_sep>#include <ctype.h> #include <cs50.h> #include <stdio.h> #include <string.h> #include <stdlib.h> //VCHPRZGJNTLSKFBDQWAXEUYMOI const string ERROR = "Usage : ./caesar key"; int check_duplicate(int i, char c, char array[]); int main(int argc, string argv[]) { string text; string key; char used_key[26]; //check if key available and key is 26 char if (argc != 2 || strlen(argv[1]) != 26) { printf("%s", ERROR); return 1; } else { for (int i = 0; i < strlen(argv[1]); i++) { //check if key's char is alphabeltical if (isalpha(argv[1][i]) == 0) { printf("%s", ERROR); return 1; } //check for duplicates key char n = tolower(argv[1][i]); used_key[i] = n; if (check_duplicate(i, n, used_key) == 1) { printf("%s", ERROR); return 1; } } } //prepare text and key for substitution text = get_string("plaintext: "); key = argv[1]; string d_text = text; //SUBSTITUTE!!! //only alpabets, keep lower and uppercase of original message for (int i = 0; i < strlen(text); i++) { char current = (text[i]); //if character is alphabet, //convert to lowercase and get its placement, //then convert back to original case //if character is not alphabet, keep it as it is if (isalpha(current)) { int map = tolower(current) - 'a'; d_text[i] = key[map]; if (isupper(current)) { d_text[i] = toupper(d_text[i]); } else { d_text[i] = tolower(d_text[i]); } } else { d_text[i] = current; } } // print encryted message and exit program printf("ciphertext: %s", d_text); printf("\n"); return 0; } int check_duplicate(int i, char c, char array[]) { int n = 0; for (int j = 0; j < i ; j++) { if (c == array[j]) { n = 1; } } return n; }
c8c0ba4ddf51c938298a6355c1f555b96a023f47
[ "Markdown", "C" ]
5
C
Jachokoreto/CS50x-2021
5baf805926ca07d82d8969ee54392f24b6b37185
44b36622a11572b6bfbc4884e7225550a8db8b32
refs/heads/master
<repo_name>caiodomingues/medtech<file_sep>/server/src/app/models/Specialty.ts // import { // Entity, // PrimaryGeneratedColumn, // Column, // CreateDateColumn, // UpdateDateColumn, // ManyToOne, // JoinColumn, // OneToMany, // ManyToMany, // } from "typeorm"; // import { Doctor } from "./Doctor"; // @Entity("Specialty") // export class Specialty { // @PrimaryGeneratedColumn("uuid") // id: string; // @Column() // name: string; // @ManyToMany((type) => Doctor, (doctor) => doctor.specialties) // doctors: Doctor[]; // @CreateDateColumn() // created_at: Date; // @UpdateDateColumn() // updated_at: Date; // } <file_sep>/server/src/routes/doctor.routes.ts import { Router } from "express"; import { getRepository } from "typeorm"; import DoctorController from "../app/controllers/DoctorController"; import { Doctor } from "../app/models/Doctor"; const doctorRouter = Router(); doctorRouter.post("/", async (req, res) => { try { const { name, specialty } = req.body; const doctorController = new DoctorController(); const doctor = await doctorController.store({ name, specialty, }); return res.status(200).json(doctor); } catch (error) { res.status(400).json({ error: error.message }); } }); doctorRouter.get("/", async (req, res) => { const doctorRepo = getRepository("Doctor"); const doctor = await doctorRepo.find(); return res.status(200).json(doctor); }); doctorRouter.get("/:id", async (req, res) => { const doctorRepo = getRepository("Doctor"); const { id } = req.params; const doctor = await doctorRepo.findOne(id); return res.status(200).json(doctor); }); doctorRouter.put("/:id", async (req, res) => { const { name } = req.body; const doctorRepo = getRepository("Doctor"); const { id } = req.params; const doctorFind = await doctorRepo.findOne(id); const doctor = doctorRepo.create({ name, }); const respo = await doctorRepo.save({ ...doctorFind, ...doctor }); return res.status(200).json(respo); }); doctorRouter.delete("/:id", async (req, res) => { const doctorRepo = getRepository("Doctor"); const { id } = req.params; await doctorRepo.delete(id); return res.status(200).send(); }); export default doctorRouter; <file_sep>/server/src/app/models/Appointment.ts import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToOne, JoinColumn, Timestamp, } from "typeorm"; import { Patient } from "./Patient"; import { Doctor } from "./Doctor"; @Entity("Appointment") export class Appointment { @PrimaryGeneratedColumn("uuid") id: string; @Column() dateHour: string; @ManyToOne(() => Patient) @JoinColumn({ name: "patientId" }) patient: Patient; @Column() patientId: string; @ManyToOne(() => Doctor) @JoinColumn({ name: "doctorId" }) doctor: Doctor; @Column() doctorId: string; @CreateDateColumn() created_at: Date; @UpdateDateColumn() updated_at: Date; } <file_sep>/server/src/routes/patient.routes.ts import { Router } from "express"; import { getRepository } from "typeorm"; import PatientController from "../app/controllers/PatientController"; import { Patient } from "../app/models/Patient"; const patientRouter = Router(); patientRouter.post("/", async (req, res) => { try { const { name } = req.body; const patientController = new PatientController(); const patient = await patientController.store({ name, }); return res.status(200).json(patient); } catch (error) { res.status(400).json({ error: error.message }); } }); patientRouter.get("/", async (req, res) => { const patientRepo = getRepository("Patient"); const patient = await patientRepo.find(); return res.status(200).json(patient); }); patientRouter.get("/:id", async (req, res) => { const patientRepo = getRepository("Patient"); const { id } = req.params; const patient = await patientRepo.findOne(id); return res.status(200).json(patient); }); patientRouter.put("/:id", async (req, res) => { const { name } = req.body; const employeeRepo = getRepository("Patient"); const { id } = req.params; const patientFind = await employeeRepo.findOne(id); const patient = employeeRepo.create({ name, }); const respo = await employeeRepo.save({ ...patientFind, ...patient }); return res.status(200).json(respo); }); patientRouter.delete("/:id", async (req, res) => { const patientRepo = getRepository("Patient"); const { id } = req.params; await patientRepo.delete(id); return res.status(200).send(); }); export default patientRouter; <file_sep>/server/src/routes/specialty.routes.ts // import { Router } from "express"; // import { getRepository } from "typeorm"; // import SpecialtyController from "../app/controllers/SpecialtyController"; // import { Doctor } from "../app/models/Doctor"; // import { Specialty } from "../app/models/Specialty"; // const specialtyRouter = Router(); // specialtyRouter.post("/", async (req, res) => { // try { // const { name } = req.body; // const specialtyController = new SpecialtyController(); // const patient = await specialtyController.store({ // name, // }); // return res.status(200).json(patient); // } catch (error) { // res.status(400).json({ error: error.message }); // } // }); // specialtyRouter.get("/", async (req, res) => { // const patientRepo = getRepository("Specialty"); // const patient = await patientRepo.find(); // return res.status(200).json(patient); // }); // specialtyRouter.get("/:id", async (req, res) => { // const patientRepo = getRepository(Specialty); // const { id } = req.params; // const patient = await patientRepo.findOne(id); // return res.status(200).json(patient); // }); // specialtyRouter.put("/:id", async (req, res) => { // const { name } = req.body; // const employeeRepo = getRepository(Specialty); // const { id } = req.params; // const patientFind = await employeeRepo.findOne(id); // const patient = employeeRepo.create({ // name, // }); // const respo = await employeeRepo.save({ ...patientFind, ...patient }); // return res.status(200).json(respo); // }); // specialtyRouter.delete("/:id", async (req, res) => { // const patientRepo = getRepository(Specialty); // const { id } = req.params; // await patientRepo.delete(id); // return res.status(200).send(); // }); // export default specialtyRouter; <file_sep>/server/src/app/controllers/PatientController.ts import { getRepository } from "typeorm"; import { Patient } from "../models/Patient"; interface Request { name: string; } class PatientController { public async store({ name }: Request): Promise<Patient> { const PatientRepository = getRepository("Patient"); const patient = PatientRepository.create({ name, }); await PatientRepository.save(patient); return patient; } } export default PatientController; <file_sep>/server/src/app/controllers/SpecialtyController.ts // import { getRepository } from "typeorm"; // import { Specialty } from "../models/Specialty"; // interface Request { // name: string; // } // class SpecialtyController { // public async store({ name }: Request): Promise<Specialty> { // const SpecialtyRepository = getRepository(Specialty); // const specialty = SpecialtyRepository.create({ // name, // }); // await SpecialtyRepository.save(specialty); // return specialty; // } // } // export default SpecialtyController; <file_sep>/server/src/routes/appointment.routes.ts import { Router } from "express"; import { getRepository } from "typeorm"; import AppointmentController from "../app/controllers/AppointmentController"; import { Appointment } from "../app/models/Appointment"; const appointmentRouter = Router(); appointmentRouter.post("/", async (req, res) => { try { const { dateHour, patientId, doctorId } = req.body; const appointmentController = new AppointmentController(); const appointment = await appointmentController.store({ dateHour, patientId, doctorId, }); return res.status(200).json(appointment); } catch (error) { res.status(400).json({ error: error.message }); } }); appointmentRouter.get("/", async (req, res) => { const patientRepo = getRepository("Appointment"); const appointment = await patientRepo.find({ relations: ["patient", "doctor"], }); return res.status(200).json(appointment); }); appointmentRouter.get("/:id", async (req, res) => { const patientRepo = getRepository("Appointment"); const { id } = req.params; const appointment = await patientRepo.find({ relations: ["patient", "doctor"], where: { id: id, }, }); return res.status(200).json(appointment); }); appointmentRouter.put("/:id", async (req, res) => { const { dateHour, patientId, doctorId } = req.body; const appointmentRepo = getRepository("Appointment"); const { id } = req.params; const patientFind = await appointmentRepo.findOne(id); const appointment = appointmentRepo.create({ dateHour, patientId, doctorId, }); const respo = await appointmentRepo.save({ ...patientFind, ...appointment }); return res.status(200).json(respo); }); appointmentRouter.delete("/:id", async (req, res) => { const patientRepo = getRepository("Appointment"); const { id } = req.params; await patientRepo.delete(id); return res.status(200).send(); }); export default appointmentRouter; <file_sep>/web/src/pages/Reports/Create/styles.ts import styled from "styled-components"; export const CardContainer = styled.div` display: flex; flex-direction: column; justify-content: center; width: 750px; `; export const CardBottom = styled.div` display: flex; flex-direction: row-reverse; justify-content: space-between; align-items: center; margin-top: 16px; .column { display: flex; flex-direction: column; } p { max-width: 450px; font-size: 14px; } `; export const Select = styled.select` border: 1px solid rgba(0, 0, 0, 0.3); border-radius: 6px; padding: 8px 16px; font-size: 16px; min-width: 340px; width: 100%; &::placeholder { opacity: 0.5; } &:hover { border: 1px solid rgba(19, 105, 255, 0.5); } &:active, &:focus { border: 2px solid rgba(19, 105, 255, 0.85); } `; <file_sep>/server/src/routes/index.ts import { Router } from "express"; import patientRouter from "./patient.routes"; import doctorRouter from "./doctor.routes"; import appointmentsRouter from "./appointment.routes"; const routes = Router(); routes.use("/patients", patientRouter); routes.use("/doctors", doctorRouter); routes.use("/appointments", appointmentsRouter); export default routes; <file_sep>/README.md # MedTech This page was made for a college project; It's **not** mobile-friendly neither responsive (yet), sorry 😅. ## Instructions ```bash $ git clone https://github.com/caiodomingues/medtech.git $ cd medtech $ cd web $ yarn $ yarn start $ cd server $ yarn $ yarn dev:server ``` **Note:** For the correct usage of the project, it's necessary to take a look at database connection configuration file: `ormconfig.json`. Made by [caiodomingues](https://github.com/caiodomingues) and [thobiasvicente](https://github.com/thobiasvicente) <file_sep>/server/src/app/controllers/AppointmentController.ts import { getRepository } from "typeorm"; import { Appointment } from "../models/Appointment"; interface Request { dateHour: string; patientId: string; doctorId: string; } class AppointmentController { public async store({ dateHour, patientId, doctorId, }: Request): Promise<Appointment> { const AppointmentRepo = getRepository("Appointment"); const type = AppointmentRepo.create({ dateHour, patientId, doctorId, }); await AppointmentRepo.save(type); return type; } } export default AppointmentController; <file_sep>/server/src/app/models/Patient.ts import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToOne, JoinColumn, OneToMany, } from "typeorm"; import { Appointment } from "./Appointment"; @Entity("Patient") export class Patient { @PrimaryGeneratedColumn("uuid") id: string; @Column() name: string; // @OneToMany(() => Appointment, (appointment) => appointment.patient) // appointments: Appointment[]; @CreateDateColumn() created_at: Date; @UpdateDateColumn() updated_at: Date; } <file_sep>/server/src/app/models/Doctor.ts import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable, } from "typeorm"; @Entity("Doctor") export class Doctor { @PrimaryGeneratedColumn("uuid") id: string; @Column() name: string; @Column() specialty: string; // @ManyToMany((type) => Specialty, (specialty) => specialty.doctors, { // cascade: true, // }) // @JoinTable() // specialties: Specialty[]; @CreateDateColumn() created_at: Date; @UpdateDateColumn() updated_at: Date; } <file_sep>/server/src/app/controllers/DoctorController.ts import { getRepository } from "typeorm"; import { Doctor } from "../models/Doctor"; import { connection } from "../../database/"; interface Request { name: string; specialty: string; } class DoctorController { public async store({ name, specialty }: Request): Promise<Doctor> { const doctorRepo = getRepository("Doctor"); const doctor = doctorRepo.create({ name, specialty, }); await doctorRepo.save(doctor); return doctor; } } export default DoctorController; <file_sep>/web/src/pages/Home/styles.ts import styled from "styled-components"; export const ContentContainer = styled.div` display: flex; flex-direction: column; `; export const Description = styled.p` opacity: 0.5; `; export const CardContainer = styled.div` display: flex; flex-direction: column; justify-content: center; width: 750px; `; export const CardIcon = styled.div` border: 2px solid rgba(0, 0, 0, 0.16); border-radius: 15px; padding: 15px; width: 75px; height: 75px; display: flex; justify-content: center; align-items: center; transition: all 0.25s ease-in-out; `; export const CardContent = styled.div` flex-direction: column; margin-left: 20px; `;
d56b48350622a44b21491e40f0d54fa7cf4bac41
[ "Markdown", "TypeScript" ]
16
TypeScript
caiodomingues/medtech
ed59705ca93954c8a31d4023988f6f822b6f60ee
ded5063c8095416905d32077fe515355803bcbaf
refs/heads/master
<repo_name>fatehah/ITT440<file_sep>/server2.py import socket import time from socket import * from time import * serversocket = socket(AF_INET,SOCK_STREAM) host = gethostname() port = 5000 serversocket.bind((host,port)) serversocket.listen(5) get = '' while True: clientsocket,addr = serversocket.accept() print("GOT THE CONNECTION FROM %s" % str(addr)) get = serversocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE) print "GET SOCKET KEEPALIVE : ",get; set = serversocket.setsockopt(SOL_SOCKET,SO_KEEPALIVE,1) print "SET SOCKET KEEPALIVE : ",serversocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE) currentTime = ctime(time()) + "\r\n" clientsocket.send(currentTime.encode('ascii')) clientsocket.close() <file_sep>/client.c #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #define DATA "Hello My Socket" int main(int argc, char *argv[]) { int sock_desc; struct sockaddr_in server; struct hostent *hp; char buff[1024]; sock_desc = socket(AF_INET,SOCK_STREAM,0); if(sock_desc < 0) { perror("Socket Failled"); exit(1); } server.sin_family =AF_INET; hp = gethostbyname(argv[1]); if(hp == 0) { perror("gethostbyname FAILED"); close(sock_desc); exit(1); } memcpy(&server.sin_addr, hp->h_addr, hp->h_length); server.sin_port =htons(2500); if(connect(sock_desc,(struct sockaddr *) &server,sizeof(server)) < 0) { perror("Connection Failed"); close(sock_desc); exit(1); } if(send(sock_desc, DATA, sizeof(DATA),0) <0) { perror("send failed"); close(sock_desc); exit(1); } printf("SENT %s\n",DATA); close(sock_desc); return 0; } <file_sep>/UDPclient.c #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main() { int clientSocket, portNum,nBytes; char buffer[1024]; struct sockaddr_in serverAddr; socklen_t addr_size; //create UDP socket clientSocket = socket(PF_INET,SOCK_DGRAM,0); //configure setting in address struct serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(7891); serverAddr.sin_addr.s_addr = inet_addr ("127.0.0.1"); memset(serverAddr.sin_zero, '\0',sizeof serverAddr.sin_zero); //initialize size variable to be used later on addr_size = sizeof serverAddr; while(1) { printf("Type a sentence to send to server : \n"); fgets(buffer,1024,stdin); printf("you typed : %s" ,buffer); nBytes =strlen(buffer) + 1; //send message to server sendto(clientSocket, buffer, nBytes,0,(struct sockaddr *)&serverAddr,addr_size); //receive message from server nBytes = recvfrom(clientSocket,buffer,1024,0,NULL,NULL); printf("Received from server : %s\n", buffer); } return 0; } <file_sep>/UDPserver.c #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <stdlib.h> #include <errno.h> int main () { int udpSocket, nBytes; char buffer[1024]; struct sockaddr_in serverAddr,clientAddr; struct sockaddr_storage serverStorage; socklen_t addr_size, client_addr_size; int j,len,value; //create UDP socket udpSocket = socket(PF_INET, SOCK_DGRAM,0); //configure settings in address struct serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(7891); serverAddr.sin_addr.s_addr = inet_addr ("127.0.0.1"); memset(serverAddr.sin_zero, '\0',sizeof serverAddr.sin_zero); //bind socket with address bind(udpSocket,(struct sockaddr *)&serverAddr,sizeof(serverAddr)); //initialize size variable to be used later on addr_size = sizeof serverStorage; while(1) { //try to receive any incoming UDP datagram.address and port of requesting client will be stored on serverStorage variable nBytes = recvfrom(udpSocket,buffer,1024,0,(struct sockaddr *)&serverStorage, &addr_size); //convert message received to uppercase for(j=0; j<nBytes -1;j++) buffer[j] = toupper(buffer[j]); //send uppercase message back to client, using serverStorage as the address sendto(udpSocket,buffer,nBytes,0,(struct sockaddr *)&serverStorage,addr_size); getsockopt(udpSocket,SOL_SOCKET, SO_DONTROUTE, &value, &len); if(value==0) { printf("UNABLE TO GET %d \n",errno); printf("UNABLE TO GET %d \n",strerror(errno)); } else printf("SUCCESS!! value : %d \n",&value); value =32768; setsockopt(udpSocket,SOL_SOCKET, SO_DONTROUTE, &value, sizeof(value)); printf("ALREADY SET \n"); getsockopt(udpSocket,SOL_SOCKET, SO_DONTROUTE, &value, &len); if(value ==0) printf("UNABLE TO GET NEW CONNECTION %d \n"); else printf("CAN GET THE NEW CONNECTION %d \n",value); } return 0; } <file_sep>/server.c #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> //inet_addr int main (int argc, char *argv[]) { int socket_desc,mysock,rval; int op_val,route; struct sockaddr_in serv_addr; char buff[1024]; //CREATE SOCKET socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc < 0) { printf("Failed to create socket"); exit(1); } serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_family = AF_INET; serv_addr.sin_port =htons(2500); //Bind if(bind(socket_desc,(struct sockaddr *)&serv_addr,sizeof (serv_addr))) { perror("bind failed"); exit(1); } //Listen listen(socket_desc,5); //Accept and incoming connection do{ mysock = accept(socket_desc,(struct sockaddr *)0,0); if(mysock ==-1) { perror("accept failed"); } else { memset(buff, 0, sizeof(buff)); if((rval = recv(mysock,buff,sizeof(buff),0))<0) perror("readimg message error"); else if(rval == 0) printf("ending connection"); else printf("MSG : %s\n",buff); printf("got the message (rval = %d)\n",rval); getsockopt(socket_desc,SOL_SOCKET, SO_DONTROUTE, &op_val, &route); if(op_val != 0) { printf ("UNABLE TO GET \n"); } printf("Get SO_DONTROUTE : %d\n", op_val); op_val = 1; setsockopt(socket_desc, SOL_SOCKET, SO_DONTROUTE, &op_val, sizeof(op_val)); printf("ALREADY set \n"); getsockopt(socket_desc, SOL_SOCKET, SO_DONTROUTE, &op_val, &route); if(op_val == 0) printf("UNABLE TO GET \n"); else printf("GET NEW SO_DONTROUTE : %d\n",op_val); close (mysock); } } while(1); return 0; } <file_sep>/client2.py import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = socket.gethostname() port = 5000 s.connect((host,port)) tm = s.recv(1024) s.close() print("The Time Got from the server is %s" % tm.decode('ascii') ) <file_sep>/server3.py import socket import sys import errno import os #create a TCP/IP socket sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #Bind the socket to the port server_address = ('localhost', 10000) print >>sys.stderr,'starting up on %s port %s' % server_address sock.bind(server_address) while True: print >>sys.stderr, '\nwaiting to receive message' data, address = sock.recvfrom(4096) print >>sys.stderr, 'received %s bytes from %s' %(len(data),address) print >>sys.stderr, data if data: sent = sock.sendto(data,address) print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address) get = sock.getsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE) print "GET SOCKET KEEPALIVE :",get #pitfall 1 if get>0: print "Already set" elif get<0: print "Error",errno.EALREADY print "Description",os.strerror(errno.EALREADY) #pitfall 2 sock.close() #pitfall 3 set = sock.setsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE,1) print "SET SOCKET KEEPALIVE : ", sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) break sock.close() <file_sep>/teha.c #include <stdio.h> int main(int argc) { printf("<NAME>"); printf("selamat hari r<NAME>"); return 0; } <file_sep>/client.py import socket client_socket = socket.socket(1) server_address = 'localhost' server_port = 555 client_socket.connect((server_address,server_port)) data=client_socker.recv(1024) print data client_socket.close()
e935f37ae57937c63fdcbbe59fac7a37d43be5c2
[ "C", "Python" ]
9
Python
fatehah/ITT440
b08b1084ab341071555a3b3fd8c706efdfa5ff91
c277e124af7fa40fe44798999654a7c8dd48424c
refs/heads/master
<file_sep>package ke.co.learning.searching; import java.util.Scanner; public class LinearSearchTest { public static void main(String[] args) { Scanner input = new Scanner(System.in); int searchInt;// search key int position;// location of search key in array // create array and output it LinearArray searchArray = new LinearArray(10); System.out.println(searchArray + "\n");// print array // get input from user System.out.print("Please enter an integer value (-1 ) to quit: "); searchInt = input.nextInt(); // read first int from user // repeately input an integer; -1 terminates the pgoram while (searchInt != -1) { // perform linear search position = searchArray.linearSearch(searchInt); if (position == -1)// integer was not found System.out.println("The integer " + searchInt + "" + " was not found.\n"); else // integer was found System.out.println("The integer " + searchInt + " was found in position " + position + "\n"); System.out.print("Please enter an integer value (-1 to quit): "); searchInt = input.nextInt();// read next int from user } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ke.co.learning.recursion; /** * * @author felix.ojiem */ public class Palindrome { private boolean calculator(String word, int beginAt, int endAt) { if (word.length() <= 1) { return true; } else { char chars[] = word.toCharArray(); if (chars[0] == chars[endAt]) { String substring = word.substring(1, word.length() - 1); return calculator(substring, beginAt, substring.length() - 1); } else { return false; } } } public static void main(String[] args) { Palindrome pal = new Palindrome(); String theString = "retor"; boolean result = pal.calculator(theString, 0, theString.length() - 1); System.err.println("Is palindrome: " + result); } } <file_sep># SortingAlgorithms SortingAlgorithms <file_sep>package ke.co.customgenericdatastructures.lists; // class List definition public class List<T> { private ListNode<T> firstNode; private ListNode<T> lastNode; private String name; // name of list public List() { this("list"); } // constructor creates an empty list with a name public List(String listName) { name = listName; firstNode = lastNode = null; } // insert item at front of list public void insertAtFront(T insertItem) { if (isEmpty()) // firstNode and lastNode refer to same object firstNode = lastNode = new ListNode<T>(insertItem); else // firstNode refers to new node firstNode = new ListNode<T>(insertItem, firstNode); } // insert item at end of list public void insertAtBAck(T insertItem) { if (isEmpty()) // firstNode and lastNode refer to the same object firstNode = lastNode = new ListNode<T>(insertItem); else // lastNode's next node refers to new node lastNode = lastNode.nextNode = new ListNode<T>(insertItem); }// end method insertAtBack // remove first node from list public T removeFromFront() throws EmptyListException { if (isEmpty()) // throw exception if List is empty throw new EmptyListException(name); T removedItem = firstNode.data; // retrieve data being removed // update references firstNode and lastNode if (firstNode == lastNode) firstNode = lastNode = null; else { // locate new last node firstNode = firstNode.nextNode; } // end else return removedItem;// return removed node data }// end method // remove last node form list public T removeFromBack() throws EmptyListException { if (isEmpty()) // throw exception of list is empty throw new EmptyListException(name); T removedItem = lastNode.data;// retrieve data being removed // update references firstNode and lastNode if (firstNode == lastNode) firstNode = lastNode = null; else // locate new last node { ListNode<T> current = firstNode; // loop while current node does not refer to lastNode while (current.nextNode != lastNode) current = current.nextNode; lastNode = current;// current is new lastNode current.nextNode = null; } return removedItem;// return removed node data } // determine whether list is empty public boolean isEmpty() { return firstNode == null;// return true if list is empty } // outputt list contents public void print() { if (isEmpty()) { System.out.printf("Empty %s\n", name); return; } System.out.printf("The %s is \n", name); ListNode<T> current = firstNode; // while not at end of list, output current node's data while (current != null) { System.out.printf("%s ", current.data); current = current.nextNode; } // end while System.out.println("\n"); } public ListNode<T> find(int index) { int currentIndex = 0; if (isEmpty()) { return null; } ListNode<T> current = firstNode; // while not at end of list, output current node's data while (current != null) { if (currentIndex == index) { return current; } current = current.nextNode; currentIndex++; } // end while return firstNode; } // replace item at specific position in list public void replaceAt(T insertItem, int position) { ListNode<T> item = find(position); item.nextNode = new ListNode<T>(insertItem); } // get list size public int size() { int size = 0; if (isEmpty()) { return size; } ListNode<T> current = firstNode; // while not at end of list, output current node's data while (current != null) { current = current.nextNode; size++; } // end while return size; } }<file_sep>package ke.co.learning; public class MergeSortTest { public static void main(String[] args) { // create object to perform merge sort MergeSort sortArray = new MergeSort(10); // print unsorted array System.out.println("Unsorted: " + sortArray + "\n"); sortArray.sort(); // sort array // print sorted array System.out.println("Sorted: " + sortArray); }// end main }// end class mergesorttest
cc521f86bece8669ce4206fa66af66329638e8fb
[ "Markdown", "Java" ]
5
Java
oriedofelo/SortingAlgorithms
1810370039b842cc6c43948c239a46f5e0ba7096
eb441eb0bd05f321c492a0ddbe65751c20b5fc8b
refs/heads/main
<file_sep>import pyautogui import time # Write any comment you need comments = ["#FreePalestine","#SalvailquartierediSheikhJarrah #RettedasViertelSheikhJarrah ","#GazaUnderAttack","#Israel_uses_phosphorus_bombs"," #SaveGaza"," #Palestine","#Save_GAZA", "#ŞeyhJarrah_mahallesini_kurtar","#Siehe_SheikhJarrah_Nachbarschaft","#Sauver_le_quartier_de_SheikhJarrah","#Salva_el_barrio_de_SheikhJarrah","#Salva_il_quartiere_di_SheikhJarrah"] time.sleep(5) #numberOfComments can be any number numberOfComments = 100 for i in range(numberOfComments): pyautogui.typewrite(comments[i%len(comments)]) pyautogui.typewrite('\n') #this time will give you normal delay to not show that you are using a script time.sleep(60) <file_sep># Comments Script Python script for writing comments on Facebook, Instagram or any platform you want # Required requirements # Python https://www.python.org/downloads/ # Install pyautogui just use this command pip install pyautogui *If you wanna update the number of comments or the comments you will need an editor for that I would recommend using Visual Studio Code* https://code.visualstudio.com/download # Instruction of How to Use After running the script you will have 5 seconds to put your cursor in the place you want then you need to leave the mouse cursor and the script will do the rest of the work
3c5fbf1cc65fa1b5cede55a9563288f9c13aaf74
[ "Markdown", "Python" ]
2
Python
Ahmedsafwat101/FacebookComments
29f67564b06af910b31da89542900f4a0eccbb29
3f0370e536f66575f7e235cbe3745e3fd395091b
refs/heads/master
<file_sep>package zx.soft.sent.solr.query; import java.util.Timer; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import zx.soft.sent.dao.common.SentimentConstant; import zx.soft.sent.solr.utils.RedisMQ; /** * 定时删除Redis中的缓存id数据(sent.cache.records):hefei08 * * 1、删除1周前的微博数据 * 2、删除1个月前的其他数据 * * 运行目录:/home/zxdfs/run-work/remove/master-redis * 运行命令:cd sentiment-solr * ./timer-remove-master-redis.sh & * * @author wanggang * */ public class RemoveRedisReplicationData { private static Logger logger = LoggerFactory.getLogger(RemoveRedisReplicationData.class); /** * 主函数 */ public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new RemoveTimer(), 0, 86400_000L); } public static class RemoveTimer extends TimerTask { @Override public void run() { logger.info("Start Removing redis-replication data ..."); RedisMQ redisMQ = new RedisMQ(); redisMQ.deleteKey(SentimentConstant.SENTIMENT_CACHE_KEY); logger.info("Finish Removing redis-replication data ..."); } } }
947820b205d6e0fd2d534a988fc770e964d2e63d
[ "Java" ]
1
Java
zhangzuoqiang/sentiment-search
c0be9135c247910ba360883e1ebf77f5c238a7b5
30c89b03aca1c4755e88ce42e300b53a0404b466
refs/heads/main
<repo_name>geeksville/python-gender-simulator<file_sep>/gensim.py import random choices = ['m', 'f'] def nextPool(curPool): """decide to keep having children if not male child""" newPool = [] for p in curPool: if p == 'f': # if female, keep trying to have kids newPool.append(random.choice(choices)) return newPool def genPool(numKids): pool = [] for i in range(numKids): pool.append(random.choice(choices)) return pool totalMales = 0 totalFemales = 0 genNum = 0 def countKids(pool): """Update global kid count based on current pool, return true if we found only males""" global totalMales, totalFemales, genNum numMales = 0 numFemales = 0 for p in pool: if p == 'm': numMales += 1 else: numFemales += 1 genNum += 1 print(f"Gen {genNum} had {numMales} males and {numFemales} females") totalMales += numMales totalFemales += numFemales return numMales == len(pool) numFirst = 1000 curPool = genPool(numFirst) while not countKids(curPool): curPool = nextPool(curPool) print(f"total males {totalMales} and females {totalFemales}")<file_sep>/README.md # a quick python birth experiment Um, I didn't believe my wife that "if parents kept having kids until they had a boy" results in only a 50% split of boys/girls. I expected a fair amount of more girls. ``` python /home/kevinh/development/gensim/gensim.py Gen 1 had 513 males and 487 females Gen 2 had 244 males and 243 females Gen 3 had 114 males and 129 females Gen 4 had 71 males and 58 females Gen 5 had 37 males and 21 females Gen 6 had 7 males and 14 females Gen 7 had 8 males and 6 females Gen 8 had 2 males and 4 females Gen 9 had 2 males and 2 females Gen 10 had 1 males and 1 females Gen 11 had 0 males and 1 females Gen 12 had 1 males and 0 females total males 1000 and females 966 ```
2da1f2bff46d89c0791fb2a058faa007dc58aead
[ "Markdown", "Python" ]
2
Python
geeksville/python-gender-simulator
fcbf7d36e22c8975f9b12abfc443784ae56a77ee
cf32ab1960bc646a80d0f1497b9ef1977e8e8563
refs/heads/master
<file_sep>----------------------------------------------------------------------------------------- -- -- main.lua -- ----------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------- display.setDefault( "background", 0, 0, 255 ) ------------------------------ ------------------- ----- ----------------------------------------------- local diameterOfPizzaTextField = native.newTextField( display.contentCenterX, display.contentCenterY + 150, 250, 50 ) diameterOfPizzaTextField.id = "diameter textField" local costOfPizzaText = display.newText( "Cost", display.contentCenterX, display.contentCenterY - 200, native.systemFont, 30) costOfPizzaText.id = "cost text" costOfPizzaText:setFillColor( 255, 0, 0) local enterText = display.newText( "diameter= (inches)" , 160, 345, native.systemFont, 25) enterText.id = "enter text" enterText:setFillColor( 1, 1, 1) local calculateButton = display.newImageRect( "MY ASSETS/calculate.png", 200, 77 ) calculateButton.x = 100 calculateButton.y = 475 calculateButton.id = "calculate button" function round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end local function calculateButtonTouch( event ) -- this function calculates the area of a square given the length of one of its sides local diameterOfPizza local costOfPizza diameterOfPizza = diameterOfPizzaTextField.text costOfPizza = ( ( 0.50 * diameterOfPizza ) + 0.75 + 1.00) *1.13 costOfPizza = round(costOfPizza,2) -- print( areaOfSquare ) costOfPizzaText.text = "The cost is $" .. costOfPizza return true end calculateButton:addEventListener( "touch", calculateButtonTouch )
e11808c4da9336b8ac625fa77ea1a7b3c740ca72
[ "Lua" ]
1
Lua
avani-1660/unit-207
94a59dae296bd168ba84804f76fd592ebc6b299c
84c59ac13443334c15b1a07913e722596b250b38
refs/heads/develop
<file_sep>package com.alorma.github.ui.activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import com.alorma.github.R; import com.alorma.github.account.BaseAccountsManager; /** * Created by bernat.borras on 24/10/15. */ public class AccountsFragmentManager extends BaseAccountsManager { private static final String KEY_IMPORT = "KEY_IMPORT"; @Override protected String[] getAccountTypes() { Boolean importAccounts = getImportAccounts(); if (importAccounts != null && importAccounts) { return new String[] { getString(R.string.account_type), getString(R.string.enterprise_account_type) }; } else { return new String[] { getString(R.string.enterprise_account_type) }; } } @Nullable private Boolean getImportAccounts() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); Boolean importAccounts = null; if (preferences.contains(KEY_IMPORT)) { importAccounts = preferences.getBoolean(KEY_IMPORT, false); } return importAccounts; } @Override public boolean multipleAccountsAllowed() { return true; } } <file_sep>include ':app' include ':sdks:GithubAndroidSdk' include ':sdks:GithubAndroidSdk:GitskariosCore'<file_sep>package com.alorma.github.ui.fragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import com.alorma.github.R; /** * Created by Bernat on 20/07/2014. */ public class GistFileFragment extends Fragment { public static final String FILE_NAME = "FILE_NAME"; public static final String CONTENT = "CONTENT"; private WebView webView; private String content; private String fileName; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_content, null, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); webView = (WebView) view.findViewById(R.id.webview); if (getArguments() != null) { fileName = getArguments().getString(FILE_NAME); content = getArguments().getString(CONTENT); webView.clearCache(true); webView.clearFormData(); webView.clearHistory(); webView.clearMatches(); webView.clearSslPreferences(); webView.getSettings().setUseWideViewPort(false); webView.setBackgroundColor(getResources().getColor(R.color.gray_github_light)); webView.setVisibility(View.VISIBLE); WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); webView.addJavascriptInterface(new JavaScriptInterface(), "bitbeaker"); webView.loadUrl("file:///android_asset/diff.html"); webView.getSettings().setDefaultTextEncodingName("utf-8"); } } protected class JavaScriptInterface { @JavascriptInterface public String getCode() { return TextUtils.htmlEncode(content.replace("\t", " ")); } @JavascriptInterface public String getRawCode() { return content; } @JavascriptInterface public String getFilename() { return fileName; } } } <file_sep>package com.clean.presenter; import android.content.Context; import android.support.annotation.NonNull; import com.alorma.github.sdk.bean.dto.response.Repo; import com.alorma.github.sdk.bean.info.RepoInfo; import com.alorma.github.sdk.services.repo.GetRepoClient; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; /** * Created by bernat.borras on 12/11/15. */ public class RepositoryPresenter extends Presenter<RepoInfo, Repo> { private Context context; public RepositoryPresenter(Context context) { this.context = context; } @Override public void load(@NonNull final RepoInfo repoInfo, @NonNull final Callback<Repo> repoCallback) { GetRepoClient repoClient = new GetRepoClient(context, repoInfo); repoClient.observable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Repo>() { @Override public void onNext(Repo repo) { repoCallback.onResponse(repo); } @Override public void onError(Throwable e) { } @Override public void onCompleted() { } }); } } <file_sep>package com.alorma.github.ui.activity.gists; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.alorma.github.R; import com.alorma.github.ui.fragment.GistFileFragment; /** * Created by Bernat on 20/07/2014. */ public class GistsFileActivity extends ActionBarActivity { public static Intent createLauncherIntent(Context context, String name, String content) { Bundle bundle = new Bundle(); bundle.putString(GistFileFragment.FILE_NAME, name); bundle.putString(GistFileFragment.CONTENT, content); Intent intent = new Intent(context, GistsFileActivity.class); intent.putExtras(bundle); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.generic_toolbar); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); GistFileFragment fileFragment = new GistFileFragment(); fileFragment.setArguments(getIntent().getExtras()); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.content, fileFragment); ft.commit(); String title = getIntent().getExtras().getString(GistFileFragment.FILE_NAME); setTitle(title); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return true; } } <file_sep>buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'com.fernandocejas.frodo' repositories { maven { url 'https://maven.fabric.io/public' } } apply plugin: 'io.fabric' apply plugin: 'com.github.ben-manes.versions' //gradle dependencyUpdates -Drevision=release android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { minSdkVersion 15 targetSdkVersion 23 versionName "2.6.10" versionCode 26901 resValue "string", "app_git_hash", getCurrentGitHash() multiDexEnabled true } lintOptions { abortOnError false } signingConfigs { playStore } packagingOptions { exclude 'LICENSE.txt' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/ASL2.0' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/services/javax.annotation.processing.Processor' } productFlavors { github { applicationId "com.alorma.github" ext.betaDistributionGroupAliases = "gitskarios-alpha-testers" } enterprise { applicationId "com.alorma.github_enterprise" ext.betaDistributionGroupAliases = "gitskarios-enterprise-alpha-testers" } } buildTypes { debug { applicationIdSuffix ".debug" buildConfigField "String", "CLIENT_ID", "\"" + getGHId(false) + "\"" buildConfigField "String", "CLIENT_SECRET", "\"" + getGHSecret(false) + "\"" buildConfigField "String", "CLIENT_CALLBACK", "\"" + getGHCallback(false) + "\"" } release { minifyEnabled false if (signingConfigs.playStore != null) { signingConfig signingConfigs.playStore } buildConfigField "String", "CLIENT_ID", "\"" + getGHId(true) + "\"" buildConfigField "String", "CLIENT_SECRET", "\"" + getGHSecret(true) + "\"" buildConfigField "String", "CLIENT_CALLBACK", "\"" + getGHCallback(true) + "\"" } } } def getCurrentGitHash() { return 'git rev-parse --short HEAD'.execute().text.trim() } def Properties props = new Properties() def propFile = file('../gradle.properties') if (propFile.canRead()) { props.load(new FileInputStream(propFile)) if (props != null && props.containsKey('SIGN_FILE') && props.containsKey('SIGN_KEYSTORE_PASS') && props.containsKey('SIGN_KEYSTORE_ALIAS') && props.containsKey('SIGN_KEYSTORE_ALIAS_PASS')) { println 'RELEASE BUILD SIGNING' android.signingConfigs.playStore.storeFile = file(props['SIGN_FILE']) android.signingConfigs.playStore.storePassword = props['SIGN_KEYSTORE_PASS'] android.signingConfigs.playStore.keyAlias = props['SIGN_KEYSTORE_ALIAS'] android.signingConfigs.playStore.keyPassword = props['SIGN_KEYSTORE_ALIAS_PASS'] } else { println 'RELEASE BUILD NOT FOUND SIGNING PROPERTIES' android.buildTypes.release.signingConfig = null } } else { println 'RELEASE BUILD NOT FOUND SIGNING FILE' android.buildTypes.release.signingConfig = null } def getGHId(pro) { if (pro) { return hasProperty('GH_PRO_ID') ? GH_PRO_ID : System.getenv('GH_PRO_ID') } else { return hasProperty('GH_DEV_ID') ? GH_DEV_ID : System.getenv('GH_DEV_ID') } } def getGHSecret(pro) { if (pro) { return hasProperty('GH_PRO_SECRET') ? GH_PRO_SECRET : System.getenv('GH_PRO_SECRET') } else { return hasProperty('GH_DEV_SECRET') ? GH_DEV_SECRET : System.getenv('GH_DEV_SECRET') } } def getGHCallback(pro) { if (pro) { return hasProperty('GH_PRO_CALLBACK') ? GH_PRO_CALLBACK : System.getenv('GH_PRO_CALLBACK') } else { return hasProperty('GH_DEV_CALLBACK') ? GH_DEV_CALLBACK : System.getenv('GH_DEV_CALLBACK') } } dependencies { debugCompile project(path: ':sdks:GithubAndroidSdk', configuration: 'libraryDebug') releaseCompile project(path: ':sdks:GithubAndroidSdk', configuration: 'libraryRelease') // Submodules provided 'com.squareup.dagger:dagger-compiler:1.2.2' compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') { transitive = true; } compile 'com.jakewharton.rxbinding:rxbinding:0.3.0' compile 'com.github.xiprox.errorview:library:2.2.0' compile 'com.android.support:design:23.1.1' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:palette-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.android.support:cardview-v7:23.1.1' compile 'com.google.android.gms:play-services-analytics:8.3.0' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4' compile 'se.emilsjolander:stickylistheaders:2.7.0' compile 'com.nineoldandroids:library:2.4.0' compile 'org.ocpsoft.prettytime:prettytime:4.0.0.Final' compile('com.mikepenz:aboutlibraries:5.2.2@aar') { transitive = true } compile('com.mikepenz:materialdrawer:4.3.7@aar') { transitive = true } compile('com.mikepenz:actionitembadge:3.1.1@aar') compile 'com.mikepenz:octicons-typeface:3.0.1@aar' compile 'com.mikepenz:google-material-typeface:1.2.0@aar' compile 'com.github.d-max:spots-dialog:0.4' compile 'com.squareup:otto:1.3.8' compile 'com.squareup.dagger:dagger:1.2.2' compile 'com.wefika:flowlayout:0.4.0' compile 'com.github.alorma:diff-textview:1.1.0' compile 'com.github.gabrielemariotti.changeloglib:changelog:2.0.0' compile 'com.timehop.stickyheadersrecyclerview:library:0.4.2@aar' compile 'com.afollestad:material-cab:0.1.4' compile 'com.afollestad:material-dialogs:0.7.9.1' compile 'com.github.pedrovgs:renderers:2.0.3' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1' compile("com.fewlaps.quitnowcache:quitnow-cache:1.2") { exclude module: 'joda-time' } compile 'com.android.support:multidex:1.0.1' compile 'io.reactivex:rxandroid:1.0.1' compile('com.crashlytics.sdk.android:answers:1.3.3@aar') { transitive = true; } compile 'com.github.Musenkishi:Atelier:1.3.1' } <file_sep>package com.alorma.github.emoji; import android.os.Parcel; import android.os.Parcelable; /** * Created by Bernat on 08/07/2015. */ public class Emoji implements Parcelable { @SuppressWarnings("unused") public static final Parcelable.Creator<Emoji> CREATOR = new Parcelable.Creator<Emoji>() { @Override public Emoji createFromParcel(Parcel in) { return new Emoji(in); } @Override public Emoji[] newArray(int size) { return new Emoji[size]; } }; private String key; private String value; public Emoji(String key, String value) { this.key = key; this.value = value; } protected Emoji(Parcel in) { key = in.readString(); value = in.readString(); } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(key); dest.writeString(value); } } <file_sep>package com.alorma.github.ui.renderers.releases; import com.alorma.github.sdk.bean.dto.response.Release; import com.pedrogomez.renderers.RendererBuilder; /** * Created by a557114 on 30/07/2015. */ public class ReleaseRendererBuilder extends RendererBuilder<Release> { @Override protected Class getPrototypeClass(Release release) { return ReleaseRenderer.class; } } <file_sep>package com.alorma.github.ui.activity.base; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.alorma.github.R; import com.alorma.github.sdk.login.AccountsHelper; import com.alorma.github.ui.activity.AccountsManager; import com.alorma.github.ui.activity.MainActivity; import com.alorma.gitskarios.core.client.StoreCredentials; import com.alorma.gitskarios.core.client.UnAuthIntent; import dmax.dialog.SpotsDialog; import java.util.List; /** * Created by Bernat on 19/07/2014. */ public class BaseActivity extends AppCompatActivity { public static final String EXTRA_WITH_TOKEN = "ETXRA_WOTH_TOKEN"; private AuthReceiver authReceiver; private UpdateReceiver updateReceiver; private Toolbar toolbar; private SpotsDialog progressDialog; private AccountsManager accountsManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accountsManager = new AccountsManager(); } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); if (isToolbarEnabled()) { toolbar = (Toolbar) findViewById(getToolbarId()); if (toolbar != null) { toolbar.setTitle(R.string.app_name); setSupportActionBar(toolbar); } } } public boolean isToolbarEnabled() { return true; } public Toolbar getToolbar() { return toolbar; } public int getToolbarId() { return R.id.toolbar; } @Override protected void onResume() { super.onResume(); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); authReceiver = new AuthReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(UnAuthIntent.ACTION); manager.registerReceiver(authReceiver, intentFilter); } @Override public void setTitle(CharSequence title) { if (toolbar != null) { toolbar.setTitle(title); } else { super.setTitle(title); } } @Override public void setTitle(int titleId) { if (toolbar != null) { toolbar.setTitle(titleId); } super.setTitle(titleId); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); manager.unregisterReceiver(authReceiver); } @NonNull protected List<Account> getAccounts() { return accountsManager.getAccounts(this); } protected void removeAccount(Account selectedAccount, final AccountsManager.RemoveAccountCallback removeAccountCallback) { accountsManager.removeAccount(this, selectedAccount, removeAccountCallback); } protected void changeNotificationState(Account account, boolean enabled) { accountsManager.changeNotificationState(this, account, enabled); } public void reload() { getContent(); } protected void getContent() { } @Override public void onStart() { super.onStart(); updateReceiver = new UpdateReceiver(); IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(updateReceiver, intentFilter); } @Override public void onStop() { super.onStop(); unregisterReceiver(updateReceiver); } protected void showProgressDialog(@StyleRes int style) { if (progressDialog == null) { try { progressDialog = new SpotsDialog(this, style); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); } catch (Exception e) { e.printStackTrace(); } } } protected void hideProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } private class AuthReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { String token = intent.getStringExtra(UnAuthIntent.TOKEN); AccountManager accountManager = AccountManager.get(context); Account[] accounts = accountManager.getAccountsByType(getString(R.string.account_type)); for (final Account account : accounts) { if (AccountsHelper.getUserToken(context, account).equals(token)) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> accountManagerFuture) { if (accountManagerFuture.isDone()) { StoreCredentials storeCredentials = new StoreCredentials(BaseActivity.this); storeCredentials.clear(); Toast.makeText(BaseActivity.this, getString(R.string.unauthorized, account.name), Toast.LENGTH_SHORT).show(); Intent loginIntent = new Intent(BaseActivity.this, MainActivity.class); loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(loginIntent); finish(); } } }; accountManager.removeAccount(account, BaseActivity.this, callback, new Handler()); } else { AccountManagerCallback<Boolean> callback = new AccountManagerCallback<Boolean>() { @Override public void run(AccountManagerFuture<Boolean> accountManagerFuture) { if (accountManagerFuture.isDone()) { StoreCredentials storeCredentials = new StoreCredentials(BaseActivity.this); storeCredentials.clear(); Toast.makeText(BaseActivity.this, getString(R.string.unauthorized, account.name), Toast.LENGTH_SHORT).show(); Intent loginIntent = new Intent(BaseActivity.this, MainActivity.class); loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(loginIntent); finish(); } } }; accountManager.removeAccount(account, callback, new Handler()); } } catch (Exception e) { e.printStackTrace(); } break; } } } } public class UpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (isOnline(context)) { reload(); } } public boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfoMob = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo netInfoWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return (netInfoMob != null && netInfoMob.isConnectedOrConnecting()) || (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting()); } } } <file_sep>package com.alorma.github.ui.view.pullrequest; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.support.v4.view.ViewCompat; import android.text.Html; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.Commit; import com.alorma.github.sdk.bean.issue.PullRequestStoryCommitsList; import com.alorma.github.utils.AttributesUtils; import com.alorma.github.utils.TimeUtils; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.octicons_typeface_library.Octicons; import com.nostra13.universalimageloader.core.ImageLoader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * Created by Bernat on 20/07/2015. */ public class PullRequestCommitsView extends LinearLayout { private TextView userText; private ImageView profileIcon; private TextView createdAt; private ViewGroup commitsView; public PullRequestCommitsView(Context context) { super(context); init(); } public PullRequestCommitsView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PullRequestCommitsView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public PullRequestCommitsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { inflate(getContext(), R.layout.pull_request_commits, this); userText = (TextView) findViewById(R.id.userLogin); profileIcon = (ImageView) findViewById(R.id.profileIcon); createdAt = (TextView) findViewById(R.id.createdAt); commitsView = (ViewGroup) findViewById(R.id.commitsView); ViewCompat.setElevation(profileIcon, 2); } public void setPullRequestStoryCommitsList(PullRequestStoryCommitsList pullRequestStoryCommitsList) { userText.setText(pullRequestStoryCommitsList.user().login); if (pullRequestStoryCommitsList.user().avatar_url != null) { ImageLoader.getInstance().displayImage(pullRequestStoryCommitsList.user().avatar_url, profileIcon); } else if (pullRequestStoryCommitsList.user().email != null) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(pullRequestStoryCommitsList.user().email.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); String hash = hexString.toString(); ImageLoader.getInstance().displayImage("http://www.gravatar.com/avatar/" + hash, profileIcon); } catch (NoSuchAlgorithmException e) { IconicsDrawable iconDrawable = new IconicsDrawable(profileIcon.getContext(), Octicons.Icon.oct_octoface); iconDrawable.color(AttributesUtils.getSecondaryTextColor(profileIcon.getContext())); iconDrawable.sizeDp(36); iconDrawable.setAlpha(128); profileIcon.setImageDrawable(iconDrawable); } } else { IconicsDrawable iconDrawable = new IconicsDrawable(profileIcon.getContext(), Octicons.Icon.oct_octoface); iconDrawable.color(AttributesUtils.getSecondaryTextColor(profileIcon.getContext())); iconDrawable.sizeDp(36); iconDrawable.setAlpha(128); profileIcon.setImageDrawable(iconDrawable); } DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); String date = TimeUtils.getTimeAgoString(formatter.print(pullRequestStoryCommitsList.createdAt())); String pushedDate = getContext().getResources().getString(R.string.pushed) + " " + date; createdAt.setText(pushedDate); commitsView.removeAllViews(); for (Commit commit : pullRequestStoryCommitsList) { TextView textView = new TextView(getContext()); textView.setText(Html.fromHtml("* " + "<b>" + commit.shortSha() + "</b> " + commit.commit.message)); commitsView.addView(textView); } } } <file_sep>package com.alorma.github.bean; import android.content.Intent; import com.mikepenz.iconics.typeface.IIcon; /** * Created by Bernat on 26/06/2015. */ public class ProfileItem { public IIcon icon; public String value; public Intent intent; public ProfileItem(IIcon icon, String value, Intent intent) { this.icon = icon; this.value = value; this.intent = intent; } } <file_sep>package com.alorma.github.ui.activity; import android.accounts.Account; import android.accounts.AccountManager; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.content.ContextCompat; import android.support.v7.graphics.Palette; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Pair; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import com.alorma.github.R; import com.alorma.github.bean.ProfileItem; import com.alorma.github.sdk.bean.dto.response.Organization; import com.alorma.github.sdk.bean.dto.response.User; import com.alorma.github.sdk.bean.dto.response.UserType; import com.alorma.github.sdk.login.AccountsHelper; import com.alorma.github.sdk.services.client.GithubClient; import com.alorma.github.sdk.services.orgs.GetOrgsClient; import com.alorma.github.sdk.services.user.GetAuthUserClient; import com.alorma.github.sdk.services.user.RequestUserClient; import com.alorma.github.sdk.services.user.follow.CheckFollowingUser; import com.alorma.github.sdk.services.user.follow.FollowUserClient; import com.alorma.github.sdk.services.user.follow.UnfollowUserClient; import com.alorma.github.ui.activity.base.BackActivity; import com.alorma.github.ui.activity.gists.GistsMainActivity; import com.alorma.github.ui.adapter.ProfileItemsAdapter; import com.alorma.github.utils.TimeUtils; import com.alorma.gitskarios.core.client.StoreCredentials; import com.mikepenz.octicons_typeface_library.Octicons; import com.musenkishi.atelier.Atelier; import com.musenkishi.atelier.ColorType; import com.musenkishi.atelier.swatch.DarkVibrantSwatch; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import java.util.List; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; /** * Created by Bernat on 15/07/2014. */ public class ProfileActivity extends BackActivity { public static final String EXTRA_COLOR = "EXTRA_COLOR"; public static final String URL_PROFILE = "URL_PROFILE"; private static final String USER = "USER"; private static final String ACCOUNT = "ACCOUNT"; private static final String AUTHENTICATED_USER = "AUTHENTICATED_USER"; private ImageView image; private User user; private boolean followingUser = false; private CollapsingToolbarLayout collapsingToolbarLayout; private ProfileItemsAdapter profileItemsAdapter; private boolean updateProfile = false; private Account selectedAccount; private boolean colorApplied; private int avatarColor; private int defaultProfileColor; public static Intent createLauncherIntent(Context context, Account selectedAccount) { Intent intent = new Intent(context, ProfileActivity.class); Bundle extras = new Bundle(); extras.putBoolean(AUTHENTICATED_USER, true); extras.putParcelable(ACCOUNT, selectedAccount); intent.putExtras(extras); return intent; } public static Intent createLauncherIntent(Context context, User user) { Bundle extras = new Bundle(); if (user != null) { extras.putParcelable(USER, user); StoreCredentials settings = new StoreCredentials(context); extras.putBoolean(AUTHENTICATED_USER, user.login.equalsIgnoreCase(settings.getUserName())); } Intent intent = new Intent(context, ProfileActivity.class); intent.putExtras(extras); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profile_activity); defaultProfileColor = ContextCompat.getColor(this, R.color.primary); image = (ImageView) findViewById(R.id.imgToolbar); collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.ctlLayout); RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler); recycler.setLayoutManager(new LinearLayoutManager(this)); recycler.setItemAnimator(new DefaultItemAnimator()); profileItemsAdapter = new ProfileItemsAdapter(this); recycler.setAdapter(profileItemsAdapter); if (getIntent().getExtras().containsKey(EXTRA_COLOR)) { avatarColor = getIntent().getIntExtra(EXTRA_COLOR, -1); if (avatarColor != -1) { applyColors(avatarColor); } } } @Override protected void getContent() { if (profileItemsAdapter == null || profileItemsAdapter.getItemCount() == 0) { GithubClient<User> requestClient; user = null; if (getIntent().getExtras() != null) { if (getIntent().getExtras().containsKey(ACCOUNT)) { selectedAccount = getIntent().getParcelableExtra(ACCOUNT); } if (getIntent().getExtras().containsKey(USER)) { user = getIntent().getParcelableExtra(USER); } } StoreCredentials settings = new StoreCredentials(this); if (user != null) { if (user.login.equalsIgnoreCase(settings.getUserName())) { requestClient = new GetAuthUserClient(this); updateProfile = true; collapsingToolbarLayout.setTitle(settings.getUserName()); } else { requestClient = new RequestUserClient(this, user.login); collapsingToolbarLayout.setTitle(user.login); } loadImageAvatar(user); } else { requestClient = new GetAuthUserClient(this); updateProfile = true; } invalidateOptionsMenu(); requestClient.observable() .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<User>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(User user) { onUserLoaded(user); } }); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (menu != null) { menu.clear(); StoreCredentials settings = new StoreCredentials(this); if (user != null && !settings.getUserName().equals(user.login)) { if (followingUser) { menu.add(0, R.id.action_menu_unfollow_user, 0, R.string.action_menu_unfollow_user); } else { menu.add(0, R.id.action_menu_follow_user, 0, R.string.action_menu_follow_user); } menu.getItem(0).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.action_menu_follow_user) { followUserAction(new FollowUserClient(this, user.login)); } else if (item.getItemId() == R.id.action_menu_unfollow_user) { followUserAction(new UnfollowUserClient(this, user.login)); } item.setEnabled(false); return true; } private void followUserAction(GithubClient<Boolean> githubClient) { githubClient.observable() .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Boolean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Boolean aBoolean) { followingUser = aBoolean; invalidateOptionsMenu(); } }); } public void onUserLoaded(final User user) { this.user = user; collapsingToolbarLayout.setTitle(user.login); StoreCredentials settings = new StoreCredentials(this); invalidateOptionsMenu(); if (updateProfile && selectedAccount != null) { AccountManager accountManager = AccountManager.get(this); accountManager.setUserData(selectedAccount, AccountsHelper.USER_PIC, user.avatar_url); ImageLoader.getInstance().clearMemoryCache(); ImageLoader.getInstance().clearDiskCache(); } if (!user.login.equalsIgnoreCase(settings.getUserName())) { followUserAction(new CheckFollowingUser(this, user.login)); } fillCardBio(user); fillCardGithubData(user); if (getSupportActionBar() != null) { loadImageAvatar(user); // new PaletteUtils().loadImageAndPalette(user.avatar_url, this); } } private void loadImageAvatar(final User user) { ImageLoader.getInstance().displayImage(user.avatar_url, image, new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (!colorApplied) { Atelier.with(ProfileActivity.this, user.avatar_url) .load(loadedImage) .swatch(new DarkVibrantSwatch(ColorType.BACKGROUND)) .listener(new Atelier.OnPaletteRenderedListener() { @Override public void onRendered(Palette palette) { applyColors(palette.getVibrantColor(defaultProfileColor)); } }) .into(image); } else { profileItemsAdapter.setAvatarColor(avatarColor); } } @Override public void onLoadingCancelled(String imageUri, View view) { } }); } // @Override // public void onImageLoaded(Bitmap loadedImage, Palette palette) { // // Drawable drawable = new BitmapDrawable(getResources(), loadedImage); // // image.setImageDrawable(drawable); // // if (palette.getSwatches().size() > 0) { // Palette.Swatch swatch = palette.getSwatches().get(0); // applyColors(swatch.getRgb(), swatch.getBodyTextColor()); // } else { // applyColors(getResources().getColor(R.color.primary), Color.WHITE); // } // // fillCardBio(user); // // fillCardGithubData(user); // // fillCardPlan(user); // // } private void applyColors(int rgb) { try { colorApplied = true; if (collapsingToolbarLayout != null) { collapsingToolbarLayout.setContentScrimColor(rgb); collapsingToolbarLayout.setExpandedTitleColor(Color.WHITE); collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE); collapsingToolbarLayout.setStatusBarScrimColor(rgb); } if (profileItemsAdapter != null) { profileItemsAdapter.setAvatarColor(rgb); } if (rgb != 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(rgb); getWindow().setNavigationBarColor(rgb); } } } catch (Exception e) { e.printStackTrace(); } } private void fillCardBio(User user) { if (!TextUtils.isEmpty(user.company)) { Intent intent = new Intent(Intent.ACTION_SEARCH); intent.putExtra(SearchManager.QUERY, user.company); ProfileItem profileUserOrganization = new ProfileItem(Octicons.Icon.oct_organization, user.company, intent); profileItemsAdapter.add(profileUserOrganization); } if (!TextUtils.isEmpty(user.location)) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri geo = Uri.parse("geo:0,0?q=" + user.location); intent.setData(geo); ProfileItem profileUserLocation = new ProfileItem(Octicons.Icon.oct_location, user.location, intent); profileItemsAdapter.add(profileUserLocation); } if (!TextUtils.isEmpty(user.email)) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { user.email }); ProfileItem profileUserEmail = new ProfileItem(Octicons.Icon.oct_mail, user.email, intent); profileItemsAdapter.add(profileUserEmail); } if (user.created_at != null) { ProfileItem profileUserCreated = new ProfileItem(Octicons.Icon.oct_clock, TimeUtils.getDateToText(this, user.created_at, R.string.joined_at), null); profileItemsAdapter.add(profileUserCreated); } } private void fillCardGithubData(User user) { if (user.public_repos > 0) { String text = getString(R.string.repos_num, user.public_repos); Intent intent = ReposActivity.launchIntent(this, user.login, user.type); ProfileItem profileItemRepos = new ProfileItem(Octicons.Icon.oct_repo, text, intent); profileItemsAdapter.add(profileItemRepos); } if (user.public_gists > 0) { String text = getString(R.string.gists_num, user.public_gists); Intent intent = GistsMainActivity.createLauncherIntent(this, user.login); ProfileItem profileItemGists = new ProfileItem(Octicons.Icon.oct_gist, text, intent); profileItemsAdapter.add(profileItemGists); } Intent intent = OrganizationsActivity.launchIntent(this, user.login); final ProfileItem profileItemOrgs = new ProfileItem(Octicons.Icon.oct_organization, getString(R.string.orgs_num_empty), intent); profileItemsAdapter.add(profileItemOrgs); GetOrgsClient orgsClient = new GetOrgsClient(this, user.login); orgsClient.observable() .observeOn(AndroidSchedulers.mainThread()) .map(new Func1<Pair<List<Organization>, Integer>, List<Organization>>() { @Override public List<Organization> call(Pair<List<Organization>, Integer> listIntegerPair) { return listIntegerPair.first; } }) .subscribe(new Subscriber<List<Organization>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<Organization> organizations) { if (organizations != null && organizations.size() > 0) { profileItemOrgs.value = getString(R.string.orgs_num, organizations.size()); profileItemsAdapter.notifyDataSetChanged(); } else { profileItemsAdapter.remove(profileItemOrgs); } } }); if (user.type == UserType.User) { Intent intentStarred = StarredReposActivity.launchIntent(this, user.login); ProfileItem profileItemStar = new ProfileItem(Octicons.Icon.oct_star, getString(R.string.profile_starreds), intentStarred); profileItemsAdapter.add(profileItemStar); Intent intentWatched = WatchedReposActivity.launchIntent(this, user.login); ProfileItem profileItemWatched = new ProfileItem(Octicons.Icon.oct_eye, getString(R.string.profile_watched), intentWatched); profileItemsAdapter.add(profileItemWatched); } } @Override protected void close(boolean navigateUp) { if (user != null && updateProfile) { Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString(URL_PROFILE, user.avatar_url); intent.putExtras(extras); setResult(selectedAccount != null ? RESULT_FIRST_USER : RESULT_OK, intent); } super.close(navigateUp); } } <file_sep>package com.alorma.github.ui.adapter.events.views; import android.content.Context; import android.text.Html; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.TextView; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.GithubEvent; import com.alorma.github.sdk.bean.dto.response.events.payload.ForkEventPayload; import com.alorma.github.utils.TimeUtils; import com.google.gson.Gson; /** * Created by Bernat on 04/10/2014. */ public class ForkEventView extends GithubEventView<ForkEventPayload> { public ForkEventView(Context context) { super(context); } public ForkEventView(Context context, AttributeSet attrs) { super(context, attrs); } public ForkEventView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void inflate() { inflate(getContext(), R.layout.payload_forked, this); } @Override protected void populateView(GithubEvent event) { int textRes = R.string.event_forked_by; ImageView authorAvatar = (ImageView) findViewById(R.id.authorAvatar); //load the profile image from url with optimal settings handleImage(authorAvatar, event); TextView authorName = (TextView) findViewById(R.id.authorName); String original = event.repo.name; String destination = eventPayload.forkee != null ? eventPayload.forkee.full_name : ""; authorName.setText(Html.fromHtml(getContext().getResources().getString(textRes, event.actor.login, original, destination))); TextView textDate = (TextView) findViewById(R.id.textDate); String timeString = TimeUtils.getTimeAgoString(event.created_at); textDate.setText(timeString); } @Override protected ForkEventPayload convert(Gson gson, String s) { return gson.fromJson(s, ForkEventPayload.class); } } <file_sep>package com.alorma.github.ui.activity; import android.accounts.Account; import android.accounts.AccountAuthenticatorActivity; import android.accounts.AccountManager; import android.animation.Animator; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import com.alorma.github.BuildConfig; import com.alorma.github.R; import com.alorma.github.account.GithubLoginFragment; import com.alorma.github.sdk.bean.dto.response.User; import com.alorma.github.sdk.login.AccountsHelper; import com.alorma.github.sdk.services.user.GetAuthUserClient; import com.alorma.gitskarios.core.client.StoreCredentials; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; public class WelcomeActivity extends AccountAuthenticatorActivity implements GithubLoginFragment.LoginCallback { private static final String KEY_IMPORT = "KEY_IMPORT"; @Bind(R.id.imageView) ImageView imageView; @Bind(R.id.imageUser) ImageView imageUser; @Bind(R.id.progressBar) ProgressBar progressBar; @Bind(R.id.appName) TextView appNameTextView; @Bind(R.id.buttonGithub) Button buttonGithub; @Bind(R.id.buttonEnterprise) Button buttonEnterprise; @Bind(R.id.buttonOpen) Button buttonOpen; @Bind(R.id.importAccountsSwitch) CompoundButton importAccountsSwitch; private GithubLoginFragment loginFragment; private String accessToken; private Long startTime; private int countClick = 0; private String url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); ButterKnife.bind(this); StoreCredentials credentials = new StoreCredentials(this); credentials.clear(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); } List<Account> accountsGitskarios = getAccounts(getString(R.string.account_type)); List<Account> accountsOctuirrel = getAccounts(getString(R.string.enterprise_account_type)); String action = getIntent().getAction(); Boolean importAccounts = getImportAccounts(); if (action != null && action.equals(Intent.ACTION_MAIN)) { if (importAccounts != null && importAccounts) { if (accountsGitskarios.size() > 0 || accountsOctuirrel.size() > 0) { openMain(); } else { showInitialButtons(); } } else if (accountsOctuirrel.size() > 0) { openMain(); } else { showInitialButtons(); } } else { showInitialButtons(); } loginFragment = new GithubLoginFragment(); loginFragment.setLoginCallback(this); getFragmentManager().beginTransaction().add(loginFragment, "login").commit(); } @Nullable private Boolean getImportAccounts() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Boolean importAccounts = null; if (preferences.contains(KEY_IMPORT)) { importAccounts = preferences.getBoolean(KEY_IMPORT, false); } return importAccounts; } @Nullable private void setImportAccounts(boolean checked) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.edit().putBoolean(KEY_IMPORT, checked).apply(); } @NonNull protected List<Account> getAccounts(String accountType, String... accountTypes) { if (accountTypes == null || accountTypes.length == 0) { accountTypes = new String[] { accountType }; } AccountManager accountManager = AccountManager.get(this); List<Account> accountList = new ArrayList<>(); for (String account : accountTypes) { Account[] accounts = accountManager.getAccountsByType(account); accountList.addAll(Arrays.asList(accounts)); } return accountList; } private String getGitskariosPackage() { String packageName = "com.alorma.github"; if (BuildConfig.DEBUG) { packageName += ".debug"; } return packageName; } private void onImportEnabled() { String packageName = getGitskariosPackage(); if (appInstalledOrNot(packageName)) { } } private boolean appInstalledOrNot(String uri) { PackageManager pm = getPackageManager(); boolean app_installed; try { pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES); app_installed = true; } catch (PackageManager.NameNotFoundException e) { app_installed = false; } return app_installed; } private void showInitialButtons() { imageView.setVisibility(View.VISIBLE); imageUser.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); buttonOpen.setVisibility(View.INVISIBLE); buttonGithub.animate().alpha(1f).setDuration(TimeUnit.SECONDS.toMillis(1)).start(); buttonGithub.setVisibility(View.VISIBLE); buttonGithub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openCreate(); } }); buttonEnterprise.animate().alpha(1f).setDuration(TimeUnit.SECONDS.toMillis(1)).start(); buttonEnterprise.setVisibility(View.VISIBLE); buttonEnterprise.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openCreateEnterprise(); } }); if (appInstalledOrNot(getGitskariosPackage())) { showImportOption(); } else { hideImportOption(); } } private void showImportOption() { importAccountsSwitch.setVisibility(View.VISIBLE); importAccountsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setImportAccounts(isChecked); if (isChecked) { importAccounts(); buttonGithub.setVisibility(View.INVISIBLE); buttonEnterprise.setVisibility(View.INVISIBLE); buttonOpen.animate().alpha(1f).setDuration(600).start(); buttonOpen.setVisibility(View.VISIBLE); buttonOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openMain(); } }); } else { showInitialButtons(); } } }); } private void importAccounts() { List<Account> accounts = getAccounts(getString(R.string.account_type)); for (Account account : accounts) { } } private void hideImportOption() { importAccountsSwitch.setVisibility(View.INVISIBLE); importAccountsSwitch.setOnCheckedChangeListener(null); } private void openMain() { MainActivity.startActivity(this); finish(); } private void openCreate() { buttonEnterprise.setVisibility(View.INVISIBLE); buttonGithub.animate().alpha(0f).setDuration(TimeUnit.SECONDS.toMillis(1)).setListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { buttonGithub.setVisibility(View.INVISIBLE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).start(); progressBar.animate().alpha(1f).setStartDelay(300).setDuration(TimeUnit.SECONDS.toMillis(1)).start(); progressBar.setVisibility(View.VISIBLE); boolean login = loginFragment.login(); if (!login) { showInitialButtons(); } } private void openCreateEnterprise() { buttonGithub.setVisibility(View.INVISIBLE); buttonEnterprise.animate().alpha(0f).setDuration(TimeUnit.SECONDS.toMillis(1)).setListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { buttonEnterprise.setVisibility(View.INVISIBLE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).start(); progressBar.animate().alpha(1f).setStartDelay(300).setDuration(TimeUnit.SECONDS.toMillis(1)).start(); progressBar.setVisibility(View.VISIBLE); Intent intent = new Intent(this, GithubEnterpriseLoginActivity.class); startActivityForResult(intent, 2112); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); StoreCredentials credentials = new StoreCredentials(this); credentials.clear(); if (loginFragment != null) { loginFragment.onNewIntent(intent); loginFragment.setLoginCallback(this); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 2112) { if (data != null && data.getExtras() != null) { if (data.getExtras().containsKey(GithubEnterpriseLoginActivity.EXTRA_ENTERPRISE_URL) && data.getExtras() .containsKey(GithubEnterpriseLoginActivity.EXTRA_ENTERPRISE_TOKEN)) { url = data.getStringExtra(GithubEnterpriseLoginActivity.EXTRA_ENTERPRISE_URL); String token = data.getStringExtra(GithubEnterpriseLoginActivity.EXTRA_ENTERPRISE_TOKEN); StoreCredentials credentials = new StoreCredentials(this); credentials.storeUrl(url); endAccess(token); } } } } @Override public void endAccess(String accessToken) { this.accessToken = accessToken; GetAuthUserClient authUserClient = new GetAuthUserClient(this, accessToken); authUserClient.observable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<User>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { WelcomeActivity.this.onError(e); } @Override public void onNext(User user) { onUserLoaded(user); } }); } @Override public void onError(Throwable error) { } public void onUserLoaded(final User user) { appNameTextView.setText(user.login); imageUser.setVisibility(View.VISIBLE); buttonOpen.animate().alpha(1f).setDuration(600).start(); buttonOpen.setVisibility(View.VISIBLE); buttonOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addAccount(user); openMain(); } }); progressBar.setVisibility(View.INVISIBLE); ImageLoader.getInstance().loadImage(user.avatar_url, new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { imageUser.setImageBitmap(loadedImage); } @Override public void onLoadingCancelled(String imageUri, View view) { } }); } private void addAccount(User user) { if (ContextCompat.checkSelfPermission(this, "android.permission.AUTHENTICATE_ACCOUNTS") == PackageManager.PERMISSION_GRANTED) { String accountType = getString(R.string.enterprise_account_type); Account account = new Account(user.login, accountType); Bundle userData = AccountsHelper.buildBundle(user.name, user.email, user.avatar_url, url); userData.putString(AccountManager.KEY_AUTHTOKEN, accessToken); AccountManager accountManager = AccountManager.get(this); accountManager.addAccountExplicitly(account, null, userData); accountManager.setAuthToken(account, accountType, accessToken); Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); result.putString(AccountManager.KEY_AUTHTOKEN, accessToken); setAccountAuthenticatorResult(result); checkAndEnableSyncAdapter(account); setResult(RESULT_OK); } } private void checkAndEnableSyncAdapter(Account account) { ContentResolver.setIsSyncable(account, account.type, ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE); if (ContentResolver.getSyncAutomatically(account, account.type)) { ContentResolver.addPeriodicSync(account, account.type, Bundle.EMPTY, 1800); ContentResolver.setSyncAutomatically(account, account.type, true); } } @Override public void loginNotAvailable() { showInitialButtons(); } } <file_sep>package com.alorma.github.ui.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import com.alorma.github.utils.AttributesUtils; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.octicons_typeface_library.Octicons; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.decode.BaseImageDecoder; /** * Created by Bernat on 15/07/2014. */ public class UniversalImageLoaderUtils { public static ImageLoaderConfiguration getImageLoaderConfiguration(Context context) { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .defaultDisplayImageOptions(getDisplayImageOptions(context)) .imageDecoder(new BaseImageDecoder(true)) .build(); return config; } public static DisplayImageOptions getDisplayImageOptions(Context context) { IconicsDrawable drawable = new IconicsDrawable(context, Octicons.Icon.oct_octoface); drawable.color(AttributesUtils.getSecondaryTextColor(context)); drawable.sizeDp(24); BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), drawableToBitmap(drawable)); return new DisplayImageOptions.Builder() .showImageOnLoading(bitmapDrawable) .cacheInMemory(true) .cacheOnDisk(true) .build(); } public static Bitmap drawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } } <file_sep>package com.alorma.github.ui.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.Button; import android.widget.EditText; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import com.alorma.github.R; import com.alorma.github.ui.activity.base.BackActivity; /** * Created by Bernat on 20/10/2015. */ public class GithubEnterpriseLoginActivity extends BackActivity { public static final String EXTRA_ENTERPRISE_TOKEN = "EXTRA_ENTERPRISE_TOKEN"; public static final String EXTRA_ENTERPRISE_URL = "EXTRA_ENTERPRISE_URL"; @Bind(R.id.enterpriseUrl) EditText enterpriseUrl; @Bind(R.id.enterpriseToken) EditText enterpriseToken; @Bind(R.id.enterpriseLogin) Button enterpriseLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.github_enterprise_login); ButterKnife.bind(this); enterpriseToken.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { enterpriseLogin.setEnabled(true); } @Override public void afterTextChanged(Editable editable) { } }); } @OnClick(R.id.enterpriseGenerateToken) public void generateToken() { if (enterpriseUrl.length() > 0) { String url = enterpriseUrl.getText().toString() + "/settings/tokens"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } } @OnClick(R.id.enterpriseLogin) public void onLogin() { if (enterpriseUrl.length() > 0 && enterpriseToken.length() > 0) { Bundle bundle = new Bundle(); bundle.putString(EXTRA_ENTERPRISE_URL, enterpriseUrl.getText().toString()); bundle.putString(EXTRA_ENTERPRISE_TOKEN, enterpriseToken.getText().toString()); Intent intent = new Intent(); intent.putExtras(bundle); setResult(RESULT_OK, intent); finish(); } } } <file_sep>package com.alorma.github.ui.fragment.repos; import android.content.Intent; import android.os.Bundle; import android.util.Pair; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.Repo; import com.alorma.github.sdk.services.repos.UserReposClient; import com.alorma.github.ui.activity.CreateRepositoryActivity; import com.mikepenz.octicons_typeface_library.Octicons; import java.util.List; public class CurrentAccountReposFragment extends BaseReposListFragment { private static final int CREATE_REPOS = 131; private String username; public static CurrentAccountReposFragment newInstance() { return new CurrentAccountReposFragment(); } public static CurrentAccountReposFragment newInstance(String username) { CurrentAccountReposFragment currentAccountReposFragment = new CurrentAccountReposFragment(); if (username != null) { Bundle bundle = new Bundle(); bundle.putString(USERNAME, username); currentAccountReposFragment.setArguments(bundle); } return currentAccountReposFragment; } @Override public void onNext(Pair<List<Repo>, Integer> listIntegerPair) { super.onNext(listIntegerPair); if (getAdapter() != null) { getAdapter().showOwnerNameExtra(false); } } @Override protected void loadArguments() { if (getArguments() != null) { username = getArguments().getString(USERNAME); } } @Override protected void executeRequest() { super.executeRequest(); setAction(new UserReposClient(getActivity(), username)); } @Override protected void executePaginatedRequest(int page) { super.executePaginatedRequest(page); setAction(new UserReposClient(getActivity(), username, page)); } @Override protected int getNoDataText() { return R.string.no_repositories; } @Override protected boolean useFAB() { return true; } @Override protected Octicons.Icon getFABGithubIcon() { return Octicons.Icon.oct_repo_create; } @Override protected void fabClick() { Intent intent = new Intent(getActivity(), CreateRepositoryActivity.class); startActivityForResult(intent, CREATE_REPOS); } } <file_sep>package com.alorma.github.ui.renderers.releases; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.Release; import com.pedrogomez.renderers.Renderer; /** * Created by a557114 on 30/07/2015. */ public class ReleaseRenderer extends Renderer<Release> { @Bind(R.id.releaseState) ImageView releaseState; @Bind(R.id.releaseName) TextView releaseName; @Bind(R.id.filesRelease) TextView filesRelease; @Override protected void setUpView(View view) { } @Override protected void hookListeners(View view) { } @Override protected View inflate(LayoutInflater layoutInflater, ViewGroup viewGroup) { View view = layoutInflater.inflate(R.layout.row_repo_release, viewGroup, false); ButterKnife.bind(this, view); return view; } @Override public void render() { Release release = getContent(); String name = release.name; if (TextUtils.isEmpty(name)) { name = release.tag_name; } releaseName.setText(name); if (release.prerelease) { releaseState.setImageResource(R.drawable.repo_release_prerelease); } if (release.assets != null) { int size = release.assets.size(); if (!TextUtils.isEmpty(release.zipball_url)) { size = size + 1; } if (!TextUtils.isEmpty(release.tarball_url)) { size = size + 1; } filesRelease.setText(filesRelease.getContext().getResources().getQuantityString(R.plurals.repo_release_num_files, size, size)); } } } <file_sep>package com.alorma.github.ui.dialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import com.alorma.github.R; import com.alorma.github.emoji.Emoji; import com.alorma.github.emoji.EmojiBitmapLoader; import com.alorma.github.emoji.EmojisActivity; import com.alorma.github.sdk.bean.dto.response.GithubComment; import com.alorma.github.sdk.bean.info.IssueInfo; import com.alorma.github.sdk.services.issues.NewIssueCommentClient; import com.alorma.github.ui.ErrorHandler; import com.alorma.github.ui.activity.base.BackActivity; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.octicons_typeface_library.Octicons; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; /** * Created by Bernat on 06/09/2014. */ public class NewIssueCommentActivity extends BackActivity implements Observer<GithubComment> { private static final String ISSUE_INFO = "ISSUE_INFO"; private static final int EMOJI_CODE = 4524; private EditText edit; private IssueInfo issueInfo; private EmojiBitmapLoader emojiBitmapLoader; private TextWatcher bodyTextWatcher; public static Intent launchIntent(Context context, IssueInfo issueInfo) { Bundle bundle = new Bundle(); bundle.putParcelable(ISSUE_INFO, issueInfo); Intent intent = new Intent(context, NewIssueCommentActivity.class); intent.putExtras(bundle); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_issue_comment); emojiBitmapLoader = new EmojiBitmapLoader(); if (getIntent().getExtras() != null) { issueInfo = getIntent().getExtras().getParcelable(ISSUE_INFO); if (issueInfo != null) { edit = (EditText) findViewById(R.id.edit); bodyTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().contains(":")) { emojiBitmapLoader.parseTextView(edit); } } @Override public void afterTextChanged(Editable s) { } }; edit.addTextChangedListener(bodyTextWatcher); } } else { finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.new_issue_comment, menu); MenuItem itemSend = menu.findItem(R.id.action_send); if (itemSend != null) { IconicsDrawable iconDrawable = new IconicsDrawable(this, Octicons.Icon.oct_bug); iconDrawable.color(Color.WHITE); iconDrawable.actionBarSize(); itemSend.setIcon(iconDrawable); } MenuItem emojiMenu = menu.findItem(R.id.action_add_emoji); emojiMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); Drawable emojiIcon = new IconicsDrawable(this, Octicons.Icon.oct_octoface).actionBar().color(Color.WHITE); emojiMenu.setIcon(emojiIcon); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.action_send) { String body = edit.getText().toString(); showProgressDialog(R.style.SpotDialog_CommentIssue); NewIssueCommentClient client = new NewIssueCommentClient(this, issueInfo, body); client.observable().observeOn(AndroidSchedulers.mainThread()).subscribe(this); } else if (item.getItemId() == R.id.action_add_emoji) { Intent intent = new Intent(this, EmojisActivity.class); startActivityForResult(intent, EMOJI_CODE); } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == EMOJI_CODE && resultCode == RESULT_OK && data != null) { Emoji emoji = data.getParcelableExtra(EmojisActivity.EMOJI); if (emoji != null) { edit.removeTextChangedListener(bodyTextWatcher); edit.setText(edit.getText() + " :" + emoji.getKey() + ": "); emojiBitmapLoader.parseTextView(edit); edit.setSelection(edit.getText().length()); } } } @Override public void onNext(GithubComment githubComment) { hideProgressDialog(); setResult(RESULT_OK); finish(); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { hideProgressDialog(); ErrorHandler.onError(this, "NewCommentDialog", e); } }
be0c1949824aa11b914072e0e45d58411b9fb83e
[ "Java", "Gradle" ]
19
Java
ashokslsk/Gitskarios
1db17d1f314a5e10e8c6e5408e5fc0832349e971
908a9f6fe24bb9fa8140208fc2fb8628452f1c6a
refs/heads/master
<file_sep>app = Dragonfly[:images] app.configure_with(:rails) FactoryGirl.define do factory :project do title "Test title" description "Nullam vitae odio quis nisl interdum volutpat. Curabitur nec mi nec mauris elementum sagittis. Integer a ante sapien, a dapibus mauris. Suspendisse non tortor sed enim sagittis convallis vel et nulla. Sed quis orci eget eros pretium hendrerit in vitae lorem. Proin ultricies molestie rhoncus. Nam cursus enim sollicitudin mauris laoreet eu mattis lectus dignissim. Ut sodales lectus sit amet lacus varius nec pellentesque quam pulvinar. Integer ligula ligula, molestie quis bibendum ac, aliquam et odio. Duis a mi nisi, vitae varius urna. Phasellus posuere sodales vehicula. Morbi nulla lacus, tempor id scelerisque quis, eleifend id elit. Donec pretium mollis lacus, ut feugiat elit suscipit eget. Fusce velit magna, tincidunt non ullamcorper hendrerit, blandit ac elit." association :user end end <file_sep>StartupWeek::Application.routes.draw do scope '(:lang)', :constraints =>{:lang => /en|pl/} do devise_for :users resources :projects end root :to => "projects#index" end <file_sep>class Ability include CanCan::Ability def initialize(user) can :read, :all if user can :create, Project with_options user_id: user.id do |owner| owner.can :update, Project owner.can :destroy, Project end end end end <file_sep>require "application_responder" class ApplicationController < ActionController::Base self.responder = ApplicationResponder respond_to :html before_filter :set_locale protect_from_forgery check_authorization :unless => :devise_controller? rescue_from CanCan::AccessDenied do |exception| flash[:alert] = "Access denied." redirect_to root_url end def set_locale logger.debug "* params: #{params}" I18n.locale = params[:lang] || I18n.default_locale logger.debug "* Locale set to '#{I18n.locale}'" end def default_url_options(options={}) logger.debug "default_url_options is passed options: #{options.inspect}\n" { :lang => I18n.locale } end end <file_sep>class ProjectsController < ApplicationController responders :flash, :http_cache before_filter :authenticate_user!, except: [:index, :show] load_and_authorize_resource def index end def show end def new end def edit end def create @project.user = current_user @project.save respond_with(@project) end def update @project.update_attributes(params[:project]) respond_with(@project) end def destroy @project.destroy UserMailer.project_deletion(@project).deliver respond_with(@project) end end <file_sep>class UserMailer < ActionMailer::Base default from: "<EMAIL>" def project_deletion(project) @project = project mail(:to => project.user.email, :subject => "Project Deleted") end end <file_sep>require 'spec_helper' describe "Project" do it "should have a title" do Project.new.should have_at_least(1).error_on(:title) end it "title should have at least 1 letter" do Project.new(title:"").should have_at_least(1).error_on(:title) end it "title should have no more then 255 letters" do Project.new(title:"Duis facilisis dolor suscipit massa pellentesque ornare. Proin mi sem, vulputate vitae facilisis in, pretium eget dolor. Donec molestie laoreet sapien at fringilla. In hac habitasse platea dictumst. Maecenas eget augue nisl. Sed leo nisi, accumsan sed dapibus ac, euismod sed. ").should have(1).error_on(:title) end it "title can have 9 letters" do Project.new(title:"test title").should have(:no).errors_on(:title) end it "should have an author" do Project.new.should have(1).errors_on(:user) end it "author could be an arbitary user" do Project.new(user: User.new).should have(:no).errors_on(:user) end it "should have a description" do Project.new.should have_at_least(1).errors_on(:description) end it "description must be longer then 50 characters" do Project.new(description: "too short").should have(1).errors_on(:description) end it "description can have 276 characters" do Project.new(description: "Duis facilisis dolor suscipit massa pellentesque ornare. Proin mi sem, vulputate vitae facilisis in, pretium eget dolor. Donec molestie laoreet sapien at fringilla. In hac habitasse platea dictumst. Maecenas eget augue nisl. Sed leo nisi, accumsan sed dapibus ac, euismod sed.").should have(:no).errors_on(:description) end end <file_sep>require 'spec_helper' describe "Visitors" do describe "GET /projects" do it "Visitor can see all project" do # Run the generator again with the --webrat flag if you want to use webrat methods/matchers project = Factory(:project) get projects_path response.status.should be(200) response.body.should include(project.title) response.body.should include(project.description) response.body.should include(project_path(project)) end it "Visitors cannot create new project" do get new_project_path response.should redirect_to("/users/sign_in") post projects_path, project:{title:"test title", description:"some description"} response.should redirect_to("/users/sign_in") end end describe "GET /projects with capybara" do it "Visitor can see all project" do # Run the generator again with the --webrat flag if you want to use webrat methods/matchers project = Factory(:project) visit projects_path page.should have_content(project.title) page.should have_content(project.description) page.should have_link("Show") end it "Visitors cannot create new project" do visit new_project_path page.should have_content("You need to sign in") end it "Visitor cannot edit project" do visit projects_path page.should have_no_link("Edit") end it "Visitor cannot delete project" do visit projects_path page.should have_no_link("Delete") page.should have_no_link("Remove") end it "Visitor can register" do visit root_path click_link "Sign up" fill_in "Email", with: "<EMAIL>" fill_in "Password", with: "<PASSWORD>" fill_in "Password confirmation", with: "<PASSWORD>" click_button "Sign up" page.should have_content("You have signed up successfully.") end end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # app = Dragonfly[:images] app.configure_with(:rails) 3.times do user = Factory(:user, confirmed_at: Time.now) (1..5).to_a.sample.times do [true, false].sample ? img = nil : img = app.generate(:plasma, (100..500).to_a.sample, (100..500).to_a.sample).encode(:jpeg) Factory(:project, user: user, image: img) end end <file_sep>class Project < ActiveRecord::Base belongs_to :user image_accessor :image validates_size_of :image, maximum: 500.kilobytes validates :user, presence: true validates :title, presence: true, length: {minimum: 1, maximum: 255} validates :description, presence: true, length: {minimum: 50} end
409a8d570f250f3ab377db2e0dfeaaaf5f2b1092
[ "Ruby" ]
10
Ruby
kacperk/startup_week
a3fe23d90f9a260d54854ce127b13b4e332429f8
305b847264df87f8f8b4f02a1882b76c6e1af946
refs/heads/master
<file_sep># hacker-rank ## Challenge: https://www.hackerrank.com/challenges/botclean ### Normal method: (score 7.60) ### Eucladian method: ### Manhattan method: <file_sep>#!/usr/bin/python def display_path_to_princess(n, grid): pos_col = {} pos_row = {} found = False for i in range(n): for j in range(n): if grid[i][j] == 'm': pos_row['m'] = i pos_col['m'] = j elif grid[i][j] == 'p': pos_row['p'] = i pos_col['p'] = j while (not found): if pos_row['m'] < pos_row['p']: pos_row['m'] = pos_row['m'] + 1 print('DOWN') elif pos_row['m'] > pos_row['p']: pos_row['m'] = pos_row['m'] - 1 print('UP') if pos_col['m'] < pos_col['p']: pos_col['m'] = pos_col['m'] + 1 print('RIGHT') elif pos_col['m'] > pos_col['p']: pos_col['m'] = pos_col['m'] - 1 print('LEFT') if pos_col['m'] == pos_col['p'] and pos_row['m'] == pos_row['m']: found = True m = int(input()) grid = [] for i in range(0, m): grid.append(input().strip()) display_path_to_princess(m, grid) <file_sep># hacker-rank Solve problems..
93a1f0842373cb8fdfdfc22a320334ca6c86f6bf
[ "Markdown", "Python" ]
3
Markdown
anoopsg/hacker-rank
8888b4edd64e468607d754664173fe35d6b26403
7fbcc7dc50f817d1b8a53f5e57be06500e73a422
refs/heads/main
<repo_name>Aks1997/AdminPanelSS<file_sep>/src/app/home/dynamic-table/dynamic-table.component.ts import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { Iuser } from 'src/app/models/Iuser'; @Component({ selector: 'app-dynamic-table', templateUrl: './dynamic-table.component.html', styleUrls: ['./dynamic-table.component.css'], }) export class DynamicTableComponent implements OnInit { @Input() headerColumns: string[]; @Input() dataColumns: Iuser[]; tableDataSource: any constructor( ) { } ngOnInit(): void { this.tableDataSource = new MatTableDataSource(this.dataColumns); } } <file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Iadmin } from '../models/Iadmin'; import { AdminService } from '../services/admin.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { emailId: string=""; passwordValue: string=""; constructor(private route: Router, private adminService: AdminService) { } ngOnInit(): void { } public login(): void{ let isAdminLoggedIn= this.adminService.loginAdmin(this.emailId, this.passwordValue); if(isAdminLoggedIn){ this.route.navigate(['../home']); } } } <file_sep>/src/app/home/create-user/create-user.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Iuser } from 'src/app/models/Iuser'; @Component({ selector: 'app-create-user', templateUrl: './create-user.component.html', styleUrls: ['./create-user.component.css'] }) export class CreateUserComponent implements OnInit { user: Iuser; constructor(private route: Router) { this.user={ name:"", age: 0, emailId: "", sex: "" } } ngOnInit(): void { } createUser(){ let jsonUsers= localStorage.getItem("users"); let users:Iuser[] = jsonUsers? JSON.parse(jsonUsers): []; users.push(this.user); this.user = { name:"", age: 0, emailId: "", sex: "" }; localStorage.setItem('users',JSON.stringify(users)); this.route.navigate(['../home/show']); } } <file_sep>/src/app/models/Iuser.ts export interface Iuser{ name: string, emailId: string, age: number, sex: string }<file_sep>/README.md # AdminPanelSS AdminPanelSS <file_sep>/src/app/signup/signup.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Iadmin } from '../models/Iadmin'; import { AdminService } from '../services/admin.service'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { admin: Iadmin; confirmPass: string; isPassMatch: boolean= true; constructor(private adminService: AdminService, private router: Router) { this.admin={ name:"", emailId:"", password: "", isAuthenticated: false } } ngOnInit(): void { } matchPassword(event){ this.confirmPass= event; if(this.confirmPass===this.admin.password){ this.isPassMatch= true; }else{ this.isPassMatch= false; } } public onSubmit(): void{ let response= this.adminService.registerAdmin(this.admin); this.router.navigate(['login']); } } <file_sep>/src/app/app.component.ts import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { Iadmin } from './models/Iadmin'; import { AdminService } from './services/admin.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { title = 'AdminPanelSS'; showHeader: boolean= false; admin: Iadmin constructor(private adminService: AdminService){ } ngOnInit(): void { this.admin = this.adminService.loggedInAdmin; } isAuthenticated(){ return this.adminService.isAuthenticated(); } } <file_sep>/src/app/home/home-route.ts import { Routes } from "@angular/router"; import { CreateUserComponent } from "./create-user/create-user.component"; import { ShowUserComponent } from "./show-user/show-user.component"; export const route: Routes = [ {path: '', redirectTo: 'show', pathMatch: 'full'}, {path: 'create', component: CreateUserComponent}, {path: 'show', component: ShowUserComponent}, ] <file_sep>/src/app/home/show-user/show-user.component.ts import { ChangeDetectionStrategy } from '@angular/compiler/src/compiler_facade_interface'; import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { Iuser } from 'src/app/models/Iuser'; @Component({ selector: 'app-show-user', templateUrl: './show-user.component.html', styleUrls: ['./show-user.component.css'] }) export class ShowUserComponent implements OnInit { headerColumns: string[]= ['name','age','sex','emailId'] dataColumns: Iuser[]= [ { name: '<NAME>', age: 23, sex: 'Male', emailId: '<EMAIL>' }, { name: 'Akhil', age: 24, sex: 'Male', emailId: '<EMAIL>' }, { name: 'Chauhan', age: 27, sex: 'Male', emailId: '<EMAIL>' }, { name: 'Qwerty', age: 20, sex: 'Female', emailId: '<EMAIL>' }, ] constructor() { const users = JSON.parse(localStorage.getItem('users')); this.dataColumns.push(...users); } ngOnInit(): void { } } <file_sep>/src/app/services/admin.service.ts import { Injectable } from '@angular/core'; import { Iadmin } from '../models/Iadmin'; @Injectable({ providedIn: 'root' }) export class AdminService { private _loggedInAdmin: Iadmin; constructor() { } public get loggedInAdmin(): Iadmin { return this._loggedInAdmin; } public set loggedInAdmin(value: Iadmin) { this._loggedInAdmin = value; } public registerAdmin(admin: Iadmin): boolean{ try{ localStorage.setItem(admin.emailId, JSON.stringify(admin)); }catch(err){ return false; } return true; } public loginAdmin(emailId: string, password: string): boolean{ let admin: Iadmin=null; try{ const parsedData = localStorage.getItem(emailId); admin = JSON.parse(parsedData); if(admin.password===<PASSWORD>){ admin.isAuthenticated= true; this.loggedInAdmin= admin; } }catch(err){ this.loggedInAdmin= null; return false; } return true; } public isAuthenticated(){ return this._loggedInAdmin ?this._loggedInAdmin.isAuthenticated: false; } } <file_sep>/src/app/home/home.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CreateUserComponent } from './create-user/create-user.component'; import { ShowUserComponent } from './show-user/show-user.component'; import { RouterModule } from '@angular/router'; import { route } from './home-route'; import { DynamicTableComponent } from './dynamic-table/dynamic-table.component'; import {MatTableModule} from '@angular/material/table'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ CreateUserComponent, ShowUserComponent, DynamicTableComponent], imports: [ CommonModule, MatTableModule, FormsModule, RouterModule.forChild(route) ] }) export class HomeModule { }
bc9e2ba55d7426fdd5c186638d6ccf498072ce59
[ "Markdown", "TypeScript" ]
11
TypeScript
Aks1997/AdminPanelSS
6dc4ccbc36584d99b5b6173b7d0f12d272342ba8
01a6773ad42760a59af89d29c246b61eac834a5d
refs/heads/main
<file_sep>const sumSquareDifference = require("../sum-square-difference"); it(`should find the difference between the sum of the squares of the first 10 numbers and the square of the sum.`, () => { expect(sumSquareDifference(10)).toBe(2640); }); it(`should find the difference between the sum of the squares of the first 100 numbers and the square of the sum.`, () => { expect(sumSquareDifference(100)).toBe(25164150); }); <file_sep>module.exports = function primeByPosition(position) { let cont = 0; for (let i = 2; i <= Number.MAX_SAFE_INTEGER; i++) { for (let j = 2; j <= i; j++) { if (i % j === 0) { if (i !== j) break; else { cont++; if (cont === position) return i; } } } } }; <file_sep>module.exports = function evenFibonacci(limit) { let a = 2; let b = 3; let nextNumber = a; let sum = nextNumber; while (nextNumber < limit) { nextNumber = a + b; a = b; b = nextNumber; if (nextNumber % 2 !== 0) continue; sum += nextNumber; } return sum; }; <file_sep>const sumMultiples = require("../multiple"); it("should find the sum of all the multiples of 3 or 5 below 10", () => { expect(sumMultiples(10)).toBe(23); }); it("should find the sum of all the multiples of 3 or 5 below 20", () => { expect(sumMultiples(20)).toBe(78); }); it("should find the sum of all the multiples of 3 or 5 below 1000", () => { expect(sumMultiples(1000)).toBe(233168); }); <file_sep>const primeByPosition = require("../primeByPosition"); it("the 6th prime is 13", () => { expect(13).toBe(primeByPosition(6)); }); it("the 1001st prime is 7927", () => { expect(7927).toBe(primeByPosition(1001)); }); // it("the 10001st prime is 104743", () => { // expect(104743).toBe(primeByPosition(10001)); // }); <file_sep>const isMultiple = (num, divider) => num % divider === 0; module.exports = function sumMultiples(limit) { let totalSum = 0; for (let i = 1; i < limit; i++) { if (isMultiple(i, 3) || isMultiple(i, 5)) { totalSum += i; } } return totalSum; }; <file_sep>module.exports = function sumSquareDifference(limit) { let sum = 0; let squaresSum = 0; for (let i = 1; i <= limit; i++) { squaresSum += Math.pow(i, 2); sum += i; } return Math.pow(sum, 2) - squaresSum; }; <file_sep>const evenFibonacci = require("../even-fibonacci"); it(`should find the sum of the even values in Fibonacci which don't exceed 100`, () => { expect(evenFibonacci(100)).toBe(188); }); it(`should find the sum of the even values in Fibonacci which don't exceed 4M`, () => { expect(evenFibonacci(4000000)).toBe(4613732); }); <file_sep>const largestPalindrome = require("../largest-palindrome"); it(`should find the largest palindrome made from the product of two 3-digit numbers.`, () => { expect(largestPalindrome()).toBe(906609); }); <file_sep># Project-euler-PM Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems. ## Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. |[Solution 1](./src/multiple.js)|[Tests 1](./src/__test__/multiple.test.js)| |--|--| ## Problem 2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. |[Solution 2](./src/even-fibonacci.js)|[Tests 2](./src/__test__/even-fibonacci.test.js)| |--|--| ## Problem 3 What is the largest prime factor of the number 600851475143 ? |[Solution 3](./src/largest-prime-factor.js)|[Tests 3](./src/__test__/largest-prime-factor.test.js)| |--|--| ## Problem 4 Find the largest palindrome made from the product of two 3-digit numbers. |[Solution 4](./src/largest-palindrome.js)|[Tests 4](./src/__test__/largest-palindrome.test.js)| |--|--| ## Problem 5 What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? |[Solution 5](./src/smallest-multiple.js)|[Tests 5](./src/__test__/smallest-multiple.test.js)| |--|--| ## Problem 6 Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. |[Solution 6](./src/sum-square-difference.js)|[Tests 6](./src/__test__/sum-square-difference.test.js)| |--|--| ## Problem 7 Find the 10001st prime number |[Solution 7](./src/primeByPosition.js)|[Tests 7](./src/__test__/primeByPosition.test.js)| |--|--| ## Problem 8 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? |[Solution 8](./src/largest-product.js)|[Tests 8](./src/__test__/largest-product.test.js)| |--|--| ## Problem 10 Find the sum of all the primes below two million. |[Solution 10](./src/primes-sum.js)|[Tests 10](./src/__test__/primes-sum.test.js)| |--|--| ## Authors | [<img src="https://avatars.githubusercontent.com/u/45442712" width="100px;"/><br /><sub><b><NAME></b></sub>](https://github.com/jesuslgarciah)<br /> | [<img src="https://avatars.githubusercontent.com/u/47506498" width="100px;"/><br /><sub><b><NAME></b></sub>](https://github.com/Esteban-Ladino)<br /> | | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | <file_sep>module.exports = function smallestMultiple(n) { let smallestNum = 2; while (smallestNum <= Number.MAX_SAFE_INTEGER) { for (let i = 2; i <= n; i++) { if (!(smallestNum % i === 0)) { break; } if (i === n) { return smallestNum; } } smallestNum++; } }; <file_sep>export const primeSum = (num) => { let sum = 0; let band = true; for (let i = 2; i < num; i++) { for (let j = 2; j <= i / 2; j++) { if (i % j === 0) { band = false; break; } } if (band) { sum += i; } band = true; } return sum; }<file_sep>import { primeSum } from "../primes-sum"; it("should find the sum of all the primes below 10.", () => { expect(primeSum(10)).toBe(17); }); // it("should find the sum of all the primes below two million.", () => { // expect(primeSum(2000000)).toBe(142913828922); // });
a0948fa9121c3f175a054713577103577004de97
[ "JavaScript", "Markdown" ]
13
JavaScript
Esteban-Ladino/project-euler-PM
84c7b56fd804b01b4d1d2a9749d832fca2be39f9
80bb6f42c00e9e2b2adb181d73aa7a8bcdab7fd0
refs/heads/master
<file_sep>using System; using System.Collections.Generic; namespace ica.model { public class SlackResponse { public string Text { get; set; } public string Color { get { return Enum.GetName(typeof(SlackColor), SlackColor); } } public SlackColor SlackColor { get; set; } public List<SlackResponse> Attachments { get; set;} } public enum SlackColor { good = 1, warning = 2, danger = 3 } } <file_sep>iz-sql: image: microsoft/mssql-server-linux environment: - 'ACCEPT_EULA=Y' - 'SA_PASSWORD=<PASSWORD>()!' ports: - '1433:1433' iz-api: build: . command: 'bash -c "cd /opt/src/ica.database.migrations app && dotnet ef database update && cd /opt/app && dotnet /opt/app/ica.rest.dll --server.urls http://0.0.0.0:3000"' environment: - 'DB__CONNECTIONSTRING=Data Source=sql; Database=izone-dev; User ID=sa; Password=<PASSWORD>()!;' links: - 'iz-sql:sql' ports: - '3001:3000' <file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace ica.database.migrations.Migrations { public partial class ExtendJobLogs : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>("jl_job_id", "job_log_db"); migrationBuilder.AddColumn<double>("jl_hours", "job_log_db"); migrationBuilder.AddColumn<string>("jl_alias", "job_log_db"); migrationBuilder.AddColumn<string>("jl_executor", "job_log_db"); migrationBuilder.AddColumn<string>("jl_description", "job_log_db"); migrationBuilder.AddColumn<string>("jl_gcal_id", "job_log_db"); migrationBuilder.AddColumn<DateTime>("jl_starttime", "job_log_db"); migrationBuilder.AddColumn<DateTime>("jl_endtime", "job_log_db"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn("jl_job_id", "job_log_db"); migrationBuilder.DropColumn("jl_hours", "job_log_db"); migrationBuilder.DropColumn("jl_alias", "job_log_db"); migrationBuilder.DropColumn("jl_executor", "job_log_db"); migrationBuilder.DropColumn("jl_description", "job_log_db"); migrationBuilder.DropColumn("jl_gcal_id", "job_log_db"); migrationBuilder.DropColumn("jl_starttime", "job_log_db"); migrationBuilder.DropColumn("jl_endtime", "job_log_db"); } } } <file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace ica.database.migrations.Migrations { public partial class UpdatePeopleDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>("p_id", "people_db"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn("p_id", "people_db"); } } } <file_sep>using System.ComponentModel.DataAnnotations.Schema; namespace ica.model { [Table("people_db")] public class Person { [Column("p_id")] public int Id { get; set; } [Column("p_firstname")] public string Firstname { get; set; } [Column("p_lastname")] public string Lastname { get; set; } [Column("p_izusername")] public string IzoneUsername { get; set; } [Column("p_email")] public string Email { get; set; } [Column("p_slack_id")] public string SlackId { get; set; } [Column("p_slack_username")] public string SlackUsername { get; set; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; namespace ica.model { [Table("job_log_db")] public class TimeEntry { [Column("jl_id")] public int Id { get; set; } [Column("jl_job_id")] public int? JobId { get; set; } [Column("jl_alias")] public string Alias { get; set; } [Column("jl_description")] public string Description { get; set; } [Column("jl_executor")] public string Executor { get; set; } [Column("jl_hours")] public double Hours { get; set; } [Column("jl_starttime")] public DateTime StartTime { get; set; } [Column("jl_endtime")] public DateTime EndTime { get; set; } [Column("jl_gcal_id")] public string GoogleCalendarId { get; set; } } }<file_sep>using System; using ica.database; using Microsoft.AspNetCore.Mvc; namespace ica.rest.Controllers { [Route("/")] public class ApiController : Controller { readonly ITimeEntryRepository _timeEntryRepository; public ApiController(ITimeEntryRepository timeEntryRepository) { _timeEntryRepository = timeEntryRepository; } [HttpGet] public string Index() { return "IZONE CORE API"; } [HttpGet] [Route("/status")] public string Status() { var dbConnectionStatus = "DOWN"; try { var hours = _timeEntryRepository.TotalHours(); Console.WriteLine(string.Format("GET /status - DB OK. Total time entries: {0} h", hours)); dbConnectionStatus = "OK"; } catch (Exception exception) { Console.WriteLine("GET /status - database connection failed."); Console.WriteLine(exception.Message); } return string.Format("Database connection: {0}", dbConnectionStatus); } } } <file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace ica.database.migrations.Migrations { public partial class AddSlackFieldsToPeopleDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>("p_slack_id", "people_db"); migrationBuilder.AddColumn<string>("p_slack_username", "people_db"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn("p_slack_id", "people_db"); migrationBuilder.DropColumn("p_slack_username", "people_db"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ica.model; using ica.model.REST; using ica.database; namespace ica.rest.Controllers { [Route("[controller]")] public class SlackController : Controller { public readonly IPersonRepository _personRepository; public readonly ITimeEntryRepository _timeEntryRepository; public SlackController(IPersonRepository personRepository, ITimeEntryRepository timeEntryRepository) { _personRepository = personRepository; _timeEntryRepository = timeEntryRepository; } [HttpPost] public SlackResponse Post([FromForm] SlackRequestPayload payload) { Console.WriteLine("Received POST /slack"); Console.WriteLine("User ID: " + payload.user_id); Console.WriteLine("Username: " + payload.user_name); var response = new SlackResponse { Attachments = new List<SlackResponse>() }; var person = GetPerson(payload.user_id, payload.user_name); if (person == null) { response.Text = "Something went wrong."; response.Attachments.Add(new SlackResponse { Text = string.Format("Your account needs to be setup in izone before you can use this command. <{0}|{1}>", payload.user_name, payload.user_id), SlackColor = SlackColor.danger }); return response; } var timeEntries = _timeEntryRepository.List(); response.Text = string.Format("Week {0} for {1} ({2} {3})", "<week>", person.IzoneUsername.ToUpper(), person.Firstname, person.Lastname); foreach (var timeEntry in timeEntries) { response.Attachments.Add(new SlackResponse { Text = string.Format("{0}: {1} h", timeEntry.Alias, timeEntry.Hours), SlackColor = SlackColor.danger }); } return response; } Person GetPerson(string slackId, string slackUsername) { var person = _personRepository.GetBySlackId(slackId); if (person != null) return person; person = _personRepository.GetBySlackUsername(slackUsername); if (person != null) { // Update Person and save SlackId. person.SlackId = slackId; _personRepository.SetSlackId(person); } return person; } } } <file_sep>using System; using System.Linq; using System.Collections.Generic; using ica.model; namespace ica.database { public class TimeEntryRepository : ITimeEntryRepository { public List<TimeEntry> List() { using (var db = new IzoneContext()) { return db.TimeEntries.Take(10).ToList(); } } double ITimeEntryRepository.TotalHours() { using (var db = new IzoneContext()) { return db.TimeEntries.Sum(x => x.Hours); } } } } <file_sep>using System.Linq; using ica.model; using System.Collections.Generic; using System; namespace ica.database { public class PersonRepository : IPersonRepository { public List<Person> List() { using (var db = new IzoneContext()) { return db.People.ToList(); } } public Person GetBySlackId(string slackId) { using (var db = new IzoneContext()) { return db.People.Where(x => x.SlackId == slackId).FirstOrDefault(); } } public Person GetBySlackUsername(string slackUsername) { using (var db = new IzoneContext()) { return db.People.Where(x => x.SlackUsername == slackUsername).FirstOrDefault(); } } public void SetSlackId(Person person) { using (var db = new IzoneContext()) { var dbPerson = db.People.Where(x => x.SlackUsername == person.SlackUsername).FirstOrDefault(); if (dbPerson == null) throw new Exception(string.Format("Cannot find Person having slack username '{0}'", person.SlackUsername)); dbPerson.SlackId = person.SlackId; db.Update(dbPerson); db.SaveChanges(); } } } } <file_sep>FROM microsoft/dotnet:2.0.0-sdk-jessie COPY . /opt/src WORKDIR /opt/src # Build. RUN dotnet build RUN dotnet test ica.rest.tests/ica.rest.tests.csproj RUN dotnet publish -o /opt/app RUN rm -fr ./!ica.database.migrations WORKDIR /opt/app # Run. EXPOSE 3000 ENV ASPNETCORE_URLS http://*:3000 CMD ["dotnet", "/opt/app/ica.rest.dll", "--server.urls", "http://0.0.0.0:3000"] <file_sep>using ica.model; using System.Collections.Generic; namespace ica.database { public interface IPersonRepository { List<Person> List(); Person GetBySlackId(string slackId); Person GetBySlackUsername(string slackUserName); void SetSlackId(Person person); } } <file_sep>using System; using System.Linq; using System.Collections.Generic; using ica.model; namespace ica.database { public interface ITimeEntryRepository { List<TimeEntry> List(); double TotalHours(); } } <file_sep>namespace ica.model.REST { public class SlackRequestPayload { public string user_id { get; set; } public string user_name { get; set; } } }<file_sep># izone-slack [![Build Status](https://drone.iteam.life/api/badges/Iteam1337/izone-core-api/status.svg)](https://drone.iteam.life/Iteam1337/izone-core-api) ## About This is an API used to connect our daily lives (i.e. Slack) with our time reporting, planning and economy systems. ## Slack The SlackController holds endpoints for slash commands in Slack. They are using features that requires your slash commands to be setup in the context of a Slack App. ## Getting started The project is using dotnet core 2.0 and it is recommended that you have docker and docker-compose installed. You can use a traditional SQL Server installation or you can simply run the docker-compose stack to get a containerized SQL Server. ### Running the stack locally ``` docker-compose up --build ``` ### Tests ``` dotnet test ica.rest.tests/ica.rest.tests.csproj ``` <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace ica.database.migrations.Migrations { public partial class ExtendPeopleDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>("p_firstname", "people_db"); migrationBuilder.AddColumn<string>("p_lastname", "people_db"); migrationBuilder.AddColumn<string>("p_izusername", "people_db"); migrationBuilder.AddColumn<string>("p_email", "people_db"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn("p_firstname", "people_db"); migrationBuilder.DropColumn("p_lastname", "people_db"); migrationBuilder.DropColumn("p_izusername", "people_db"); migrationBuilder.DropColumn("p_email", "people_db"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; namespace ica.database.migrations { public class DBMigrationsContext : DbContext { public DbSet<JobLog> JobLogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionString = Environment.GetEnvironmentVariable("DB__CONNECTIONSTRING"); if (string.IsNullOrEmpty(connectionString)) connectionString = @"Data Source=sql; Database=the-dev-db; User ID=sa; Password=<PASSWORD>;"; optionsBuilder.UseSqlServer(connectionString); } } [Table("job_log_db")] public class JobLog { [Column("jl_id")] public int Id { get; set; } } } <file_sep>using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace ica.database.migrations.Migrations { public partial class SeedJobLogs : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(@" INSERT INTO job_log_db ( jl_job_id ,jl_alias ,jl_description ,jl_executor ,jl_hours ,jl_starttime ,jl_endtime ,jl_gcal_id ) VALUES ( 1 ,'meow' ,'purring and meoweing' ,'acr' ,2.5 ,'2017-01-02 10:15:00' ,'2017-01-02 12:45:00' ,'0123456789abcdef' ) " ); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(@" DELETE FROM job_log_db WHERE 1 = 1 " ); } } } <file_sep>using System; using Xunit; using Moq; using FluentAssertions; using ica.rest.Controllers; using ica.model; using ica.model.REST; using ica.database; using System.Collections.Generic; namespace ica.rest.tests.Controllers { public class SlackControllerTests { private readonly SlackController _slackController; private readonly Mock<IPersonRepository> _personRepository; private readonly Mock<ITimeEntryRepository> _timeEntryRepository; private SlackRequestPayload payload = new SlackRequestPayload { user_id = "C47", user_name = "kittycat" }; private Person person = new Person { Firstname = "Kitty", Lastname = "Cat", IzoneUsername = "KCT", SlackUsername = "kittycat" }; public SlackControllerTests() { _personRepository = new Mock<IPersonRepository>(); _timeEntryRepository = new Mock<ITimeEntryRepository>(); // Some general setups. _personRepository.Setup(x => x.GetBySlackId(It.IsAny<string>())).Returns(person); _timeEntryRepository.Setup(x => x.List()).Returns(new List<TimeEntry>()); // Create the Controller to be tested and inject mocks.. _slackController = new SlackController(_personRepository.Object, _timeEntryRepository.Object); } [Fact] public void POST_slack_calls_PersonRepository() { _slackController.Post(payload); _personRepository.Verify(x => x.GetBySlackId(It.IsAny<string>()), Times.Once()); } [Fact] public void POST_slack_calls_TimeEntryRepository() { _slackController.Post(payload); _timeEntryRepository.Verify(x => x.List(), Times.Once()); } [Fact] public void POST_slack_attempts_to_get_user_by_name_if_not_found_by_id() { var req = new SlackRequestPayload { user_id = "some id", user_name = "some name" }; _personRepository.Setup(x => x.GetBySlackId(req.user_id)).Returns<Person>(null); _personRepository.Setup(x => x.GetBySlackUsername(req.user_name)).Returns(person); _slackController.Post(req); _personRepository.Verify(x => x.GetBySlackId(req.user_id), Times.Once()); _personRepository.Verify(x => x.GetBySlackUsername(req.user_name), Times.Once()); } [Fact] public void POST_slack_attempts_to_update_Person_with_id_if_user_was_mapped_using_name() { var req = new SlackRequestPayload { user_id = "some id", user_name = "some name" }; _personRepository.Setup(x => x.GetBySlackId(req.user_id)).Returns<Person>(null); _personRepository.Setup(x => x.GetBySlackUsername(req.user_name)).Returns(person); _slackController.Post(req); _personRepository.Verify(x => x.SetSlackId(It.IsAny<Person>()), Times.Once()); } [Fact] public void POST_slack_returns_proper_error_message_if_no_Person_can_be_mapped() { _personRepository.Setup(x => x.GetBySlackId(It.IsAny<string>())).Returns<Person>(null); _personRepository.Setup(x => x.GetBySlackUsername(It.IsAny<string>())).Returns<Person>(null); var response =_slackController.Post(payload); response.Text.Should().Be("Something went wrong."); response.Attachments[0].SlackColor.Should().Be(SlackColor.danger); response.Attachments[0].Text.Should().Be(string.Format("Your account needs to be setup in izone before you can use this command. <{0}|{1}>", payload.user_name, payload.user_id)); } } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace ica.database.migrations.Migrations { public partial class SeedPeopleDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(@" INSERT INTO people_db ( p_id ,p_firstname ,p_lastname ,p_izusername ,p_email ,p_slack_id ,p_slack_username ) VALUES ( 1 ,'Alexander' ,'Czigler' ,'acr' ,'<EMAIL>' ,'U0260BV6S' ,'ilix' ) " ); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(@" DELETE FROM people_db WHERE p_id = 1 " ); } } } <file_sep>using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System; using ica.model; namespace ica.database { public class IzoneContext : DbContext { public DbSet<TimeEntry> TimeEntries { get; set; } public DbSet<Person> People { get; set; } public IzoneContext() { Database.SetCommandTimeout(150000); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionString = Environment.GetEnvironmentVariable("DB__CONNECTIONSTRING"); if (string.IsNullOrEmpty(connectionString)) connectionString = @"Data Source=sql; Database=the-dev-db; User ID=sa; Password=<PASSWORD>;"; optionsBuilder.UseSqlServer(connectionString); } } }
eb2957bab8b018f24ba7de84cb5808bd20c339ea
[ "Markdown", "C#", "YAML", "Dockerfile" ]
22
C#
Iteam1337/izone-core-api
0a4f6eee1a2f86c6dd0ac5b281f762f61341f917
e34ac1e9bae779759ddca2b9b46888d72e8e8651
refs/heads/master
<repo_name>Displayr/flipPictographs<file_sep>/examples/table_numeric2d.R xx <- data.frame(A=1:3, B=2:4, C=3:5) rownames(xx) <- c("i", "ii", "iii") p1 <- PictoStdChart(xx) # Scaling p2 <- PictoStdChart(xx*10, show.legend=T) # Layout x3 <- c(Mixed=2, Bus=9, Cyclists=14, Pedestrians=19, SingleLaneBus=20, LightRail=22, DoubleLaneBus=43, HeavyRail=80, SuburbanRail=100) p3 <- PictoStdChart(x3, transpose=T, image="stickman", scale=1, hide.base.image = T, icon.ncol=8, fill.direction="frombottom", label.data.type="count", label.data.align.horizontal = "center") p3b <- PictoStdChart(x3, transpose=T, image="stickman", scale=1, hide.base.image = T, icon.ncol=8, fill.direction="frombottom", hide.label.top = T, label.data.type="count", label.data.align.horizontal = "center") # Spacing # This example has been implemented, but running it will freeze RStudio x4 <- matrix(c(2500,50,70,560,100,650,650,2500,1700,450, 2500,2400,750,650,125,1000,90,840,150,720, 4650,1830,1440,1200,1170,2500,4250,2700,5000,200), byrow=T, ncol=5) p4 <- PictoStdChart(x4, icon.ncol=10, scale=50, total.icons=500, image="waterdrop", label.data.type="count", label.data.align.horizontal="right", pad.row=200, pad.col=200, print.config=T) # Data labels x5 <- c(0.35, 0.28, 0.14, 0.12, 0.09, 0.03, 0) p5 <- PictoStdChart(x5, icon.ncol=5, scale=0.01, transpose=T, hide.base.image = T, fill.direction="frombottom", label.data.type="percentage", total.icons=35) p5b <- PictoStdChart(x5, icon.ncol=5, scale=0.01, transpose=T, hide.base.image = T, fill.direction="frombottom", label.data.type="proportion", total.icons=35) p5c <- PictoStdChart(x5, icon.ncol=5, scale=0.01, transpose=T, hide.base.image = T, fill.direction="frombottom", label.data.type="count", total.icons=35) # Lines x6 <- data.frame(China=c(1,73,58,2100), Japan=c(0,47,16,353), US=c(1,9,2,54), Vietnam=c(0,7,0,213), Philippines=c(0,3,0,8)) rownames(x6) <- c("Aircraft carriers", "Destroyers/frigates", "Submarines", "Fighter/bomber aircraft") p6 <- PictoStdChart(x6, show.lines=T, scale=10, icon.ncol=10,image="circle", label.left.align.horizontal="left", label.left.align.vertical="top", label.top.align.horizontal="left", label.left.width=500, label.font.family="Arial Black", label.font.size=9, label.data.type="count",print.config=T, label.top.height=NA) afflicted <- matrix(c(3.46e8, 3.4e7, 1.2e8, 1e9), 2, 2) papers <- matrix(c(194481, 154562, 1858, 10770), 2, 2) p7a <- PictoStdChart(afflicted, image="stickman", icon.ncol=10, scale=1e7, hide.base.image=T, fill.direction="fromtop", label.data.type="count", label.data.position="header", pad.row=100, pad.col=100) p7b <- PictoStdChart(papers, image="stack", icon.ncol=1, fill.direction="frombottom", scale=500, hide.base.image = T, label.data.type="count", label.data.position="footer") # label colors x8 <- data.frame(ArmedForces=c(2.3e6, 1.4e6), ArtillaryPieces=c(13790,7429), BattleTanks=c(6540,2785), Submarines=c(70,73), CombatAircraft=c(2571,3680), Destroyers=c(17,62)) rownames(x8) <- c("China", "US") p8 <- PictoStdChart(x8, icon.ncol=10, label.font.color="red", label.font.family="Arial Black", show.legend=T, label.data.type="count", label.data.position="header", label.data.align.horizontal = "center") # check padding p9 <- PictoStdChart(xx*100, image="square", icon.palette = "Blues", scale=4, icon.ncol=10, background.color="gold", pad.col=100, pad.row=50, show.lines=T, label.bottom=colnames(x3), hide.label.top=T, hide.label.right=F, hide.label.left=F, hide.label.bottom=T, print.config=F, label.right=rownames(x3), label.left.align.horizontal = "right", label.right.align.horizontal = "left", table.by.row = T, label.top.align.vertical = "center", label.bottom.align.vertical = "center") <file_sep>/R/visualizenumber.R #' Visualizes a number #' #' Shows a number as an htmlwidget. The number can be shown on an oval/rectangle or icon. #' @inherit SinglePicto #' @param x The number to display #' @param display A string describing the visualization output. This can be simply "Number"; or #' a number on a shape ("Oval", "Rectangle", "Donut", "Gauge"); or a number on top of an "Icon"; #' or a "Pictograph" (where the amount of icons filled reflects the size of \code{x}). #' @param border.color Color of the border around "Oval" or "Rectangle") #' @param border.opacity Opacity of border, which should be between 0 and 1. #' @param border.width Width of the border as a proportion of the graphic dimensions. #' @param border.resolution The number of points used to define the border of the circle. #' @param base.color The color of the base graphic when a Pictograph (with the base image shown) #' or a Donut is displayed. For backwards compatibility, \code{base.icon.color} can also be used. #' @param base.opacity Alpha transparency; only used when \code{display} is Donut. #' @param fill.color Color of the shape (Oval or Rectangle) or the icon (for Icon or Pictograph) #' if custom.icon is not used. #' @param fill.opacity Alpha transparency of the Oval or Rectangle. #' @param global.font.family Character; font family for all occurrences of any #' font attribute for the chart unless specified individually. #' @param global.font.color Global font color as a named color in character format #' (e.g. "black") or an a hex code. #' @param background.opacity Transparency of background (0 to 1). This is only valid for #' Number, Oval or Rectangle. #' @param label.data.number.type Format in which \code{x} should be shown. #' One of "Number", "Percentage", "Percentage (no sign)", Scientific". #' @param label.data.decimals Integer; Number of decimals shown in data label. #' @param label.data.1000.separator String placed to separate thousands. #' By default this is a comma. Set to empty string to hide. #' @param label.data.position This is only used for Icon or Pictograph. It can be one of #' "Above", "Below" or "Overlay" (i.e. on to top of the icons). For oval/rectangle it #' is always "Overlay". If it is set to "Above", then the \code{label.data} parameters #' with override the \code{text.above} parameters. If set to "Below", it will override \code{text.below}. #' @param label.data.halign Horizontal alignment of data label. One of "left", "center or "right". #' @param label.data.valign Vertical alignment of data label. One of "top", "middle", "bottom". #' This is ignored if \code{text.above.outside} or \code{text.below.outside} is false. #' @param label.data.pad Vertical space between data label and the edge of the shape/icon in pixels. #' @param label.data.xpad Horizontal space between data label and the edge of the shape/icon in pixels. #' @param text.below Text to show below the Oval/Rectangle/Icon/Pictograph. For Oval and Rectangle #' add "<br>" to add new lines to the text. #' @param text.below.outside Whether \code{text.below} should be shown outside the Oval/Rectangle. #' For Icon/Pictograph, this is always true. #' @param text.below.pad Numeric; Vertical space between \code{text.below} and edge of shape/icon in pixels. #' @param text.below.xpad Numeric; Horizontal space between \code{text.below} and edge of shape/icon in pixels. #' @param text.below.halign Horizontal alignment of \code{text.below}. There is no control #' for vertical alignment because it always aligns with the edge of the window. #' @param text.below.font.family Font family of \code{text.below}. #' @param text.below.font.color Font color of \code{text.below}. #' @param text.below.font.size Font size of \code{text.below}. #' @param text.below.font.weight Weight of \code{text.below}, i.e. one of "bold" or "normal". #' @param text.above Text to show above the Oval/Rectangle/Icon/Pictograph. #' @param text.above.outside Whether \code{text.above} should be shown outside the Oval/Rectangle. #' For Icon/Pictograph, this is always true. #' @param text.above.pad Numeric; Vertical space between \code{text.above} and edge of shape/icon in pixels. #' @param text.above.xpad Numeric; Horizontal space between \code{text.above} and edge of shape/icon in pixels. #' @param text.above.halign Horizontal alignment of \code{text.above}. There is no control #' for vertical alignment because it always aligns with the edge of the window. #' @param text.above.font.family Font family of \code{text.above}. #' @param text.above.font.color Font color of \code{text.above}. #' @param text.above.font.size Font size of \code{text.above}. #' @param text.above.font.weight Weight of \code{text.above}, i.e. one of "bold" or "normal". #' @param hover.text Optional text to show when the cursor hovers above widget. #' @param hover.distance Deprecated. #' @param hover.bg.color Color of the background of the hovertext. #' @param hover.font.family Font family of \code{hover.text}. #' @param hover.font.color Font color of \code{hover.text}. #' @param hover.font.size Font size of \code{hover.text}. #' @param hole.size Numeric between 0 and 1, specifying the size of the hole when \code{display} #' is "Donut" or "Gauge". #' @param segment.gap Numeric between 0 and 1, specifying the gap between the segments #' in the gauge. #' @param maximum.value Numeric value specifying the maximum that \code{x} will be expected to take. #' This value is used to show proportional data #' (i.e. \code{display} is "Donut", "Gauge" or "Pictograph (single icon)"). #' @param minimum.value Numeric value specifying the minimum value that \code{x} is expected to take. #' This value is only used in "Gauge", "Bar" and "Pictograph (single icon)". #' For "Donut" it is always assumed to be zero. #' @param tick.show Whether to show the \code{minimum.value} and \code{maximum.value} when #' \code{display} is "Gauge". #' @param tick.outside Whether to show the ticks inside or outside the gauge. #' @param tick.number.type Format in which \code{x} should be shown. #' One of "Automatic", "Number", "Percentage", "Scientific". If "Automatic" is used, #' then a percentage format will be used if \code{attr(x, "statistic")} or #' \code{attr(x, "format")} is "\%". Otherwise a number format will be used. #' @param tick.decimals Integer; Number of decimals shown in ticks #' @param tick.1000.separator String placed to separate thousands. By default this is a comma. Set to empty string to hide. #' @param tick.prefix Optional text to prepend to ticks. #' @param tick.suffix Optional text to append to ticks. #' @param tick.font.family Font family of \code{tick}. #' @param tick.font.color Font color of \code{tick}. #' @param tick.font.size Font size of \code{tick}. #' @param font.unit Set to 'pt' (default) to get font sizing consistent with textboxes. #' Otherwise fonts will be taken to be specified in pixels. #' @param ... Other parameters passed to \code{iconWithText}. #' @importFrom plotly plot_ly layout toRGB config add_pie add_trace #' @importFrom janitor round_half_up #' @export #' @examples #' VisualizeNumber(4.0, display = "Rectangle", text.above = "Above", text.above.outside = TRUE) #' VisualizeNumber(7.0, display = "Oval", label.data.prefix = "Number: ", label.data.suffix = ".", #' label.data.valign = "bottom", label.data.halign = "right", label.data.pad = 30) #' VisualizeNumber(Sys.Date(), text.above = "The date is", text.below = "today.", #' global.font.color = "white", text.above.font.size = 10, text.below.font.size = 10, #' label.data.font.size = 20, background.color = "grey", background.opacity = 1.0) #' VisualizeNumber(-7, text.below = "FROZEN<br>FOODS", global.font.color = "white", #' text.above.font.size = 10, text.below.font.size = 10, label.data.font.size = 20, #' background.color = "grey", background.opacity = 1.0, text.above.outside = FALSE, #' text.below.outside = FALSE) VisualizeNumber <- function(x, display = c("Oval", "Rectangle", "Number", "Icon", "Donut", "Gauge", "Pictograph")[1], fill.color = rgb(166, 197, 57, maxColorValue = 255), fill.opacity = 0.4, total.icons = NA, global.font.family = "Arial", global.font.color = "#808080", label.data.number.type = c("Automatic", "Number", "Percentage", "Scientific")[1], label.data.decimals = 0, label.data.1000.separator = ",", label.data.position = "Overlay", # only used for icons label.data.prefix = "", label.data.suffix = "", label.data.valign = "middle", label.data.halign = "center", label.data.pad = 0.0, label.data.xpad = 0.0, label.data.font.family = global.font.family, label.data.font.color = global.font.color, label.data.font.size = 16, label.data.font.weight = "normal", text.below = "", text.below.outside = TRUE, text.below.halign = "center", text.below.pad = 0.0, text.below.xpad = 0.0, text.below.font.family = global.font.family, text.below.font.color = global.font.color, text.below.font.size = 10, text.below.font.weight = "normal", text.above = "", text.above.outside = TRUE, text.above.halign = "center", text.above.pad = 0.0, text.above.xpad = 0.0, text.above.font.family = global.font.family, text.above.font.color = global.font.color, text.above.font.size = 10, text.above.font.weight = "normal", border.color = rgb(0.5, 0.5, 0.5), border.opacity = 0.5, border.width = 0.0, border.resolution = 1000, segment.gap = 0.000, hole.size = 0.8, tick.outside = TRUE, tick.show = TRUE, tick.font.family = global.font.family, tick.font.color = global.font.color, tick.font.size = 8, tick.number.type = label.data.number.type, tick.decimals = label.data.decimals, tick.1000.separator = label.data.1000.separator, tick.prefix = "", tick.suffix = "", minimum.value = 0.0, maximum.value = NA, base.icon.color = "", # backward compatability base.color = base.icon.color, base.opacity = fill.opacity, background.color = rgb(1, 1, 1), background.opacity = 0, hover.text = "", hover.distance = 0.2, hover.bg.color = rgb(0.5,0.5,0.5), hover.font.color = rgb(1,1,1), hover.font.size = 9, hover.font.family = global.font.family, font.unit = "pt", margin.left = 0, margin.right = 0, margin.top = 0, margin.bottom = 0, ...) { display <- switch(tolower(display), oval = "circle", circle = "circle", "number in an oval" = "circle", rectangle = "rectangle", square = "rectangle", "number in a rectangle" = "rectangle", number = "number", donut = "donut", "number in a donut" = "donut", "number on a donut" = "donut", gauge = "gauge", "number in a gauge" = "gauge", "number on a gauge" = "gauge", bar = "bar", "number in a bar" = "bar", "number on a bar" = "bar", icon = "icon", "number on an icon" = "icon", "pictograph (single icon)" = "pictograph - single", "pictograph - single icon" = "pictograph - single", "pictograph (repeated icons)" = "pictograph - repeated", "pictograph - repeated icons" = "pictograph - repeated", "circle") # default if (tolower(font.unit) %in% c("pt", "point", "points")) { fsc <- 1.3333 label.data.font.size = round(fsc * label.data.font.size, 0) text.above.font.size = round(fsc * text.above.font.size, 0) text.below.font.size = round(fsc * text.below.font.size, 0) tick.font.size = round(fsc * tick.font.size, 0) hover.font.size = round(fsc * hover.font.size, 0) } if (display == "number") { opacity <- 0.0 border.width <- 0.0 } if (border.width < 0 || border.width >= 0.5) { warning("Border width must be between 0 and 0.5.") border.width <- 0 } if (label.data.number.type == "Automatic" && (isTRUE(grepl("%", attr(x, "statistic"))) || isTRUE(grepl("%", attr(x, "format"))))) { # If number.type is percentage, we typically expect inputs # to be decimals in [0.00, 1.00] # But when number.type is automatic, we check that # range is not incorrectly specified (bad defaults on old std R pages) # Note that manually setting type to percentage will avoid this label.data.number.type <- "Percentage" if (isTRUE(maximum.value == 100)) maximum.value <- 1 } # Once we have used statistic attribute to set label.data.number.type # we can parse inputs and discard the attribute if (any(class(x) %in% c("Date", "POSIXct", "POSIXlt"))) x <- as.character(x) if (isTRUE(grepl("%", attr(x, "statistic")))) x <- x/100 if (isTRUE(grepl("%", attr(maximum.value, "statistic")))) maximum.value <- maximum.value/100 if (isTRUE(grepl("%", attr(minimum.value, "statistic")))) minimum.value <- minimum.value/100 # Construct formatted string of x is.percent <- (grepl("^Percentage", label.data.number.type)) # includes "Percentage (no sign)" suffix.doesnt.use.percent <- !any(grepl("%", label.data.suffix)) tmp.percent <- if (label.data.number.type == "Percentage" && suffix.doesnt.use.percent) "%" tmp.format <- if (label.data.number.type == "Scientific") "e" else "f" if (is.na(x) || is.null(x)) label.str <- "NA" else { if (!is.numeric(x) || label.data.number.type == "Scientific") x.round <- x else x.round <- as.numeric(round_half_up(if (is.percent) x * 100 else x, label.data.decimals)) label.str <- paste0(label.data.prefix, formatC(x.round, format = tmp.format, digits = label.data.decimals, big.mark = label.data.1000.separator), tmp.percent, label.data.suffix) } if (is.na(x) || is.null(x)) x <- 0 if (display %in% c("icon", "pictograph - single", "pictograph - repeated")) { value <- if (display == "icon") 1.0 else x if (!is.numeric(value)) stop("Input value for pictographs cannot be non-numeric.") if (display %in% c("icon", "pictograph - single")) total.icons <- 1.0 if (display == "pictograph - single") { if (is.null(minimum.value) || !is.finite(minimum.value)) minimum.value <- 0.0 if (maximum.value <= minimum.value) stop("'Maximum value' (", maximum.value, ") must be greater than the ", "'Minimum value' (", minimum.value, ").") value <- (x - minimum.value)/(maximum.value - minimum.value) if (value > 1) stop("Input data cannot be greater 'Maximum value'. ", "Change 'Display' to 'Pictograph (repeated icons)' to show more than 1 icon.\n") if (value < 0) stop("Input data cannot be smaller than 'Minimum value'.") maximum.value <- 1.0 } if (label.data.position %in% c("Above icons", "Below icons")) { pos <- if (label.data.position == "Above icons") "above" else "below" assign(paste0("text.", pos), label.str) assign(paste0("text.", pos, ".halign"), label.data.halign) assign(paste0("text.", pos, ".valign"), label.data.valign) assign(paste0("text.", pos, ".pad"), label.data.pad) assign(paste0("text.", pos, ".xpad"), label.data.xpad) assign(paste0("text.", pos, ".font.family"), label.data.font.family) assign(paste0("text.", pos, ".font.color"), label.data.font.color) assign(paste0("text.", pos, ".font.size"), label.data.font.size) assign(paste0("text.", pos, ".font.weight"), label.data.font.weight) label.str <- "" } if (label.data.position == "None") label.str <- "" return(iconsWithText(value, fill.icon.color = fill.color, base.icon.color = base.color, maximum.value = maximum.value, total.icons = total.icons, ..., # other icon parameters? text.overlay = label.str, text.overlay.halign = tolower(label.data.halign), text.overlay.valign = tolower(label.data.valign), text.overlay.pad = label.data.pad, text.overlay.xpad = label.data.xpad, text.overlay.font.family = label.data.font.family, text.overlay.font.color = label.data.font.color, text.overlay.font.size = label.data.font.size, text.overlay.font.weight = tolower(label.data.font.weight), text.below = text.below, text.below.font.weight = tolower(text.below.font.weight), text.below.halign = tolower(text.below.halign), text.below.pad = text.below.pad, text.below.xpad = text.below.xpad, text.below.font.family = text.below.font.family, text.below.font.color = text.below.font.color, text.below.font.size = text.below.font.size, text.above = text.above, text.above.halign = tolower(text.above.halign), text.above.pad = text.above.pad, text.above.xpad = text.above.xpad, text.above.font.family = text.above.font.family, text.above.font.color = text.above.font.color, text.above.font.size = text.above.font.size, text.above.font.weight = tolower(text.above.font.weight), background.color = if (background.opacity > 0) background.color else "transparent", margin.top = margin.top, margin.right = margin.right, margin.bottom = margin.bottom, margin.left = margin.left)) } if (display %in% c("donut", "gauge", "bar")) { if (!is.numeric(x) || !is.finite(x)) stop("Input data is non-numeric") if (!any(nzchar(base.color))) base.color <- rgb(230, 230, 230, maxColorValue = 255) if (is.na(maximum.value)) maximum.value <- 1 if (display == "donut") minimum.value <- 0.0 if (maximum.value <= minimum.value) stop("'Maximum value' (", maximum.value, ") must be greater than the 'Minimum value' (", minimum.value, ").") prop <- (x - minimum.value)/(maximum.value - minimum.value) if (prop > 1) stop("Input data cannot be greater than 'Maximum value'.") if (prop < 0 && display == "donut") stop("Input data cannot be smaller than zero.") if (prop < 0 && display == "gauge") stop("Input data cannot be smaller than 'Minimum value'.") } if (display == "donut") { p <- plot_ly(values = c(prop, 1 - prop), hoverinfo = "skip", textinfo = "none", marker = list(colors = c(toRGB(fill.color, alpha = fill.opacity), toRGB(base.color, alpha = base.opacity)), line = list(width = border.width * 100, color = toRGB(border.color, alpha = border.opacity)))) p <- add_pie(p, hole = hole.size, direction = "clockwise", sort = FALSE) shapes <- NULL } else if (display == "gauge") { p <- plot_ly(x = c(0, 1), y = c(0, 1), type = "scatter", mode = "none", cliponaxis = FALSE, hoverinfo = "skip") fill.segment <- pathToShape(segmentPath(c(0, prop - segment.gap), hole.size, border.resolution), fill.color, fill.opacity) bg.segment <- pathToShape(segmentPath(c(prop + segment.gap, 1), hole.size, border.resolution), base.color, base.opacity) shapes <- list(fill.segment, bg.segment) } else if (display == "bar") { p <- plot_ly(x = c(0,1), y = c(0, 1), type = "scatter", mode = "none", cliponaxis = FALSE, hoverinfo = "skip") fill.shape <- list(type = "rectangle", x0 = 0, x1 = prop, y0 = 0, y1 = 1, yref = "y", xref = "x", fillcolor = fill.color, opacity = fill.opacity, layer = "above", line = list(width = 0)) shapes <- fill.shape } else { p <- plot_ly(x = c(0,1), y = c(0, 1), type = "scatter", mode = "none", cliponaxis = FALSE, hoverinfo = "skip") border.path <- NULL if (border.width > 0) { border.path <- if (display == "rectangle") rectangleBorder(border.width) else circleBorder(border.width, border.resolution) } fill.shape <- list(type = display, x0 = border.width, x1 = (1 - border.width), y0 = border.width, y1 = 1 - border.width, yref = "y", xref = "x", fillcolor = fill.color, opacity = fill.opacity, layer = "above", line = list(width = 0)) shapes <- list(pathToShape(border.path, border.color, border.opacity), fill.shape) } # Position data and text labels data.yanchor <- NA if (tolower(label.data.valign) == "middle") { if (isTextInside(text.above, text.above.outside) && isTextInside(text.below, text.below.outside)) data.yanchor <- "middle" else if (isTextInside(text.above, text.above.outside)) data.yanchor <- "top" else if (isTextInside(text.below, text.below.outside)) data.yanchor <- "bottom" } annot.data <- setText(label.str, tolower(label.data.valign), tolower(label.data.halign), font = list(family = label.data.font.family, color = label.data.font.color, size = label.data.font.size), label.data.font.weight, xmax = if (display == "bar") prop else 1.0, xshift = label.data.xpad, yshift = label.data.pad, yanchor = data.yanchor) if (display == "bar" && label.data.halign == "right") annot.data$x <- prop if (any(nzchar(hover.text))) p <- add_trace(p, type = "scatter", mode = "markers", x = annot.data$x, y = annot.data$y, hoverinfo = "text", hovertext = hover.text, values = NULL, textinfo = NULL, marker = list(color="transparent", size = max(annot.data$xshift, annot.data$yshift) + annot.data$font$size)) if (isTRUE(data.yanchor == "middle") && isTextInside(text.above, text.above.outside)) text.above.pad <- text.above.pad + (getVerticalSpace(annot.data))/2 annot.above <- setText(text.above, "top", tolower(text.above.halign), font = list(family = text.above.font.family, color = text.above.font.color, size = text.above.font.size), text.above.font.weight, xmax = if (display == "bar") prop else 1.0, text.above.outside, xshift = text.above.xpad, yshift = text.above.pad) if (isTRUE(data.yanchor == "middle") && isTextInside(text.below, text.below.outside)) text.below.pad <- text.below.pad + (getVerticalSpace(annot.data))/2 annot.below <- setText(text.below, "bottom", tolower(text.below.halign), font = list(family = text.below.font.family, color = text.below.font.color, size = text.below.font.size), text.below.font.weight, xmax = if (display == "bar") prop else 1.0, text.below.outside, xshift = text.below.xpad, yshift = text.below.pad) tick0 <- NULL tick1 <- NULL if (display == "gauge" && tick.show) { if (tick.number.type == "Automatic") tick.number.type <- label.data.number.type tmp.vals <- c(minimum.value, maximum.value) is.percent <- grepl("^Percentage", tick.number.type) tmp.percent <- if (tick.number.type == "Percentage") "%" else "" tmp.format <- if (tick.number.type == "Scientific") "e" else "f" tick.str <- paste0(tick.prefix, formatC(if (is.percent) tmp.vals * 100 else tmp.vals, format = tmp.format, digits = tick.decimals, big.mark = tick.1000.separator), tmp.percent, tick.suffix) tick.font = list(family = tick.font.family, size = tick.font.size, color = tick.font.color) tick.align <- if (tick.outside) "top" else "bottom" pos <- (1 - hole.size)/4 tick0 <- list(text = tick.str[1], font = tick.font, x = pos, y = 0, yshift = 0, yanchor = tick.align, xanchor = "center", showarrow = FALSE) tick1 <- list(text = tick.str[2], font = tick.font, x = 1 - pos, y = 0, yshift = 0, yanchor = tick.align, xanchor = "center", showarrow = FALSE) } # Adjust margins so that labels do not fall off margin.top <- margin.top + text.above.outside * getVerticalSpace(annot.above, direction = "top") margin.bottom <- margin.bottom + max(text.below.outside * getVerticalSpace(annot.below, direction = "bottom"), tick.outside * getVerticalSpace(tick0), tick.outside * getVerticalSpace(tick1)) margin.left <- margin.left + max(getLeftSpace(annot.above), getLeftSpace(annot.data), getLeftSpace(annot.below)) margin.right <- margin.right + max(getRightSpace(annot.above), getRightSpace(annot.data), getRightSpace(annot.below)) p <- layout(p, margin = list(l = margin.left, r = margin.right, t = margin.top, b = margin.bottom, pad = 0, autoexpand = FALSE), showlegend = FALSE, xaxis = list(showticklabels = FALSE, showgrid = FALSE, zeroline = FALSE, range = c(0,1), fixedrange = TRUE, constrain = "domain"), yaxis = list(showticklabels = FALSE, showgrid = FALSE, zeroline = FALSE, range = c(0,1), fixedrange = TRUE, constrain = "domain", scaleratio = 0.5, scaleanchor = if (display == "gauge") "x" else NULL), plot_bgcolor = toRGB(rgb(0,0,0), alpha = 0.0), paper_bgcolor = toRGB(background.color, alpha = background.opacity), shapes = shapes, annotations = list(annot.data, annot.above, annot.below, tick0, tick1), hoverlabel = list(bgcolor = hover.bg.color, bordercolor = hover.bg.color, font = list(color = hover.font.color, size = hover.font.size, family = hover.font.family)), hovermode = "closest", hoverdistance = hover.distance, autosize = TRUE) p <- config(p, displayModeBar = FALSE, responsive = TRUE) p$sizingPolicy$browser$padding <- 0 class(p) <- c(class(p), "visualization-selector") attr(p, "can-run-in-root-dom") <- TRUE return(p) } setText <- function(text, yalign, xalign, font, font.weight, # parameters always supplied outside = NA, yshift = 0, xshift = 0, yanchor = NA, xmax = 1.0) { if (!any(nzchar(text))) return (NULL) xpos <- switch(xalign, left = 0.0, center = xmax/2, right = xmax) if (!is.na(outside) && !outside) ypos <- 0.5 else ypos <- switch(yalign, bottom = 0.0, middle = 0.5, top = 1.0) eval(yanchor) if (is.na(outside) && is.na(yanchor)) # aligning text inside the shape yanchor <- yalign else if (is.na(yanchor)) # aligning text outside the shape yanchor <- switch(yalign, top = "bottom", bottom = "top", "middle") if (yanchor == "top") yshift <- -1 * yshift if (tolower(font.weight) == "bold") text <- paste0("<b>", text, "</b>") return(list(text = text, font = font, x = xpos, y = ypos, showarrow = FALSE, xshift = xshift, yshift = yshift, xanchor = xalign, yanchor = yanchor)) } #' @importFrom verbs Sum getVerticalSpace <- function(annot, direction = "any") { if (is.null(annot)) return(0.0) if (direction == "top" && (annot$yshift < 0 || annot$y < 1)) return(0.0) if (direction == "bottom" && (annot$yshift > 0 || annot$y > 0)) return(0.0) nline <- Sum(gregexpr("<br>", annot$text)[[1]] > -1, remove.missing = FALSE) + 1 return (abs(annot$yshift) + (annot$font$size * nline) + 5) } getLeftSpace <- function(annot) { if (is.null(annot) || annot$x > 0.0) return (0.0) else return(max(0.0, -1 * annot$xshift)) } getRightSpace <- function(annot) { if (is.null(annot) || annot$x < 1.0) return (0.0) else return(max(0.0, annot$xshift)) } isTextInside <- function(text, outside) { if (outside) return(FALSE) if (!any(nzchar(text))) return(FALSE) return(TRUE) } <file_sep>/examples/factor1d.R require(flipPictographs) # Handling a vector of factors # K is set to be the length of the factor excluding NAs # This is appropriate for both pick-one questions f1 <- factor(sample(1:4, size=150, replace=T), labels=c("None", "Some", "Mostly", "All")) pf1 <- PictoStdChart(f1) pf1b <- PictoStdChart(f1, hide.base.image = T) pf1c <- PictoStdChart(f1, hide.base.image = T, label.data.type="percentage", show.legend=T, label.data.align.horizontal="left") pf1d <- PictoStdChart(f1, hide.base.image = T, label.data.type="count", show.legend=T) pf1e <- PictoStdChart(f1, hide.base.image = T, label.data.type="proportion", show.legend=T) # For bar and column the defaults set on the Std R Page should be # show.legend=T, hide.base.image=T b1 <- PictoStdChart(f1, mode="bar", show.legend=T, label.data.type="percentage", label.data.position="footer", label.data.align.horizontal="center") b2 <- PictoStdChart(f1, mode="bar", show.legend=T, gradient.col1="blue", gradient.col2="orange", label.font="helvetica", label.size=16, label.weight="bold", label.data.type="percentage", label.data.align.horizontal="left") c1 <- PictoStdChart(f1, mode="column", show.legend=T, gradient.col1="blue", gradient.col2="orange", label.data.type="percentage", label.data.position="footer", label.data.align.horizontal="left") # What about pick-any questions? # Also need to look at function calls using the 'by' parameter <file_sep>/R/iconswithtext.R # Similar to single picto but has more flexibility with text labels. # Arguments are designed to match with PrettyNumber #' @importFrom verbs Sum iconsWithText <- function (x, total.icons = NA, image = "star", base.image = "", is.custom.url = FALSE, number.rows = NA, number.cols = NA, width.height.ratio = 1, layout = NA, scale = 1, maximum.value = NA, hide.base.image = FALSE, fill.direction = "fromleft", fill.icon.color = "black", base.icon.color = "", background.color = "transparent", # background.fill.opacity not supported auto.size = TRUE, icon.width = 50, pad.row = 0, pad.col = 0, margin = 0, margin.top = margin, # not used margin.right = margin, margin.bottom = margin, margin.left = margin, global.font.family = "Arial", global.font.color = rgb(44, 44, 44, maxColorValue = 255), text.overlay = "", text.overlay.halign = "center", text.overlay.valign = "middle", text.overlay.pad = 0.0, test.overlap.xpad = 0.0, text.overlay.font.family = global.font.family, text.overlay.font.color = global.font.color, text.overlay.font.size = 10, text.overlay.font.weight = "normal", text.below = "", text.below.halign = "center", text.below.pad = 0.0, text.below.xpad = 0.0, text.below.font.family = global.font.family, text.below.font.color = global.font.color, text.below.font.size = 10, text.below.font.weight = "normal", text.above = "", text.above.halign = "center", text.above.pad = 0.0, text.above.xpad = 0.0, text.above.font.family = global.font.family, text.above.font.color = global.font.color, text.above.font.size = 10, text.above.font.weight = "normal", print.config = FALSE, x.limit = 1000, ...) { if (!(length(x) == 1 && x >= 0)) stop("Input data must be a single positive number\n") if (scale <= 0 && is.na(maximum.value)) stop("Scale must be greater than zero\n") if (isTRUE(grepl("%", attr(scale, "statistic")))) scale <- scale/100 if (!is.na(maximum.value) && scale != 1) warning("Parameter scale overridden by maximum value\n") if (!is.na(total.icons) && total.icons <= 0) stop("Total icons must be greater than zero\n") if (!is.na(maximum.value)) { if (maximum.value <= 0) stop("Maximum value must be greater than zero\n") if (maximum.value < x) stop("Input data cannot be greater than 'Maximum value'. ", "Change 'Display' to 'Pictograph (repeated icons)' to show more than 1 icon.\n") if (is.na(total.icons)) total.icons <- maximum.value scale <- maximum.value/total.icons } # Some parameter substitutions for R GUI Controls if (is.custom.url) { fill.icon.color <- "" base.icon.color <- "" hide.base.image <- nchar(base.image) == 0 } else { image <- gsub(" ", "", tolower(image)) } fill.direction <- gsub(" ", "", tolower(fill.direction)) if (auto.size) icon.width <- 50 if (!is.na(total.icons) && total.icons == 1) { # Parameters not supplied in Pictographs - Single layout <- "Width-to-height ratio" pad.row <- 0 pad.col <- 0 } if (!is.na(layout)) { if (layout != "Width-to-height ratio") width.height.ratio = 1 if (layout != "Number of rows") number.rows = NA if (layout != "Number of columns") number.cols = NA } # Determine plot values if (!is.na(x.limit) && x/scale > x.limit) { scale <- scale * 10^{floor(log10(x/scale)) - 1} warning("The input value is too large to plot, and the Scale has been set to ", scale, ". Consider entering a larger Scale value in the inputs.\n") } x <- x/scale if (is.na(total.icons)) total.icons <- ceiling(x) if (length(total.icons) != 1 && total.icons > 0) stop("The total icons must be a single numeric value and greater than zero\n") if (!is.na(number.rows) && (number.rows <= 0 || number.rows != ceiling(number.rows))) stop("The number of rows must be a positive integer\n") if (!is.na(number.rows)) number.rows <- min(number.rows, total.icons) if (!is.na(number.cols) && (number.cols <= 0 || number.cols != ceiling(number.cols))) stop("The number of columns must be a positive integer\n") if (!is.na(number.cols)) number.cols <- min(number.cols, total.icons) if (width.height.ratio <= 0) stop("The width-height ratio must be greater than zero\n") if (icon.width <= 0) stop("icon width must be greater than zero\n") prop <- x/total.icons if (prop < 0 | prop > 1) stop("Input data must be between 0 and total icons\n") if (round(total.icons) != total.icons) stop("The number of total icons must be an integer\n") # Determine layout based on which parameters are supplied layout.str <- "" icon.WHratio <- if (is.custom.url) getWidthHeightRatio(image) * (1 + pad.col) / (1 + pad.row) else imageWHRatio[image] * (1 + pad.col) / (1 + pad.row) if (!is.na(number.rows) && is.na(number.cols)) { layout.str <- paste(",\"numRows\":", number.rows, sep="") number.cols <- ceiling(total.icons/number.rows) } else if (!is.na(number.cols)) { layout.str <- paste(",\"numCols\":", number.cols, sep="") number.rows <- ceiling(total.icons/number.cols) } else { number.rows <- max(1, round(sqrt(icon.WHratio/width.height.ratio * total.icons))) if (number.rows > total.icons) number.rows <- total.icons number.cols <- ceiling(total.icons/number.rows) layout.str <- paste(",\"numRows\":", number.rows, sep="") } image.type <- "url" if (image %in% c("circle", "square")) image.type <- image base.image.str <- "" if (!hide.base.image) { if (nchar(base.icon.color) > 0) base.icon.color <- paste(base.icon.color, ":", sep="") base.image.url <- if (is.custom.url) { checkImageUrl(base.image) base.image } else imageURL[image] base.image.str <- if (nchar(base.image.url) == 0 && is.custom.url) "" else paste(",\"baseImage\":\"", image.type, ":", base.icon.color, base.image.url, "\"", sep="") } image.url <- if (is.custom.url) image else imageURL[image] variable.image <- if (is.custom.url) paste(image.type, ":", fill.direction, ":", image.url, sep="") else paste(image.type, ":", fill.direction, ":", fill.icon.color, ":", image.url, sep="") # size of pictograph output dim.str <- "" icon.size.str <- "" if (auto.size) dim.str <- "\"rowHeights\":[\"proportion:1\"], \"colWidths\":[\"flexible:graphic\"]" else { dim.str <- "\"rowHeights\":[\"fixedsize:graphic\"], \"colWidths\":[\"fixedsize:graphic\"]" icon.size.str <- paste0(",\"imageWidth\":", icon.width) } # Text labels label.overlay.str <- "" label.above.str <- "" label.below.str <- "" # Adjust margins to fit text labels # padding format: top right bottom left pad.above.left <- pad.above.right <- pad.above.top <- pad.above.bottom <- 0 pad.below.left <- pad.below.right <- pad.below.top <- pad.below.bottom <- 0 if (any(nzchar(text.above))) { if (text.above.halign == "left") pad.above.left <- text.above.xpad if (text.above.halign == "right") pad.above.right <- text.above.xpad } if (any(nzchar(text.below))) { if (text.below.halign == "left") pad.below.left <- text.below.xpad if (text.below.halign == "right") pad.below.right <- text.below.xpad } margin.left <- margin.left + max(0, -pad.above.left, -pad.below.left) margin.right <- margin.right + max(0, pad.above.right, pad.below.right) if (any(nzchar(text.above))) label.above.str <- sprintf(paste0(", \"table-header\":{\"padding\": \"%f %f %f %f\", ", "\"text\":\"%s\", \"font-size\":\"%fpx\", \"font-family\":\"%s\", ", "\"font-color\":\"%s\", \"font-weight\":\"%s\", ", "\"horizontal-align\":\"%s\", \"vertical-align\":\"top\"}"), margin.top + 1, margin.right - pad.above.right + 1, max(0, text.above.pad) + 1, margin.left + pad.above.left + 1, cleanPictographLabels(text.above), text.above.font.size, text.above.font.family, text.above.font.color, text.above.font.weight, text.above.halign) if (any(nzchar(text.below))) label.below.str <- sprintf(paste0(", \"table-footer\":{\"padding\": \"%f %f %f %f\", ", "\"text\":\"%s\", \"font-size\":\"%fpx\", \"font-family\":\"%s\", ", "\"font-color\":\"%s\", \"font-weight\":\"%s\", ", "\"horizontal-align\":\"%s\", \"vertical-align\":\"bottom\"}"), max(text.below.pad, 0) + 1, margin.right - pad.below.right + 1, margin.bottom + 1, margin.left + pad.below.left + 1, cleanPictographLabels(text.below), text.below.font.size, text.below.font.family, text.below.font.color, text.below.font.weight, text.below.halign) if (any(nzchar(text.overlay))) { xpos <- if (text.overlay.halign == "left") 0 else if (text.overlay.halign == "right") number.cols else number.cols/2 ypos <- if (text.overlay.valign == "top") 0 else if (text.overlay.valign == "bottom") number.rows else number.rows/2 label.overlay.str <- sprintf(paste0(",\"floatingLabels\":[{\"position\":\"%f:%f\", ", "\"text\":\"%s\", \"font-size\":\"%fpx\", \"font-family\":\"%s\", ", "\"font-color\":\"%s\", \"font-weight\":\"%s\", \"horizontal-align\":\"%s\"}]"), ypos, xpos, cleanPictographLabels(text.overlay), text.overlay.font.size, text.overlay.font.family, text.overlay.font.color, text.overlay.font.weight, text.overlay.halign) } pad.around.icons <- sprintf(",\"padding\":\"%f %f %f %f\"", margin.top, margin.right, margin.bottom, margin.left) json.string <- paste0("{\"table\": {", dim.str, ",\"rows\":[[{\"type\":\"graphic\", \"value\":{", "\"proportion\":", prop, pad.around.icons, ",\"numImages\":", total.icons, label.overlay.str, icon.size.str, layout.str, ",\"rowGutter\":", pad.row, ",\"columnGutter\":", pad.col, ",\"variableImage\":\"", variable.image, "\"", base.image.str, "}}]]}", label.above.str, label.below.str, ",\"background-color\":\"", background.color, "\"}") if (print.config) cat(json.string) res <- graphic(json.string) class(res) <- c(class(res), "visualization-selector") return(res) } cleanPictographLabels <- function(x) { # New line characters were causing errors in the JSON # Note these can be coded as \n or \r x <- gsub("\\s", " ", x) # Escape backslashes in labels x <- gsub("\\", "\\\\", x, fixed = TRUE) # These characters used to be shown as text but that is # probably not what the user wants to see x <- gsub("&nbsp;", " ", x) x <- gsub('"', '\\"', x, fixed = TRUE) return(x) } <file_sep>/tests/testthat/test-getwidthheightratio.R context("getWidthHeightRatio") test_that("getWidthHeightRatio", { expect_equal(getWidthHeightRatio("https://wiki.q-researchsoftware.com/images/a/ab/Dizzy_drunk_color.png"), 0.529) }) test_that("getImage", { expect_error(getImage("https://wiki.q-researchsoftware.com/images/a/ab/Dizzy_drunk_color.png"), NA) expect_error(getImage("https://wiki.q-researchsoftware.com/wiki/File:Dizzy_drunk_color.png"), "The url content type is 'text/html'") expect_error(getImage("google.com"), "The url content type is 'text/html'") expect_error(getImage("www.google.com"), "The url content type is 'text/html'") }) test_that("checkImageUrl", { expect_error(checkImageUrl("https://wiki.q-researchsoftware.com/images/a/ab/Dizzy_drunk_color.png"), NA) expect_error(checkImageUrl("www.google.com"), "The url content type is 'text/html'") }) <file_sep>/tests/testthat.R library(testthat) library(flipPictographs) library(flipTables) library(flipTransformations) test_check("flipPictographs") <file_sep>/R/SummarizeVariable.R #' Summarizes a numeric or categorical variable for plotting #' @param x The input variable to summarize #' @param type The type of summary statistic to output. This should be one of 'Average', 'Sum', 'Most frequent' or 'Percentage'. #' @param subset Option logical vector of the same length as \code{x} indicating whether or not to include #' an observation in \code{x}. #' @param weights Sampling or replication weights. This is a numeric vector of the same length as \code{x}. #' @param category A comma-seperated list of the name or indices of the categories to include for 'Percentage'. #' @importFrom flipStatistics Mean WeightedTable #' @importFrom flipTransformations AsNumeric TextAsVector #' @importFrom flipU ConvertCommaSeparatedStringToVector #' @importFrom verbs Sum #' @export SummarizeVariable <- function(x, type = c("Average", "Sum", "Percentage")[1], weights = NULL, subset = NULL, category = NULL) { if (!is.null(weights) && length(weights) > 1 && length(weights) != length(x)) stop("Weights should be the same length as the input variable") if (!is.null(subset) && length(subset) > 1) { if (length(subset) != length(x)) stop("Filters should have the same length as the input variable") x <- x[subset] if (!is.null(weights)) weights <- weights[subset] } if (grepl("Average", type) || grepl("Mean", type)) return(Mean(AsNumeric(x, binary = FALSE), weights = weights)) if (grepl("Sum", type)) return(Sum(x, weights = weights)) # Convert QDate to Factors (Dates do not give sensible result for Average or Sum either way) if (!is.null(attr(x, "QDate"))) x <- attr(x, "QDate") if (grepl("Most frequent", type)) { counts <- sort(WeightedTable(x, weights = weights), decreasing = TRUE) tmp <- names(counts)[1] if (is.numeric(x)) return(as.numeric(tmp)) else return(x[x == tmp][1]) } # Compute "Percentage" selected # for binary variable if (isTRUE(attr(x, "questiontype") == "PickAny") || isTRUE(attr(x, "questiontype") == "PickAnyGrid") || is.logical(x)) { if (any(nzchar(category))) warning("Showing percentage selected (ignoring Category '", category, "').") return(as_pct(Mean(x, weights = weights))) } # "Percentage" for numeric variable if (is.numeric(x) && any(nzchar(category))) { if (grepl("\\d+\\s*-\\s*\\d+", category)) { cat.range <- as.numeric(trimws(strsplit(category, split = "-")[[1]])) if (length(cat.range) == 2 && all(!is.na(cat.range))) { in.range <- x >= min(cat.range) & x <= max(cat.range) return(as_pct(Mean(in.range, weights = weights))) } } else if (is.numeric(x) && any(x != round(x, 0))) warning("A numeric variable was supplied. Specify a range as the category (e.g. '1-5') or round variables to integers") } category.names <- levels(as.factor(x)) # only interested in labels so don't need to worry about values if (!any(nzchar(category))) stop("Select one or more categories from \"", paste(category.names, collapse = "\", \""), "\".") category.selected <- ConvertCommaSeparatedStringToVector(as.character(category), text.qualifier = "\"") ind.not.selected <- which(!category.selected %in% category.names) if (length(ind.not.selected) > 0 && any(grepl(",", category.names, fixed = TRUE))) warning("Categories \"", paste(category.selected[ind.not.selected], collapse = "\", \""), "\" not found. Use double-quotes to surround category names containing commas.") # "Percentage" for categorical variable (the section above is just to get warning) is.selected <- x %in% category.selected is.selected[is.na(x)] <- NA # '%in%' converts NA to FALSE return(as_pct(Mean(is.selected, weights = weights))) } as_pct <- function (x) { x <- x * 100 attr(x, "statistic") <- "%" return(x) } <file_sep>/examples/bar_numeric1d.R # In StdRPage set hide.base.image=T x1 <- c(First=1, SecondLonger=4.5, Third=3) x2 <- 100*x1 p1 <- PictoStdChart(x1, mode="bar") p2 <- PictoStdChart(x1) p2b <- PictoStdChart(x1, show.legend=T, mode="bar") p2c <- PictoStdChart(x1, show.legend=T, mode="bar", pad.legend=3, legend.icon.color="red") p2d <- PictoStdChart(x1, show.legend=T, mode="bar", pad.legend=3, background.color="green") p2e <- PictoStdChart(x1, total.icons=10, show.legend=T, mode="bar", pad.legend=3, background.color="green") p2f <- PictoStdChart(x2, show.legend=T, mode="bar", background.color="green", hide.label.right=F, pad.legend=0) # Padding p3a <- PictoStdChart(x1, total.icons=10, show.legend=T, mode="bar", pad.legend=3, background.color="green", pad.icon.row=0.5) p3c <- PictoStdChart(x1, total.icons=10, icon.ncol=2, show.legend=T, mode="bar", pad.legend=3, background.color="green", pad.icon.row=0.5, show.lines=T) p3b <- PictoStdChart(x1, total.icons=10, show.legend=T, mode="bar", pad.legend=3, background.color="green", pad.icon.col=0.5) # Data labels (error) p4a <- PictoStdChart(x1, total.icons=10, show.legend=T, mode="bar", pad.legend=3, background.color="green", label.data.type="count") p4b <- PictoStdChart(x1, show.legend=T, mode="bar", label.data.type="percentage") p5 <- PictoStdChart(x1, show.legend=T, mode="bar", hide.label.right = F) p5b <- PictoStdChart(x1, show.legend=T, mode="bar", hide.label.right = F, hide.label.left=T) p5c <- PictoStdChart(x1, show.legend=T, mode="bar", hide.label.right = F, hide.label.left=F) # Sublabels (direct) lab2 <- letters[1:3] p6 <- PictoStdChart(x1, label.left2=lab2, label.font.family="Impact") p6b <- PictoStdChart(x1, label.left2=lab2, label.left.font.family="Impact", label.left.font.size=20) p6c <- PictoStdChart(x1, label.left2=lab2, label.left.font.family="Impact", label.left.font.size=20, label.left2.font.size=5) p7 <- PictoStdChart(x1, mode="bar", hide.label.right = F, label.font.family = "Impact") p7b <- PictoStdChart(x1, mode="bar", hide.label.right = F, label.font.family = "Impact", label.right2=lab2, label.right.font.size=20) p7c <- PictoStdChart(x1, mode="bar", hide.label.right = F, label.font.family = "Impact", label.right2=lab2, label.right.font.size=20, label.right2.font.size=5) # Moving data label to sublabels p8 <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On left") p8b <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On left", label.data.font.size=20) p8c <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On left", label.data.font.size=20, label.font.family="Impact") p8d <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On left", label.data.font.size=20, label.font.family="Impact", label.data.onTop=T) p9 <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On right") p9b <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On right", label.data.font.size=20) p9c <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On right", label.data.font.size=20, label.font.family="Impact") p9d <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On right", label.data.font.size=20, label.font.family="Impact", label.data.onTop=T) p9e <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On right", label.data.font.size=20, label.font.family="Impact", label.data.onTop=T, hide.label.right=F) #ugly! p9f <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On right", label.data.font.size=20, label.font.family="Impact", label.data.onTop=T, hide.label.right=F, label.right.align.horizontal = "left", label.data.align.horizontal = "left") # Label colors p10 <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On left", label.color.asIcon = T, label.data.font.size=20, label.font.family="Impact", label.data.onTop=T, label.left.align.horizontal = "right", label.data.align.horizontal = "right") p10b <- PictoStdChart(x1, mode="bar", label.data.type="count", label.data.position="On left", label.color.asIcon = T, icon.colors = "read,green,blue", icon.palette = "User-specified", label.data.font.size=20, label.font.family="Impact", label.data.onTop=T, label.left.align.horizontal = "right", label.data.align.horizontal = "right") # Need to see what happens with fonts after the image slot is resized! # Check other icons with WHratio != 1 # Examples dat1 <- c(Upper=3, UpperMid=5, LowerMid=6, Lower=7) ex1 <- PictoStdChart(dat1, mode="bar", hide.base.image=T, hide.label.left=T, label.data.type="count", label.data.position="On left") dat3 <- c('2012'=0.53, '2014'=0.41) ex3 <- PictoStdChart(dat3, mode="bar", scale=0.01, icon.nrow=3, hide.base.image=F, label.color.asIcon = T, icon.palette="User-specified", icon.colors="grey,blue", label.data.type="percentage",label.data.position = "On right") # Label padding p11a <- PictoStdChart(dat1, mode="bar", total.icons=20, label.left.align.horizontal="right", label.pad=20, background.color="red") p11b <- PictoStdChart(dat1, mode="bar", total.icons=20, hide.label.right=F, label.right.align.horizontal="left", label.right.width=25, label.pad=20, background.color="red") dat12 <- c(DEAD=9079,INJURED=2628,MISSING=12664) p12 <- PictoStdChart(dat12, mode="bar", scale=200, icon.ncol=15, hide.base.image=T, show.legend=F,image="circle", label.data.type="count", label.data.position="On left", label.font.family="Impact", label.left.align.horizontal = "left", label.width=20, label.data.font.size=40, background.color=rgb(0.8,0.8,0.8)) # Size warnings dat13 <- structure(c(81.3, 81.1, 80.8, 80.8, 80.5, 80.5, 80.5, 80.3, 80.3, 80.2, 80, 80, 79.9, 79.9, 79.8, 79.7, 79.6, 79.5, 79.5, 79.5, 79.5, 79.4, 79.2, 79, 79, 78.8, 78.7, 78.5, 78.5, 78.5, 78.4, 78.4, 78.3, 78.3, 78.2, 78.1, 77.8, 77.8, 77.6, 77.5, 77.2, 77, 76.5, 76.3, 76, 76, 75.9, 75.7, 75.4, 75.4, 75), questiontype = "Number", name = "All", label = "All", question = "All", .Names = c("Hawaii", "Minnesota", "Connecticut", "California", "Massachusetts", "New York", "Vermont", "New Hampshire", "New Jersey", "Utah", "Colorado", "Wisconsin", "Washington", "Rhode Island", "Nebraska", "Iowa", "Arizona", "North Dakota", "Oregon", "Idaho", "South Dakota", "Florida", "Maine", "Virginia", "Illinois", "Maryland", "Kansas", "Pennsylvania", "Montana", "Texas", "New Mexico", "Delaware", "Wyoming", "Alaska", "Michigan", "Nevada", "North Carolina", "Ohio", "Indiana", "Missouri", "Georgia", "South Carolina", "District of Columbia", "Tennessee", "Kentucky", "Arkansas", "Oklahoma", "Louisiana", "Alabama", "West Virginia", "Mississippi")) <file_sep>/tests/testthat/test-pictographchart.R context("PictographChart") x1 <- c(A=1, Bbbbbb=3.6, Cc=2.8) test_that("Simple barchart", { expect_error( PictographChart(x1, show.legend=T), NA) }) test_that("Scaling works", { expect_error( PictographChart(x1*100, show.legend=T), NA) }) #test_that("Simple column chart", { # expect_error( PictographChart(x1, mode="column"), NA) #}) test_that("Wide pictograph", { x2 <- structure(c(17, 83, 56, 144, 138, 26, 26, 206, 196, 4, 312), .Dim = 11L, statistic = "Count", .Dimnames = list( c("iPad", "iPod", "iPhone", "Nokia mobile phone", "Other mobile phone (not Nokia and not iPhone)", "Mac computer - desktop", "Mac computer – laptop", "PC (non-Mac)", "Laptop computer (non-Mac)", "None of these", "NET")), name = "Q6", questions = c("Q6", "SUMMARY")) # expect_error(suppressWarnings(PictographChart(x2, mode="bar", hide.base.image=T, graphic.width.inch=244/72, graphic.height.inch=583/72, # show.label.data=T, label.data.position="Next to bar")), "Window is too narrow.") }) <file_sep>/R/ifelseimage.R #' IfElseImage #' #' Conditionally shows an image as a htmlwidget #' @param condition Expression evaluating to \code{TRUE} or {FALSE} that determines which image is displayed. #' @param true.image URL to image (jpeg, png or svg) to be shown when \code{condition} is \code{TRUE}. #' @param false.image URL to image (jpeg, png or svg) to be shown when \code{condition} is \code{FALSE}. #' @examples #' \dontrun{ #' IfElseImage(TRUE) #' IfElseImage(3 < 2, #' "https://displayrcors.displayr.com/images/thumbsup_grey.svg", #' "https://displayrcors.displayr.com/images/thumbsdown_grey.svg") #' } #' @export IfElseImage <- function(condition, true.image = "https://displayrcors.displayr.com/images/uparrow_grey.svg", false.image = "https://displayrcors.displayr.com/images/downarrow_grey.svg") { if (is.na(condition) || !is.logical(condition)) stop("Parameter 'condition' should be TRUE or FALSE.") image <- if (condition) true.image else false.image SinglePicto(1, 1, is.custom.url = TRUE, image = image, auto.size = TRUE) } <file_sep>/R/pictostack.R #' @importFrom grDevices colorRamp rgb pictoStack <- function(x, image, mode, col1, col2, ...) { # Assume scaling and conversions performed already using PictoStdChart if (nchar(col1)==0 || nchar(col2)==0) stop("Colors not specified\n") # By default, tables are stacked in bars if (mode=="column") x <- t(x) n <- if (is.null(nrow(x))) length(x) else nrow(x) m <- if (is.null(ncol(x))) 1 else ncol(x) # Set up colorscale c.rgb <- colorRamp(c(col1, col2))(seq(0,1,length=m)) c.hex <- rgb(c.rgb[,1], c.rgb[,2], c.rgb[,3], maxColorValue=255) c.hex <- c(c.hex, "") # Compute transformed matrices, as for a barchart m2 <- ceiling(max(apply(x, 1, sum))) x2 <- matrix(0, n, m2) rownames(x2) <- rownames(x) c.fg <- matrix(c.hex[1], n, m2) c.bg <- matrix("", n, m2) for (i in 1:n) { i.cum <- cumsum(unlist(x[i,])) k <- which.max(i.cum > 0) for (j in 1:m2) { if (k > m) next c.fg[i,j] <- c.hex[k] x2[i,j] <- max(0, min(1, i.cum[k] - j + 1), 0) while (k <= m && i.cum[k] < j) k <- k +1 c.bg[i,j] <- c.hex[k] } } pad.col <- 0 pad.row <- 5 # Undo transform for column charts if (mode=="column") { pad.col <- 5 pad.row <- 0 x2 <- t(x2[,m2:1]) c.fg <- t(c.fg[,m2:1]) c.bg <- t(c.bg[,m2:1]) } c.fg <- paste(c.fg, ":", imageURL[image], sep="") c.bg <- ifelse(nchar(c.bg) > 0, paste(c.bg, ":", imageURL[image], sep=""), NA) cat("pictostack: line 58\n") print(x2) return(pictoChart(x2, fill.image=c.fg, base.image=c.bg, pad.col=pad.col, pad.row=pad.row, total.icons=1, icon.nrow=1, icon.ncol=1, width.height.ratio=NA, show.label.data = FALSE, ...)) } <file_sep>/data-raw/sysdata.R # This script contains the data about the image data used in # PictoStdChart() and SinglePicto() # Data is stored as a data.frame available only internally # Note that PictoChart takes URLs, and does not use imageURL # Ratios are calculated from SVG file: viewBox="0 0 width height" imageWHRatio <- c(apple=0.884,baby=1.0,banana=1.124,bank=1.039,barn=1.358, beer=0.584,book=1, bread=1,building=0.928,cake=1.005,car=1.693,cash=0.9, chicken=0.890,church=0.812,citygate=0.998, computer=1.347,cow=1.293, cross=1, cup=1.398,cutlery=1.398,dna=0.475,elephant=1.431, 'face-happy'=1,'face-neutral'=1,'face-sad'=1,fuel=1.431,glass=0.750,globe=1.431,government=0.717, graduation=1.440,gun=1.595,heart=1.052,house=1.052, idea=1.00,law=1,man=0.492,medicine=1,money=1,patient=0.704, police=1.0,renewenergy=1.152,road=0.803, rocket=0.803, rubbish=0.875,sickperson=0.556, soldier=0.510,soup=0.851,sport=0.680,stack=16.317, star=1.103,stickman=0.372,stickwoman=0.458, 'symbol-tick'=1, 'symbol-cross'=1, 'symbol-minus'=1, 'symbol-plus'=1, testtube=1,trolley=1.153,thumbsup=1.048,thumbsdown=1.048,tick=1.301, tomato=1.004,tools=1,trafficlight=0.594, train=0.792,tree=0.872,truck=1.731,tv=1,user=0.860, waterdrop=0.646,weight=0.998,wine=0.523, trump=1.167, clinton=1.00, happyface=1, neutralface=1, sadface = 1, circle=1, square=1) image.names <- names(imageWHRatio) imageURL <- sprintf("https://displayrcors.displayr.com/images/%s_grey.svg", image.names) names(imageURL) <- image.names imageURL["circle"] <- "" imageURL["square"] <- "" save(imageURL, imageWHRatio, file = "R/sysdata.rda") <file_sep>/R/pictostdchart.R #' @description \code{PictoStdChart} Deprecated function for backwards-compatibility #' @rdname PictographChart #' @export PictoStdChart <- function(...) { warning("This function is deprecated. Please use PictographChart instead\n") PictographChart(...) } <file_sep>/R/pictographchart.R #' Create chart of pictographs #' #' \code{PictographChart} Create a chart to visually represent the data in a table or vector using the number of icons displayed #' @aliases PictoStdChart #' #' @param x Data to plot. Can be vector, matrix or data.frame. #' @param image Name of icon (e.g. \code{"star", "stickman",...}) or URL to icon image if \code{is.custom.url}. #' @param base.image URL of image to use as base image. Only used if \code{is.custom.url = TRUE} and \code{hide.base.image = FALSE}. #' @param is.custom.url Whether the image parameter is a url supplied by the user. #' @param hide.base.image Turns off background image (on by default). In general, the base image should only be shown if the input data is a proportion. #' @param total.icons Maximum number of icons in each table cell. By default, it will be determine based on \code{ceiling(x)}. #' @param icon.palette Name of palette used to color icons. Only applicable for in-built icons #' @param icon.colors Vector of colors for icons. Only applicable when \code{icon.palette = "Custom color"} or {"Custom palette"} and in-built icons used (Deprecated). #' @param icon.custom.color A single color which is used if \code{icon.palette} is set to \code{"Custom color"}. #' @param icon.custom.gradient.start Character; starting color of gradient if \code{icon.palette} is set to \code{"Custom gradient"}. #' @param icon.custom.gradient.end Character; last color of gradient if \code{icon.palette} is set to \code{"Custom gradient"}. #' @param icon.custom.palette Character; comma separated list of colors to be used if \code{icon.palette} is set to \code{"Custom palette"}. #' @param layout May be one of \code{"Number of rows"} or \code{"Number of columns"}. This parameter controls how the configuration of icons is specified. If no string is supplied, it will be automatically determined depending on whether \code{icon.nrow} or \code{icon.ncol} is supplied. #' @param scale Value of one icon. If \code{scale = 0}, the value is automatically determined from the data so that the largest entry is represented by 10 icons. #' @param legend.text Text shown with legend. If this string is empty, it will be automatically filled in using \code{scale}. (To hide text completely, use \code{legend.text = " "}) #' @param fill.direction Direction in which icons are filled. One of \code{"From left", "From right", "From top", "From bottom"}. #' @param row.names.to.remove List of rownames to exclude from the chart. This can be in the form of a vector or a comma-separated string. This variable is ignored if the input data has no rownames. #' @param column.names.to.remove List of colnames to exclude from the chart. #' @param hide.label.left Suppress labels on left of graphics. By default, if \code{label.left} is not supplied, labels are taken from the rownames of \code{x}. #' @param hide.label.top Suppress labels above graphics. #' @param hide.label.bottom Suppress labels below graphics (shown by default when \code{mode = "column"}). #' @param hide.label.right Suppress labels on right of graphics. #' @param mode Can be set to one of \code{"table", "bar", "column"}. For options \code{bar} and \code{column}, the chart is constrained to look like a bar or column chart. e.g For \code{mode = "column"}, 1-dimensional vectors/matrices are re-shaped to have multiple columns, labels are put below the graphis and icons are arranged vertically. Option \code{mode = "table"} is the most general and does not impose constraints. #' @param fix.icon.nrow When \code{mode="bar" and hide.base.image=T}, set to \code{FALSE} to allow the bars to contain varying number of rows. #' @param table.by.row By default, when a 2-dimensional table is supplied, values in each column will be shown in the same color. Set to \code{TRUE} to color values by row. #' @param label.color.asIcon When set to \code{TRUE}, row and data labels are shown in the same color as the icons. #' @param label.data.position When \code{show.label.data}, the position of the data labels can be one of \code{"Above icons", "Below icons"} (all modes) or \code{"Next to bar", "Above row label", "Below row label"} (bar mode only). Note that the last two options will overrride \code{sublabel.left} and \code{sublabel.right} #' @param show.label.data Boolean indicating whether or not to show data labels. #' @param customize.label.data Boolean indicating whether of not users want to customize data labels. By default this is on, but when set to \code{FALSE}, parameters \code{label.data.digits, label.data.100prc, label.data.prefix, label.data.suffix} is ignored. #' @param data.above.label Set to \code{TRUE}, to place data labels above row labels. #' @param label.data.digits Number of digits to show after decimal place. #' @param label.data.bigmark Option to prettify large numbers. By default a comma is placed after a thousand. #' @param label.data.100prc Option to show data labels multiplied by 100. This is useful when reporting percentages. #' @param label.data.prefix String to prepend data label. #' @param label.data.suffix String to append to data label. #' @param label.data.type Does nothing. Retained for backwards compatibility. #' @param label.pad Numeric specifying padding around the labels. Alternatively, the user can individually specify \code{label.left.pad} (horizontal space between left row label and icons), \code{label.right.pad} (horizontal space between right row label and icons). #' @param ... Arguments to pass to pictoChart #' @importFrom flipTables RemoveRowsAndOrColumns #' @importFrom grDevices col2rgb #' @importFrom stats median #' @importFrom flipChartBasics ChartColors #' @importFrom rhtmlPictographs graphic #' @examples #' xx <- c(First = 3, Second = 6, Third=2) #' PictographChart(xx, image="circle", mode="bar") #' PictographChart(xx, image="elephant", hide.base.image=TRUE, show.label.data=TRUE, mode="bar") #' PictographChart(xx, total.icons=10, mode="bar", fill.direction="fromright", is.custom.url=TRUE, #' image="http://wiki.q-researchsoftware.com/images/a/a9/Stick_woman_dark_red.png", #' base.image="http://wiki.q-researchsoftware.com/images/7/78/Stick_man_light_grey.png") #' @export #' @inheritParams pictoChart #' PictographChart <- function(x, image = "stickman", base.image = "", is.custom.url = FALSE, hide.base.image = FALSE, total.icons = NA, scale = NA, mode = "table", icon.palette = "Strong colors", icon.colors = "black", # for backwards compatibility icon.custom.color = NA, icon.custom.gradient.start = NA, icon.custom.gradient.end = NA, icon.custom.palette = NA, fill.direction = "fromleft", show.lines = FALSE, layout = NA, icon.nrow = 1, icon.ncol = NA, fix.icon.nrow = TRUE, table.by.row = FALSE, row.names.to.remove = "", column.names.to.remove = "", show.legend = FALSE, legend.text = "", legend.icon.color = NA, pad.legend = 40, hide.label.right = TRUE, hide.label.left = !hide.label.right, hide.label.bottom = (mode!="column"), hide.label.top = (mode=="column"), label.color.asIcon = FALSE, label.left = NA, label.top = NA, label.bottom = NA, label.right = NA, label.pad = 0, # just for convenience label.left.pad = label.pad, label.right.pad = label.pad, label.bottom.align.horizontal = "center", label.left.align.horizontal = "default", label.right.align.horizontal = "default", label.top.align.horizontal = "center", label.left.align.vertical = ifelse(is.na(icon.ncol[1]), "center", "top"), label.top.align.vertical = "center", label.right.align.vertical = ifelse(is.na(icon.ncol[1]), "center", "top"), label.bottom.align.vertical = "center", width.height.ratio = NA, label.top.height = NA, label.font.family = "arial", label.font.size = 12, label.font.color = "#2C2C2C", label.left.font.color = label.font.color, label.right.font.color = label.font.color, label.top.font.color = label.font.color, label.bottom.font.color = label.font.color, label.left.font.size = label.font.size, label.top.font.size = label.font.size, label.right.font.size = label.font.size, label.bottom.font.size = label.font.size, label.left.font.weight = "normal", label.top.font.weight = "normal", label.bottom.font.weight = "normal", label.right.font.weight = "normal", show.label.data = FALSE, customize.label.data = TRUE, label.data.digits = 0, label.data.bigmark = ",", # to prettify large numbers label.data.prefix = "", label.data.suffix = "", label.data.100prc = FALSE, label.data.position = ifelse(mode=="bar", "Next to bar", "footer"), label.data.font.weight = "normal", label.data.font.size = 0.8*label.font.size, label.data.font.color = label.font.color, label.data.align.horizontal = "default", label.data.type = "None", # does nothing, retained for backwards compatability data.above.label = FALSE, ...) { # Parameters not controlled by the user by passed to pictoChart label.width = NA label.left.width = label.width label.right.width = label.width label.data.text = NULL if (!is.numeric(unlist(x))) stop("Input data must be numeric") if (label.data.type != "None") show.label.data <- TRUE if (is.custom.url) { hide.base.image <- FALSE # overwritten in next block icon.palette <- "Default colors" # ignored anyway - but must be defined base.icon.color <- "" label.color.asIcon <- FALSE } if (is.custom.url && nchar(base.image) == 0) hide.base.image <- TRUE # Parameter substitutions for R Gui Controls fill.direction <- gsub(" ", "", tolower(fill.direction)) if (!is.custom.url) image <- gsub(" ", "", tolower(image)) # For !show.label.data, values will be ignored # But for !customize.label.data, values will be overridden later if (!show.label.data || !customize.label.data) { if (!show.label.data) { label.data.align.horizontal <- "center" label.data.position <- "" } data.above.label <- FALSE label.data.prefix <- "" label.data.suffix <- "" label.data.100prc <- FALSE label.data.digits <- 0 label.data.font.size <- 12 } if (show.label.data) { if (label.data.position == "Above icons") label.data.position <- "header" if (label.data.position == "Below icons") label.data.position <- "footer" if (label.data.position == "On left") label.data.position <- "left" if (label.data.position == "On right") label.data.position <- "right" } if (!is.na(layout)) { if (layout != "Number of rows") icon.nrow <- NA if (layout != "Number of columns") icon.ncol <- NA } if (mode=="bar" && hide.label.left && hide.label.right) label.width <- NA if (hide.label.left) { label.left.width <- NA label.left.font.size <- label.font.size label.left.font.weight <- "normal" label.left.align.horizontal <- "center" label.left.align.vertical <- "center" } if (hide.label.right) { label.right.width <- NA label.right.font.size <- label.font.size label.right.font.weight <- "normal" label.right.align.horizontal <- "center" label.right.align.vertical <- "center" } if (hide.label.top) { label.top.height <- NA label.top.font.size <- label.font.size label.top.font.weight <- "normal" label.top.align.horizontal <- "center" label.top.align.vertical <- "center" } label.top.align.horizontal <- tolower(label.top.align.horizontal) label.top.align.vertical <- tolower(label.top.align.vertical) label.left.align.horizontal <- tolower(label.left.align.horizontal) label.left.align.vertical <- tolower(label.left.align.vertical) label.right.align.horizontal <- tolower(label.right.align.horizontal) label.right.align.vertical <- tolower(label.right.align.vertical) label.data.align.horizontal <- tolower(label.data.align.horizontal) if (label.left.align.horizontal == "default") label.left.align.horizontal <- "right" if (label.right.align.horizontal == "default") label.right.align.horizontal <- "left" if (!show.legend) { legend.text <- "" pad.legend <- 0 legend.icon.color <- NA } if (show.label.data && !customize.label.data) { stat <- attr(x, "statistic") if (!is.null(stat) && grepl("%", stat)) { label.data.suffix <- "%" label.data.100prc <- all(x <= 1) } } # More parameters not controlled by the user but passed to pictoChart sublabel.left = NA sublabel.right = NA sublabel.left.align.horizontal = "left" sublabel.right.align.horizontal = "left" sublabel.left.font.size = label.left.font.size sublabel.right.font.size = label.right.font.size sublabel.left.font.weight = label.left.font.weight sublabel.right.font.weight = label.right.font.weight show.label.float = FALSE label.float.text = NULL label.float.font.weight = label.data.font.weight label.float.font.size = label.data.font.size label.float.font.color = label.data.font.color label.float.align.horizontal = "left" label.float.align.vertical = "center" if (mode == "bar" && !hide.label.right) label.float.align.vertical <- label.right.align.vertical if (mode == "bar" && !hide.label.left) label.float.align.vertical <- label.left.align.vertical # Some basic checks on input data #x <- AsChartMatrix(y = x, x = by, transpose = (transpose), aggregate.period = aggregate.period) if (length(dim(x)) > 2) { err.msg <- ifelse(is.null(attr(x,"questions")), "x has too many dimensions\n", "Input table should only contain one statistic per cell\n") stop(err.msg) } x <- as.matrix(x) #if (!is.atomic(x) && !is.table(x) && !is.matrix(x) && !is.data.frame(x) && !is.array(x)) # stop(paste("x must be a vector, matrix, data.frame or array")) # Reshaping arrays/matrices and removing unwanted rows/columns if (mode == "column") { if (all(is.na(icon.ncol))) icon.ncol <- 1 icon.nrow <- NA if (!is.null(dim(x)) && min(dim(x)) > 1) stop("Input data should be a one-dimensional table or a numeric vector") if (is.null(rownames(x)) && is.null(colnames(x))) stop("Input data should have row or column names") if (ncol(x) == 1 && (nrow(x) > 1 || is.null(colnames(x)))) x <- t(x) if (nrow(x) > 1) stop("Input data should be a one-dimensional table or a numeric vector") } if (mode == "bar") { if (all(is.na(icon.ncol))) icon.nrow <- 1 else icon.nrow <- NA if (!is.null(dim(x)) && min(dim(x)) > 1) stop("Input data should be a one-dimensional table or a numeric vector") if (is.null(rownames(x)) && is.null(colnames(x))) stop("Input data should have row or column names") if (nrow(x) == 1 && (ncol(x) > 1 || is.null(rownames(x)))) x <- t(x) if (ncol(x) > 1) stop("Input data should be a one-dimensional table or a numeric vector") } x <- RemoveRowsAndOrColumns(x, row.names.to.remove, column.names.to.remove) # Data labels label.data.values <- unlist(x) * (1+(99*label.data.100prc)) if (!customize.label.data && max(label.data.values) <= 1) label.data.digits <- 2 label.data.text <- sprintf("%s%s%s", label.data.prefix, formatC(label.data.values, digits=label.data.digits, format="f", big.mark=label.data.bigmark), label.data.suffix) # Automatically set scale to be nearest power of 10 if (is.na(scale)) scale <- 10^{round(log10(max(x)) - 1)} #if (is.na(scale) && max(x) <= 1) # scale <- 10^{round(log10(median(x)))} if (scale <= 0) stop("Scale must be greater than zero\n") if (all(is.na(total.icons))) total.icons <- ceiling(max(x)/scale) if (nchar(legend.text) == 0 && scale > 0) legend.text = sprintf(paste(" = %.", 0-min(0,floor(log10(scale))), "f", sep = ""), scale) x <- x/scale # if mode==table, and dim(x)==2 and show.legend is false, check range of data # if range differs by more than a range of 100 and the greatest and 2nd greatest # are in the same row/column then compute scale for each row/column # Adjust labels based on chart type if (mode == "column") { # Defaults will put labels on the top - add functionality for bottom if (!hide.label.bottom) label.bottom <- colnames(x) } if (mode == "bar") { # Defaults will put labels on the left if (!hide.label.right) { label.right <- rownames(x) } if (!fix.icon.nrow && hide.base.image && !is.na(icon.ncol)) { icon.nrow <- ceiling(x/icon.ncol) total.icons <- icon.nrow * icon.ncol icon.nrow <- NA # needed so that icon.ncol is used } # Position data labels relative to fill direction if (label.data.position == "Next to bar" && hide.base.image) { show.label.float <- TRUE label.float.text <- label.data.text label.float.align.horizontal <- switch(fill.direction, fromleft="left", fromright="right") # Ignore icon.ncol if its too large if (all(!is.na(icon.ncol)) && all(icon.ncol >= total.icons)) { icon.ncol <- NA icon.nrow <- 1 } #if (any(ceiling(x) >= total.icons) && !is.na(icon.nrow) && all(icon.nrow == 1)) # total.icons <- total.icons + 1 show.label.data <- FALSE } else if (label.data.position == "Next to bar") { label.data.position <- switch(fill.direction, fromleft="right", fromright="left") } else if (label.data.position == "Below row label" || label.data.position == "Above row label") { if (label.data.position == "Above row label") data.above.label <- TRUE label.data.position <- switch(fill.direction, fromleft="left", fromright="right") } # Position of data labels in absolute terms if (label.data.position == "left") { if (label.data.align.horizontal == "default") label.data.align.horizontal <- label.left.align.horizontal if (!hide.label.left && data.above.label) { sublabel.left <- rownames(x) sublabel.left.font.size <- label.left.font.size sublabel.left.font.weight <- label.left.font.weight sublabel.left.align.horizontal <- label.left.align.horizontal label.left <- label.data.text label.left.font.size <- label.data.font.size label.left.font.weight <- label.data.font.weight label.left.align.horizontal <- label.data.align.horizontal } else { sublabel.left <- label.data.text sublabel.left.font.size <- label.data.font.size sublabel.left.font.weight <- label.data.font.weight sublabel.left.align.horizontal <- label.data.align.horizontal if (!hide.label.right) label.left.align.vertical <- label.right.align.vertical } show.label.data <- FALSE } if (label.data.position == "right") { if (label.data.align.horizontal == "default") label.data.align.horizontal <- label.right.align.horizontal if (!hide.label.right && data.above.label) { sublabel.right <- rownames(x) sublabel.right.font.size <- label.right.font.size sublabel.right.font.weight <- label.right.font.weight sublabel.right.align.horizontal <- label.right.align.horizontal label.right <- label.data.text label.right.font.size <- label.data.font.size label.right.font.weight <- label.data.font.weight label.right.align.horizontal <- label.data.align.horizontal } else { sublabel.right <- label.data.text sublabel.right.font.size <- label.data.font.size sublabel.right.font.weight <- label.data.font.weight sublabel.right.align.horizontal <- label.right.align.horizontal if (!hide.label.left) label.right.align.vertical <- label.left.align.vertical } show.label.data <- FALSE } } # Fix dimensions using icon.ncol - icon.nrow will be adjusted in pictochart() if (all(is.na(icon.ncol))) icon.ncol <- unlist(total.icons)/icon.nrow + show.label.float if (length(icon.ncol) == 1) icon.ncol <- min(icon.ncol, total.icons) n <- if (is.null(nrow(x))) length(x) else nrow(x) m <- if (is.null(ncol(x)) || is.na(ncol(x))) 1 else ncol(x) if (hide.label.left) label.left <- NULL if (hide.label.top) label.top <- NULL if (hide.label.bottom) label.bottom <- NULL if (hide.label.right) label.right <- NULL if (image %in% c("circle", "square")) image.type <- image else image.type <- "url" # Icon colors if (icon.palette == "User-specified") { # Old approach - only for supporting old R outputs c.hex <- unlist(strsplit(split=",", icon.colors)) tryCatch(tmp.col <- col2rgb(c.hex), error = function(cond){cat("Invalid color specified\n"); c.hex <- "black"}) } else { c.length <- m if (m == 1 || table.by.row) c.length <- n c.hex <- ChartColors(c.length, given.colors = icon.palette, custom.color = icon.custom.color, custom.gradient.start = icon.custom.gradient.start, custom.gradient.end = icon.custom.gradient.end, custom.palette = icon.custom.palette, reverse = icon.palette %in% c("Reds", "Blues", "Greens", "Greys")) c.hex <- c.hex[1:c.length] if (any(is.na(c.hex))) stop("Unknown color palette specified") } c.hex <- matrix(c.hex, n, m, byrow = !table.by.row) if (is.na(legend.icon.color)) legend.icon.color <- c.hex[1] # Font colors if (label.color.asIcon && mode == "bar") { label.left.font.color <- c.hex[,1] label.right.font.color <- c.hex[,1] label.data.font.color <- c.hex[,1] label.float.font.color <- c.hex[,1] } if (label.color.asIcon && mode == "column") { label.top.font.color <- c.hex[1,] label.bottom.font.color <- c.hex[1,] label.data.font.color <- c.hex[1,] label.float.font.color <- c.hex[1,] } if (label.data.align.horizontal == "default") label.data.align.horizontal <- "right" image.url <- if (is.custom.url) image else imageURL[image] base.image <- if (hide.base.image) NA else if (is.custom.url) { checkImageUrl(base.image) base.image } else imageURL[image] fill.icon.color <- if (is.custom.url) "" else c.hex width.height.ratio <- if (is.custom.url) getWidthHeightRatio(image) else imageWHRatio[image] json <- NA f.mspace <- 0 # space in margin for floating labels while (is.na(json) || is.numeric(json)) { json <- pictoChart(x, fill.image = image.url, fill.icon.color = fill.icon.color, image.type = image.type, f.mspace = f.mspace, base.image = base.image, width.height.ratio = width.height.ratio, show.lines = show.lines, total.icons = total.icons, icon.nrow = icon.nrow, icon.ncol = icon.ncol, label.left = label.left, label.top = label.top, label.right = label.right, sublabel.left = sublabel.left, sublabel.right = sublabel.right, label.font.family = label.font.family, label.font.color = label.font.color, label.left.width = label.left.width, label.right.width = label.right.width, label.left.font.color = label.left.font.color, label.right.font.color = label.right.font.color, label.top.font.color = label.top.font.color, label.bottom.font.color = label.bottom.font.color, label.font.size = label.font.size, label.left.font.size = label.left.font.size, label.right.font.size = label.right.font.size, label.bottom.font.size = label.bottom.font.size, sublabel.left.font.size = sublabel.left.font.size, sublabel.right.font.size = sublabel.right.font.size, label.data.font.size = label.data.font.size, label.top.font.size = label.top.font.size, label.left.font.weight = label.left.font.weight, label.right.font.weight = label.right.font.weight, label.top.font.weight = label.top.font.weight, label.bottom.font.weight = label.bottom.font.weight, sublabel.left.font.weight = sublabel.left.font.weight, sublabel.right.font.weight = sublabel.right.font.weight, label.left.align.horizontal = label.left.align.horizontal, label.top.align.horizontal = label.top.align.horizontal, label.right.align.horizontal = label.right.align.horizontal, label.bottom.align.horizontal = label.bottom.align.horizontal, sublabel.left.align.horizontal = sublabel.left.align.horizontal, sublabel.right.align.horizontal = sublabel.right.align.horizontal, label.left.align.vertical = label.left.align.vertical, label.top.align.vertical = label.top.align.vertical, label.bottom.align.vertical = label.bottom.align.vertical, label.right.align.vertical = label.right.align.vertical, label.bottom = label.bottom, label.top.height = label.top.height, fill.direction = fill.direction, pad.legend = pad.legend, show.legend = show.legend, legend.text = legend.text, legend.icon.color = legend.icon.color, show.label.data = show.label.data, label.data.position = label.data.position, label.data.text = label.data.text, label.data.font.weight = label.data.font.weight, label.data.font.color = label.data.font.color, label.float.font.weight = label.float.font.weight, label.data.align.horizontal = label.data.align.horizontal, label.left.pad = label.left.pad, label.right.pad = label.right.pad, show.label.float = show.label.float, label.float.text = label.float.text, label.float.font.size = label.float.font.size, label.float.font.color = label.float.font.color, label.float.align.horizontal = label.float.align.horizontal, label.float.align.vertical = label.float.align.vertical, ...) if (is.na(json) && hide.base.image) total.icons <- total.icons + 1 if(is.numeric(json)) f.mspace <- f.mspace + json } return(graphic(json)) } <file_sep>/tests/testthat/test-visualizenumber.R context("VisualizeNumber") library(flipTransformations) library(flipTables) # This function replaces SinglePicto as the function used in the Standard R pages test_that("VisualizeNumber", { expect_error(VisualizeNumber(0.4, maximum.value = 1.0), NA) expect_error(VisualizeNumber(ParseText("40%"), display = "Pictograph (single icon)", label.data.number.type = "Percentage", maximum.value = ParseText("100%")), NA) expect_error(VisualizeNumber(ParseText("40%"), display = "Pictograph (repeated icons)", label.data.number.type = "Percentage", maximum.value = ParseText("100%"), total.icons = 10), NA) expect_error(VisualizeNumber(4, display = "Pictograph (repeated icons)", scale = ParseText("100%"), label.data.number.type = "Percentage", total.icons = NA), NA) expect_error(VisualizeNumber(4, display = "Pictograph (repeated icons)", scale = 2, label.data.number.type = "Percentage", total.icons = NA), NA) expect_error(VisualizeNumber(ParseText("-40%"), display = "Gauge", label.data.number.type = "Percentage", maximum.value = ParseText("100%"), minimum.value = ParseText("-100%")), NA) expect_error(VisualizeNumber(0.46, display = "Pictograph (single icon)", maximum.value = 1.0, text.below = "\"ABC\""), NA) expect_error(VisualizeNumber(0.46, display = "Pictograph (single icon)", maximum.value = 1.0, label.data.number.type = "Percentage", label.data.prefix = "\"", label.data.suffix = "\""), NA) }) # This is QTable with the Base n statistic tabWithN <- structure(c(12.2448979591837, 6.12244897959184, 4.08163265306122, 6.12244897959184, 4.08163265306122, 8.16326530612245, 22.4489795918367, 19.3877551020408, 17.3469387755102, 100, 32.2033898305085, 13.5593220338983, 5.08474576271187, 10.1694915254237, 5.08474576271187, 0, 5.08474576271187, 13.5593220338983, 15.2542372881356, 100, 11.8811881188119, 12.8712871287129, 12.8712871287129, 13.3663366336634, 8.41584158415842, 13.3663366336634, 13.3663366336634, 8.91089108910891, 4.95049504950495, 100, 10.8843537414966, 17.687074829932, 11.5646258503401, 7.48299319727891, 16.3265306122449, 3.40136054421769, 6.12244897959184, 22.4489795918367, 4.08163265306122, 100, 12.5, 6.25, 18.75, 6.25, 9.375, 12.5, 18.75, 15.625, 0, 100, 3.57142857142857, 19.6428571428571, 8.92857142857143, 16.0714285714286, 26.7857142857143, 5.35714285714286, 10.7142857142857, 8.92857142857143, 0, 100, 13.0769230769231, 2.30769230769231, 12.3076923076923, 20, 13.8461538461538, 6.92307692307692, 11.5384615384615, 12.3076923076923, 7.69230769230769, 100, 6.57894736842105, 15.7894736842105, 7.89473684210526, 5.26315789473684, 11.8421052631579, 9.21052631578947, 9.21052631578947, 28.9473684210526, 5.26315789473684, 100, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 147, 147, 147, 147, 147, 147, 147, 147, 147, 147, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800, 800), .Dim = c(10L, 8L, 3L), .Dimnames = list( c("18 to 24 ", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 64", "65 or more", "NET"), c("Every or nearly every day", "4 to 5 days a week", "2 to 3 days a week", "Once a week", "Once every 2 weeks", "Once a month", "Less than once a month", "Never"), c("Column %", "Column n", "Base n")), name = "Age by Exercise frequency", questions = c("Age", "Exercise frequency")) test_that("VisualizeNumber with SelectEntry", { expect_warning(value <- SelectEntry(tabWithN, 1, 1), "Only the first statistic") expect_equal(attr(value, "format"), "%") expect_equal(value, 0.122449, check.attributes = FALSE, tol = 1e-3) }) <file_sep>/examples/single_examples.R require(flipPictographs) # default icon is star s1 <- SinglePicto(2.5, 5) s1b <- SinglePicto(2.5, 5, icon.width=10) s2 <- SinglePicto(2.5, 5, hide.base.image = T) # for a fixed icon.width, size of icons remain constant s3 <- SinglePicto(4.5, 6, icon.width=10) s4 <- SinglePicto(4.5, 6, number.rows=3) s4b <- SinglePicto(4.5, 6, number.rows=3, fill.direction="fromleft") s4c <- SinglePicto(4.5, 6, number.rows=3, fill.direction="fromright") s4d <- SinglePicto(4.5, 6, number.rows=3, fill.direction="fromtop") s4e <- SinglePicto(4.5, 6, number.rows=3, fill.direction="frombottom") # Dimensions change depending on aspect ratio of image s5 <- SinglePicto(4.5, 6, number.cols=3, image="stickwoman") s6 <- SinglePicto(2.5, 5, number.cols=5, image="stickman", background.color="red") # Autosize s7 <- SinglePicto(2.5, 4, number.rows=4, image="stickman", background.color="red", auto.size = T) # Margins s8 <- SinglePicto(2.5, 5, image="stickman", background.color="red", auto.size = T) s8a <- SinglePicto(2.5, 5, image="stickman", background.color="red", auto.size = T, margin.top=10) s8b <- SinglePicto(2.5, 5, image="stickman", background.color="red", auto.size = T, pad.col=0.9) s8c <- SinglePicto(2.5, 5, image="stickman", background.color="red", auto.size = F) s8d <- SinglePicto(2.5, 5, image="stickman", background.color="red", auto.size = F, margin=10) s8e <- SinglePicto(2.5, 5, image="stickman", background.color="red", auto.size = F, margin.top=10, margin.left=10) # Padding s10 <- SinglePicto(10, width.height.ratio = 2, auto.size=T, background.color="green", image="star", pad.row=0.2) # Check ratios of built in images i.list <- names(flipPictographs:::imageURL) s9 <- list() n <- length(i.list)-2 for (i in 1:n) s9[[i]] <- SinglePicto(9, 9, 3, image=i.list[i], margin.left=100, background.color = "red") <file_sep>/tests/testthat/test-singlepicto.R context("SinglePicto") test_that("SinglePicto runs (simple example)", { expect_error( SinglePicto(2.5, 5), NA) }) test_that("SinglePicto accepts width parameter", { expect_error( SinglePicto(2.5, 5, icon.width=10), NA) }) test_that("SinglePicto accepts direction parameter", { expect_error( SinglePicto(4.5, 6, number.rows=2, fill.direction="fromright"), NA) }) test_that("SinglePicto accepts image parameter", { expect_error( SinglePicto(2.5, 5, image="stickman"), NA) }) test_that("SinglePicto accepts background parameter", { expect_error( SinglePicto(2.5, 5, 5, image="stickman", background.color="red") , NA) }) test_that("SinglePicto accepts autosize parameter", { expect_error( SinglePicto(2.5, 5, 3, image="stickman", background.color="red", auto.size = T) , NA) }) test_that("SinglePicto custom icon", { expect_error( SinglePicto(48, total.icons = 1, maximum.value = 100, width.height.ratio = 1.125, image = "http://docs.displayr.com/images/5/51/Female_Blue.svg", base.image = "http://docs.displayr.com/images/7/70/Female_Grey.svg", is.custom.url = TRUE) , NA) }) #test_that("SinglePicto redirected custom icon", { # expect_error( SinglePicto(48, # total.icons = 1, # maximum.value = 100, # width.height.ratio = 1.125, # image = "http://docs.displayr.com/images/5/51/Female_Blue.svg", # base.image = "http://docs.displayr.com/images/7/70/Female_Grey.svg", # is.custom.url = TRUE) , "Image type is text/html. Ensure the image url is #correct and not redirected.") #}) <file_sep>/R/circle.R #' Circle #' #' Draws a circle #' @param color One of 'red', 'green' or 'yellow' or a hex color code. #' @param opacity A numeric value between 0 and 1. #' @param print.config If set to \code{TRUE}, the JSON string used to generate pictograph will be printed to standard output. This is useful for debugging. #' @importFrom rhtmlPictographs graphic #' @examples #' Circle("red") #' Circle("#000000", opacity=0.2) #' @export Circle <- function(color = "red", opacity = 0.9, print.config = FALSE) { if (opacity < 0.0 || opacity > 1.0) stop("'opacity' should be a numeric between 0 and 1.") if (tolower(color) == "red") color <- rgb(255, 76, 92, maxColorValue = 255) if (tolower(color) == "yellow") color <- rgb(252, 174, 50, maxColorValue = 255) if (tolower(color) == "green") color <- rgb(39, 195, 153, maxColorValue = 255) config <- sprintf("{\"variableImage\":\"circle:%s:opacity=%f\", \"resizable\":\"true\"}", color, opacity) if (print.config) cat(config, "\n") graphic(config) } <file_sep>/R/singlepicto.R #' SinglePicto #' #' Creates a single pictograph. Allows customization of the number of icons #' and dimensions. #' @seealso PictographChart to create a chart or table of pictographs #' @param x Input data which determines the number of icons (\code{x/scale}) filled in the pictograph. #' @param total.icons Total number of icons. Defaults to \code{total.icons=ceiling(x/scale)}. #' @param image The name of the icon to use (e.g. \code{"star", "stickman"}) or the URL of an image when \code{is.custom.url} is true. #' @param base.image The URL of the base image. Only used if \code{is.custom.url = TRUE} and \code{hide.base.image = FALSE}. #' @param is.custom.url When set to true, image is expected to be a URL to an jpeg or png image file available from online. #' @param scale Scaling factor for \code{x}. Defaults to 1. #' @param maximum.value Maximum value \code{x} is expected to take. When this is value is specified, the pictograph will display \code{x} as a proportion out of \code{maximum.value}. This value overrides scale. #' @param layout Optional parameter to determine how the layout is specified. Can be one of \code{"Width-to-height ratio", "Number of rows", "Number of columns", "Fill graphic"}. If not supplied, a decision will be made based on which parameters are supplied #' @param number.rows If neither \code{number.rows} and \code{number.cols} is supplied, the default behaviour is to place icons according to \code{width.height.ratio}. Note that number.rows is ignored when number.cols is non-zero. #' @param number.cols Maximum number of icons in each column. Overrides \code{number.rows} and \code{width.height.ratio}. #' @param width.height.ratio Width to height ratio of pictograph if \code{layout == "Width-to-height ratio"}. #' @param hide.base.image Set to \code{TRUE} to use blank background instead of base image. #' @param fill.direction Direction in which pictograph is filled (one of \code{"fromleft","fromright","fromtop","frombottom"}). #' @param fill.icon.color Color of the filled icons. Only applicable for built-in icons. #' @param base.icon.color Color of the unfilled icons when \code{hide.base.image == FALSE}. Defaults to grey (#CCCCCC). Only applicable for built-in icons. #' @param background.color Color of the graphic background #' @param auto.size Automatically sizes the plot based on the size of the window/slot. #' @param icon.width Width of a single icon in pixels when \code{auto.size} is \code{FALSE}. #' @param pad.row Vertical space between icons. This should be a number between 0 (no space) and 1.0 (all space). #' @param pad.col Horizontal space between icons. #' @param margin Controls space on margins of the graphic. When \code{margin} is used, space on all 4 sides are adjusted simultaneously, but margins can also be adjusted separately using \code{margin.top, margin.right, margin.bottom, margin.left}. #' @param margin.top Spacing on top of graphic. This value overrides \code{margin}. #' @param margin.right Spacing on the right of the graphic. #' @param margin.bottom Spacing below graphic. #' @param margin.left Spacing on the left of the graphic. #' @param label.data.position One of \code{"None"}, \code{"Above"} or \code{"Below"}. #' @param label.data.font.family Font in which the data labels are displayed. #' @param label.data.font.size Font size of data labels. #' @param label.data.font.color Font color of data labels. #' @param label.data.font.weight Weight of data labels, i.e. one of \code{"bold"} or \code{"normal"}. #' @param label.data.align.horizontal Horizontal alignment of data labels. #' @param label.data.digits Number of digits to show after decimal place. #' @param label.data.bigmark Option to prettify large numbers. By default a comma is placed after a thousand. #' @param label.data.100prc Option to show data labels multiplied by 100. This is useful when reporting percentages. #' @param label.data.prefix String to prepend data label. #' @param label.data.suffix String to append to data label. #' @param graphic.width.inch (deprecated) Horizontal dimension of the chart output in inches. If these dimensions are not specified, the width-to-height ratio of the chart output may not match the desired dimensions. #' @param graphic.height.inch (deprecated) Verical dimension of the chart output in inches. #' @param graphic.resolution (deprecated) Conversion from inches to pixels. #' @param print.config If set to \code{TRUE}, the JSON string used to generate pictograph will be printed to standard output. This is useful for debugging. #' @param x.limit Upper limit of x above which \code{scale} is automatically calculated. This can be set to \code{NA}, but may cause slowness or freezing when the user inputs a large \code{x}. #' @importFrom rhtmlPictographs graphic #' @examples #' xx <- 4 #' SinglePicto(xx) #' SinglePicto(xx, total.icons=10, image="stickman", number.cols=5, #' fill.icon.color="red", base.icon.color="deepskyblue") #' SinglePicto(xx, 9, number.rows=3, is.custom.url=TRUE, #' image="http://wiki.q-researchsoftware.com/images/9/91/Star_filled.svg", #' base.image="http://wiki.q-researchsoftware.com/images/2/21/Star_unfilled.png") #' @export SinglePicto <- function (x, total.icons = NA, image = "star", base.image = "", is.custom.url = FALSE, number.rows = NA, number.cols = NA, width.height.ratio = 1, layout = NA, scale = 1, maximum.value = NA, hide.base.image = FALSE, fill.direction = "fromleft", fill.icon.color = "black", base.icon.color = "", background.color = "transparent", auto.size = FALSE, icon.width = 50, pad.row = 0, pad.col = 0, margin = 0, margin.top = margin, margin.right = margin, margin.bottom = margin, margin.left = margin, label.data.position = c("None", "Above", "Below")[1], label.data.digits = 0, label.data.bigmark = ",", # to prettify large numbers label.data.prefix = "", label.data.suffix = "", label.data.100prc = FALSE, label.data.font.weight = "normal", label.data.font.size = 12, label.data.font.family = "arial", label.data.font.color = "#2C2C2C", label.data.align.horizontal = "center", graphic.width.inch = NA, graphic.height.inch = NA, graphic.resolution = 96, print.config = FALSE, x.limit = 1000) { if (!(length(x) == 1 && x >= 0)) stop("Input data must be a single positive number\n") if (scale <= 0 && is.na(maximum.value)) stop("Scale must be greater than zero\n") if (!is.na(maximum.value) && scale != 1) warning("Parameter scale overridden by maximum value\n") if (!is.na(total.icons) && total.icons <= 0) stop("Total icons must be greater than zero\n") if (!is.na(maximum.value)) { if (maximum.value <= 0) stop("Maximum value must be greater than zero\n") if (maximum.value < x) stop("Input data must be smaller than or equal to maximum value\n") if (is.na(total.icons)) total.icons <- maximum.value scale <- maximum.value/total.icons } # Some parameter substitutions for R GUI Controls if (is.custom.url) { fill.icon.color <- "" base.icon.color <- "" hide.base.image <- nchar(base.image) == 0 } else { image <- gsub(" ", "", tolower(image)) } fill.direction <- gsub(" ", "", tolower(fill.direction)) if (auto.size) icon.width <- 50 if (!is.na(total.icons) && total.icons == 1) { # Parameters not supplied in Pictographs - Single layout <- "Width-to-height ratio" pad.row <- 0 pad.col <- 0 } if (!is.na(layout)) { if (layout != "Width-to-height ratio") width.height.ratio = 1 if (layout != "Number of rows") number.rows = NA if (layout != "Number of columns") number.cols = NA } if (label.data.position == "None") { label.data.font.size <- 0 label.data.align.horizontal <- "center" } label.data.str <- "" label.data.values <- x label.data.align.horizontal <- tolower(label.data.align.horizontal) # Determine plot values if (!is.na(x.limit) && x/scale > x.limit) { scale <- scale * 10^{floor(log10(x/scale)) - 1} warning("The input value is too large to plot, and the Scale has been set to ", scale, ". Consider entering a larger Scale value in the inputs.\n") } x <- x/scale if (is.na(total.icons)) total.icons <- ceiling(x) if (length(total.icons) != 1 && total.icons > 0) stop("The total icons must be a single numeric value and greater than zero\n") if (!is.na(number.rows) && (number.rows <= 0 || number.rows != ceiling(number.rows))) stop("The number of rows must be a positive integer\n") if (!is.na(number.cols) && (number.cols <= 0 || number.cols != ceiling(number.cols))) stop("The number of columns must be a positive integer\n") if (width.height.ratio <= 0) stop("The width-height ratio must be greater than zero\n") if (icon.width <= 0) stop("icon width must be greater than zero\n") prop <- x/total.icons if (prop < 0 | prop > 1) stop("Input data must be between 0 and total icons\n") if (round(total.icons) != total.icons) stop("The number of total icons must be an integer\n") # Determine layout based on which parameters are supplied layout.str <- "" icon.WHratio <- if (is.custom.url) getWidthHeightRatio(image) * (1 + pad.col) / (1 + pad.row) else imageWHRatio[image] * (1 + pad.col) / (1 + pad.row) if (!is.na(number.rows) && is.na(number.cols)) { layout.str <- paste(",\"numRows\":", number.rows, sep="") number.cols <- ceiling(total.icons/number.rows) } else if (!is.na(number.cols)) { layout.str <- paste(",\"numCols\":", number.cols, sep="") number.rows <- ceiling(total.icons/number.cols) } else { number.rows <- max(1, round(sqrt(icon.WHratio/width.height.ratio * total.icons))) if (number.rows > total.icons) number.rows <- total.icons number.cols <- ceiling(total.icons/number.rows) layout.str <- paste(",\"numRows\":", number.rows, sep="") } image.type <- "url" if (image %in% c("circle", "square")) image.type <- image base.image.str <- "" if (!hide.base.image) { if (nchar(base.icon.color) > 0) base.icon.color <- paste(base.icon.color, ":", sep="") base.image.url <- if (is.custom.url) { checkImageUrl(base.image) base.image } else imageURL[image] base.image.str <- if (nchar(base.image.url) == 0 && is.custom.url) "" else paste(",\"baseImage\":\"", image.type, ":", base.icon.color, base.image.url, "\"", sep="") } image.url <- if (is.custom.url) image else imageURL[image] variable.image <- if (is.custom.url) paste(image.type, ":", fill.direction, ":", image.url, sep="") else paste(image.type, ":", fill.direction, ":", fill.icon.color, ":", image.url, sep="") # size of pictograph output dim.str <- "" icon.size.str <- "" if (auto.size) dim.str <- "\"rowHeights\":[\"proportion:1\"], \"colWidths\":[\"flexible:graphic\"]" else { dim.str <- "\"rowHeights\":[\"fixedsize:graphic\"], \"colWidths\":[\"fixedsize:graphic\"]" icon.size.str <- paste0(",\"imageWidth\":", icon.width) } # Data labels if (label.data.position != "None") { tmp.str <- "" if (label.data.position == "Next to icons") { x.pos <- ceiling(label.data.values/scale) label.float.position <- sprintf("%d:%d", floor(x.pos/number.cols), x.pos %% number.cols) tmp.str <- "]" } label.data.text <- sprintf("%s%s%s", label.data.prefix, formatC(label.data.values * (1+(99*label.data.100prc)), digits=label.data.digits, format="f", big.mark=label.data.bigmark), label.data.suffix) label.pos.str <- switch(label.data.position, 'Above' = "\"table-header\":{\"padding\": \"10 1 1 1\",", 'Below' = "\"table-footer\":{\"padding\": \"10 1 1 1\",") label.data.str <- sprintf(", %s\"text\":\"%s\", \"font-size\":\"%fpx\", \"font-weight\":\"%s\", \"font-family\":\"%s\", \"font-color\":\"%s\", \"horizontal-align\":\"%s\"}%s", label.pos.str, label.data.text, label.data.font.size, label.data.font.weight, label.data.font.family, label.data.font.color, label.data.align.horizontal, tmp.str) } json.string <- paste0("{\"table\": {", dim.str, ",\"rows\":[[{\"type\":\"graphic\", \"value\":{", "\"proportion\":", prop, ",\"numImages\":", total.icons, icon.size.str, layout.str, ",\"rowGutter\":", pad.row, ",\"columnGutter\":", pad.col, ",\"variableImage\":\"", variable.image, "\"", base.image.str, "}}]]}", label.data.str, ",\"background-color\":\"", background.color, "\"}") if (print.config) cat(json.string) graphic(json.string) } <file_sep>/examples/column_numeric1d.R # In StdRPage set hide.base.image=T x1 <- c(First=1, SecondLonger=4.5, Third=3) p1 <- PictoStdChart(x1, mode="column") x2 <- 100*x1 p2 <- PictoStdChart(x1) p2b <- PictoStdChart(x1, show.legend=T, mode="column") p2c <- PictoStdChart(x1, show.legend=T, mode="column", pad.legend=3, legend.icon.color="red") p2d <- PictoStdChart(x1, show.legend=T, mode="column", pad.legend=3, background.color="green", pad.col=0) p2e <- PictoStdChart(x1, show.legend=T, mode="column", pad.legend=3, background.color="green", pad.icon.col=0.5) p2f <- PictoStdChart(x1, show.legend=T, mode="column", pad.legend=3, background.color="green", pad.icon.row=0.5) p2g <- PictoStdChart(x1, show.legend=T, mode="column", pad.legend=3, background.color="green", pad.col=20) p2h <- PictoStdChart(x1, show.legend=T, mode="column", pad.legend=3, background.color="green", pad.row=20, pad.icon.row=0.5) # Padding between column p3 <- PictoStdChart(x2, mode="column", image="circle", hide.base.image = T, fill.direction = "frombottom", icon.ncol=2, pad.col=100, icon.palette = "Blues", show.legend=T) <file_sep>/examples/stackbar_numeric2d.R xx <- data.frame(A=1:3, B=2:4, C=3:5) rownames(xx) <- c("i", "ii", "iii") p1 <- PictoStdChart(xx) # Scaling p2 <- PictoStdChart(xx*10, mode="bar", stack=T, show.legend=T) # For 2D, you need to consider transposing the data matrix <file_sep>/R/getwidthheightratio.R #' @importFrom httr GET content #' @importFrom bmp read.bmp #' @importFrom png readPNG #' @importFrom jpeg readJPEG #' @importFrom grDevices as.raster getWidthHeightRatio <- function(image.url) { # Download custom image to compute width-height ratio response <- getImage(image.url) tmp.type <- response$headers$'content-type' whratio <- NA if (grepl("svg", tmp.type)) { # No warning is given because recoloring option is not available for pngs or jpegs # if (!any(grepl("fill", tmp.image))) # warning("SVG image is missing fill attribute. Icon cannot be recolored\n") tmp.image <- content(response, as = "text", encoding = "UTF-8") tmp.image <- unlist(strsplit(split="<", tmp.image))[1:5] tmp.str <- regmatches(tmp.image, regexpr("viewBox=\"[0-9 .-]+", tmp.image)) tmp.dim <- suppressWarnings(as.numeric(unlist(strsplit(split=" ", tmp.str)))) whratio <- tmp.dim[3]/tmp.dim[4] if (is.na(whratio)) { warning("SVG image is missing viewBox attribute. Aspect ratio may not be preserved.") tmp.w <- regmatches(tmp.image, regexpr("\\swidth=\"[0-9 .]+", tmp.image)) tmp.h <- regmatches(tmp.image, regexpr("\\sheight=\"[0-9 .]+", tmp.image)) if (length(tmp.w) != 0 && length(tmp.h) != 0) { ww <- as.numeric(gsub("\"", "", strsplit(split="=", tmp.w)[[1]][2])) hh <- as.numeric(gsub("\"", "", strsplit(split="=", tmp.h)[[1]][2])) whratio <- ww/hh } } } else { tmp.file <- NULL tmp.image <- content(response, as = "raw", encoding = "UTF-8") if (grepl("png", tmp.type)) tmp.file <- readPNG(tmp.image) else if (grepl("jpeg|jpg", tmp.type)) tmp.file <- readJPEG(tmp.image) else if (grepl("bmp", tmp.type)) tmp.file <- as.raster(read.bmp(tmp.file), max=255) else if (grepl("png", image.url)) tmp.file <- readPNG(tmp.image) else if (grepl("jpeg|jpg", image.url)) tmp.file <- readJPEG(tmp.image) else if (grepl("bmp", image.url)) tmp.file <- as.raster(read.bmp(tmp.file), max=255) tmp.dim <- dim(tmp.file) if (length(tmp.dim) >= 1) whratio <- tmp.dim[2]/tmp.dim[1] } if (is.null(whratio) || is.na(whratio)) { whratio <- 1 warning("Could not determine width-height ratio from image. Defaulting to 1.\n") } return(whratio) } getImage <- function(image.url) { response <- try(GET(image.url), silent = TRUE) if (inherits(response, "try-error")) stop("Could not retrieve image from '", image.url, "'. Check that url is correct.") if(response$status_code != 200) stop("Error (status code ", response$status_code, ") retrieving image ", image.url) tmp.type <- response$headers$'content-type' if (any(grepl("text/html", tmp.type, fixed = TRUE))) stop("The url content type is 'text/html'. Ensure the image url is correct and not redirected.") # Give warning because sometimes chrome can fix this, but will show as blank in IE unknown.type <- !any(grepl("image", tmp.type, fixed = TRUE)) if (unknown.type) warning("URL content type is '", tmp.type, "'. This may not display properly in all browsers.") response } checkImageUrl <- function(image.url) { getImage(image.url) invisible() } <file_sep>/R/drawshapes.R # Draw a segment of a half circle that fills a page from [0,0] to [1,1] segmentPath <- function(x, hole.size, border.resolution, debug = FALSE) { radius <- 0.5 thetas <- pi * (1 - seq(from = x[1], to = x[2], length = border.resolution)) xx.o <- radius * cos(thetas) + 0.5 xx.i <- rev(radius * hole.size * cos(thetas) + 0.5) yy.o <- 2 * radius * sin(thetas) yy.i <- rev(2 * radius * hole.size * sin(thetas)) path <- paste(paste("M", xx.o[1], yy.o[1]), paste("L", xx.o, yy.o, collapse = " "), paste("L", xx.i[1], yy.i[1]), paste("L", xx.i, yy.i, collapse = " "), "Z") if (debug) cat(path, "\n") return(path) } # For drawing the border of a full circle filling page with corners [0,0] and [1,1] circleBorder <- function(border.width, border.resolution, debug = FALSE) { thetas <- pi * seq(from = -1, to = 1, length = border.resolution) xx.o <- 0.5 * cos(thetas) + 0.5 xx.i <- rev(0.5 * (1 - 2*border.width) * cos(thetas) + 0.5) yy.o <- 0.5 * sin(thetas) + 0.5 yy.i <- rev(0.5 * (1 - 2*border.width) * sin(thetas) + 0.5) path <- paste(paste("M", xx.o[1], yy.o[1]), paste("L", xx.o, yy.o, collapse = " "), paste("L", xx.i, yy.i, collapse = " ")) if (debug) cat(path, "\n") return(path) } # For drawing the border of a rectangle filling page with corners [0,0] and [1,1] rectangleBorder <- function(border.width, debug = FALSE) { path <- paste("M 0 0 V 1 H 1 V 0 Z M", border.width, border.width, "V", 1-border.width, "H", 1-border.width, "V", border.width, "H", 1 - border.width) if (debug) cat(path, "\n") return(path) } pathToShape <- function(path, color, opacity) { if (is.null(path)) return(NULL) return(list(type = "path", path = path, line = list(width = 0), fillcolor = color, opacity = opacity)) } <file_sep>/examples/rhtml_labels.R # Check that labels are handled properly by rhtmlPictographs t1 <- rhtmlPictographs::graphic('{ "proportion": "=3/5", "numImages": 5, "numRows": 1, "variableImage": "circle:fromleft:lightblue", "floatingLabels": [ { "position": "0:3", "text": "3", "horizontal-align": "left" } ] }') t2 <- rhtmlPictographs::graphic('{ "numImages": 6, "numRows": 2, "variableImage": "circle:lightblue", "floatingLabels": [ { "position": "0:0", "font-size": "10px", "text": "0:0" }, { "position": "0:1", "font-size": "10px", "text": "0:1" }, { "position": "0:2", "font-size": "10px", "text": "0:2" }, { "position": "1:0", "font-size": "10px", "text": "1:0" }, { "position": "1:1", "font-size": "10px", "text": "1:1" }, { "position": "1:2", "font-size": "10px", "text": "1:2" } ] }') <file_sep>/R/pictochart.R #' pictoChart #' #' Function that computes dimensions for PictographChart. It should not be called directly. #' The output is a JSON string for creating the widget #' #' @return Either a JSON string to create the widget or NA or a numeric value (see parameter \code{f.mspace}) if adjustment of dimensions is required to fit the floating labels in properly. The iterative adjustment is performed only when \code{graphic.width.inch} and \code{graphic.height.inch} is provided. #' @param x Data for charting #' @param fill.image URL of icon #' @param base.image Optional URL of background image #' @param total.icons Maximum icons in each table cell. Ignored if both \code{icon.nrow} and \code{icon.ncol} supplied. #' @param fill.direction Accepts \code{horizontal}, \code{vertical}, \code{radial}, \code{scale}. (But \code{scale} may not be appropriate, especially if \code{total.icons} is important). #' @param show.lines Add horizontal lines between each row #' @param line.width Width of lines #' @param line.color Line colour #' @param show.legend Show legend (true or false). #' @param legend.text Text to show beside legend icon. #' @param legend.font.family.family Font of legend. #' @param legend.font.size Text size of legend text. #' @param legend.icon.color Color of icon shown in legend. #' @param background.color Background colour of pictograph #' @param icon.nrow Configuration of icons in each table cell. Can be a single value or a vector with length equal to the number of rows. #' @param icon.ncol Configuration of icons in each table cell. Can be a single value or a vector with length equal to the number of columns. #' @param label.left.pad,label.right.pad Horizontal spacing between row labels and icons. #' @param label.left Length must be equal to length (if \code{x} is a vector) or number of rows (if \code{x} is matrix or data.frame) as x. If no value is supplied, labels will be read from names/rowname of \code{x}. To suppress labels, use \code{label.left = NULL}. #' @param label.top By default, labels are read from column names of \code{x}. #' @param label.bottom Optional labels below graphic cells. The length of the labels must be the same as the number of columns in \code{x}. #' @param label.right Optional labels to the right of graphic cells. The length of the labels must be the same as the number of rows in \code{x}. #' @param label.font.family Controls font-family of all labels. To modify only the font of one label use \code{label.left.font.family, label.top.font.family}, etc. #' @param label.font.size Size of label text. #' @param label.font.color Colour of labels. This can be a string or a 6-digit hex code. #' @param label.top.height Height of top label row in pixels. #' @param label.left.width Width of left label column in pixels. #' @param label.left.align.horizontal,label.right.align.horizontal,label.top.align.horizontal,label.bottom.align.horizontal Horizontal alignment of row and column labels. One of \code{"left", "right"} or \code{"center"}. #' @param label.left.align.vertical,label.right.align.vertical,label.top.align.vertical,label.bottom.align.vertical Vertical alignment of row and column labels. One of \code{"top", "bottom"} or \code{"center"}. #' @param label.left.font.color,label.right.font.color,label.top.font.color,label.bottom.font.color Font color of row/column labels which overrides the global \code{label.font.color} setting. #' @param label.left.font.size,label.right.font.size,label.top.font.size,label.bottom.font.size Font size of row/column labels which overrides the global \code{label.font.size} setting. #' @param label.left.font.weight,label.right.font.weight,label.top.font.weight,label.bottom.font.weight Font weight of row/column labels which overrides the global \code{label.font.weight} setting. #' @param label.data.font.family Font in which the data labels are displayed. #' @param label.data.font.size Font size of data labels. #' @param label.data.font.color Font color of data labels. #' @param label.data.font.weight Weight of data labels, i.e. one of \code{"bold"} or \code{"normal"}. #' @param label.data.align.horizontal Horizontal alignment of data labels. #' @param row.height Height of graphic cells. Can be a single value or a character or numeric vector the same length as the number of rows in \code{x}. #' @param column.width Width of graphic cells. #' @param width.height.ratio Width-to-height ratio used to adjust row heights and column widths so they match the aspect ratio of the icon. Mis-specfication does not distort icon, but graphic will have extra spacing. When set to zero, row.height and column.width are unchanged, otherwise initial values are decreased to match \code{width.height.ratio}. #' @param pad.row Single numeric specifying vertical spacing between graphic cells in the table. #' @param pad.col Vertical spacing between cells in table. #' @param pad.icon.row Numeric specifying vertical spacing between icons inside each table cell. May be a single value or a numeric matrix of the same dimensions as \code{x}. #' @param pad.icon.ncol Horizontal spacing between icons inside each table cell. #' @param pad.legend Horizontal spacing between the chart and the legend. #' @param f.mspace Space in left/right margin left for floating labels. This parameter is adjusted iteratively by \code{PictographChart} when floating labels are used in bar pictographs. #' @param font.whratio Numeric specifying the average aspect ratio of a single character, which usually varies around 0.4 - 0.6. It is used to calculate the minimum width of the labels. #' @param graphic.width.inch Horizontal dimension of the chart output in inches. If these dimensions are not specified, the width-to-height ratio of the chart output may not match the desired dimensions. #' @param graphic.height.inch Verical dimension of the chart output in inches. #' @keywords internal #' @importFrom utils tail #' @importFrom verbs Sum pictoChart <- function(x, fill.image, base.image = NA, image.type = "url", total.icons = max(ceiling(x)), fill.icon.color = "", base.icon.color = "", fill.direction = "fromleft", show.lines = FALSE, show.legend = FALSE, legend.text = "", icon.nrow = 1, icon.ncol = NA, label.left = NA, label.right = NA, label.top = NA, label.bottom = NA, sublabel.left = NA, sublabel.right = NA, label.left.pad = 5, label.right.pad = 5, label.font.family = "arial", label.font.size = 12, label.font.color = "#2C2C2C", label.top.font.family = label.font.family, label.top.font.size = label.font.size, label.top.font.weight = "normal", label.top.font.color = label.font.color, label.top.height = NA, label.right.font.family = label.font.family, label.right.font.size = label.font.size, label.right.font.weight = "normal", label.right.font.color = label.font.color, label.right.width = NA, label.bottom.font.family = label.font.family, label.bottom.font.size = label.font.size, label.bottom.font.weight = "normal", label.bottom.font.color = label.font.color, label.bottom.height = NA, label.left.font.family = label.font.family, label.left.font.size = label.font.size, label.left.font.weight = "normal", label.left.font.color = label.font.color, label.left.width = NA, label.left.align.horizontal = "right", label.right.align.horizontal = "left", label.top.align.horizontal = "center", label.bottom.align.horizontal = "left", label.left.align.vertical = "center", label.right.align.vertical = "center", label.top.align.vertical = "center", label.bottom.align.vertical = "center", sublabel.left.font.size = label.left.font.size, sublabel.left.font.weight = label.left.font.weight, sublabel.left.align.horizontal = label.left.align.horizontal, sublabel.right.font.size = label.right.font.size, sublabel.right.font.weight = label.right.font.weight, sublabel.right.align.horizontal = label.right.align.horizontal, legend.font.family = label.font.family, legend.font.size = 0.8*label.font.size, legend.font.weight = "normal", legend.font.color = label.font.color, legend.icon.color = fill.icon.color[1], show.label.data = FALSE, label.data.text = NULL, label.data.position = "footer", label.data.font.family = label.font.family, label.data.font.size = 0.8*label.font.size, label.data.font.weight = "normal", label.data.font.color = label.font.color, label.data.align.horizontal = "right", show.label.float = FALSE, label.float.text = NULL, label.float.font.family = label.font.family, label.float.font.size = 0.8*label.font.size, label.float.font.weight = "normal", label.float.font.color = label.font.color, label.float.align.horizontal = "center", label.float.align.vertical = "center", row.height = NA, column.width = NA, width.height.ratio = NA, background.color = "transparent", line.color = "#A8A8A8", line.width = 0.5, pad.legend = 0.5*column.width[1], pad.row = 2, pad.col = 2, pad.icon.row = 0.0, pad.icon.col = 0.0, label.vpad = 0, # deprecated - is ignored f.mspace = 0, #margin.top = 0, #margin.right = 0, #margin.bottom = 0, #margin.left = 0, graphic.width.inch = NA, graphic.height.inch = NA, graphic.resolution = 72, font.whratio = 0.9, print.config = FALSE ) { n <- if (is.null(nrow(x))) length(x) else nrow(x) m <- if (is.null(ncol(x)) || is.na(ncol(x))) 1 else ncol(x) # Errors that are commonly encountered by Displayr/Q users are in sentence case # (e.g. total icons instead of total.icons), but parameters which are less commonly used # are referred to by exact parameter name so they can be easily corrected if (is.na(width.height.ratio)) width.height.ratio <- 1 if (any(total.icons != ceiling(total.icons))) stop("Total icons must be a whole number\n") if (any(total.icons <= 0)) stop("Total icons must be greater than zero\n") if (length(total.icons) != 1 && length(total.icons) != length(x)) stop("total.icons must be either a single integer or a matrix with the same dimensions as x\n") if (all(total.icons == 0)) stop("No non-zero entries in total.icons\n") if (length(icon.nrow) != 1 && length(icon.nrow) != n) stop("icon.nrow should be a single integer or a vector of length ", n, "\n") if (length(icon.ncol) != 1 && length(icon.ncol) != m) stop("icon.ncol should be a single integer or a vector of length ", m, "\n") if (pad.icon.row < 0 || pad.icon.row >= 1) stop("pad.icon.row must be smaller than 1 and greater or equal to 0\n") if (pad.icon.col < 0 || pad.icon.col >= 1) stop("pad.icon.col must be smaller than 1 and greater or equal to 0\n") total.icons <- matrix(total.icons, nrow=n, ncol=m) prop <- as.vector(unlist(x))/unlist(total.icons) prop[total.icons == 0] <- 0 if (any(is.na(prop))) { warning("Non-numeric values set to zero\n") prop[is.na(prop)] <- 0 } # Scale has already been checked for non-negativity in pictographchart if (any(prop < 0)) stop("Input data cannot be negative\n") if (any(prop > 1)) stop("Input data is too large. Try increasing the scale or total icons\n") # Determine layout layout.str <- "" if (any(!is.na(icon.nrow))) { if (any(!is.na(icon.ncol))) warnings("icon.ncol is ignored when icon.nrow is specified\n") if (length(icon.nrow) == 1) icon.nrow <- rep(icon.nrow, n) icon.nrow.matrix <- matrix(icon.nrow, n, m) icon.ncol <- apply(total.icons/icon.nrow.matrix, 2, max) layout.str <- paste("\"numRows\":", icon.nrow.matrix) } else { if (length(icon.ncol) == 1) icon.ncol <- rep(icon.ncol, m) icon.ncol.matrix <- matrix(icon.ncol, n, m, byrow=T) icon.nrow <- apply(total.icons/icon.ncol.matrix, 1, function(x){ceiling(max(x))}) layout.str <- paste("\"numCols\":", icon.ncol.matrix) } tot.icon.nrow <- Sum(icon.nrow, remove.missing = FALSE) tot.icon.ncol <- Sum(icon.ncol, remove.missing = FALSE) # Fill row/column labels with defaults if (!is.null(label.left) && is.na(label.left) && m == 1 && is.null(row.names(x)) && !is.null(names(x))) label.left <- names(x) if (!is.null(label.left) && all(is.na(label.left)) && !is.null(rownames(x))) label.left <- rownames(x) if (!is.null(label.top) && all(is.na(label.top)) && !is.null(colnames(x))) label.top <- colnames(x) if (!is.null(label.right) && all(is.na(label.right))) label.right <- NULL if (!is.null(label.bottom) && all(is.na(label.bottom))) label.bottom <- NULL if (!is.null(label.right) && all(is.na(label.right))) label.right <- NULL if (!is.null(label.left) && all(is.na(label.left))) label.left <- NULL if (!is.null(label.top) && all(is.na(label.top))) label.top <- NULL if (!is.null(sublabel.left) && all(is.na(sublabel.left))) sublabel.left <- NULL if (!is.null(sublabel.right) && all(is.na(sublabel.right))) sublabel.right <- NULL if (!is.null(label.left) && length(label.left) != n) stop("label.left must be of length ", n, "\n") if (!is.null(label.right) && length(label.right) != n) stop("label.right must be of length ", n, "\n") if (!is.null(label.top) && length(label.top) != m) stop("label.top must be of length ", m, "\n") if (!is.null(label.bottom) && length(label.bottom) != m) stop("label.bottom must be of length ", m, "\n") if (length(row.height) != 1 && length(row.height) != n) stop("row.height must be of length 1 or ", n, "\n") if (length(column.width) != 1 && length(column.width) != m) stop ("column.width must be of length 1 or ", m, "\n") fill.icon.color.str <- ifelse(nchar(fill.icon.color) > 0, paste(fill.icon.color, ":", sep = ""), "") base.image.str <- "" if (any(!is.na(base.image))) { base.icon.color.str <- ifelse(nchar(base.icon.color) > 0, paste(base.icon.color, ":", sep = ""), "") base.image.str <- ifelse(!is.na(base.image), paste("\"baseImage\":\"", image.type, ":", base.icon.color.str, base.image, "\",", sep = ""), "") } # Calculate floating labels # We need to do this first in case we need to leave extra space in the margin label.float.str <- "" if (show.label.float) { #if (any(x >= total.icons)) # warning("Floating labels placed at invalid positions. Please increase total.icons\n") i.pos <- floor(x/icon.ncol) j.pos <- x %% icon.ncol ind.outside <- which(x >= icon.ncol) if (length(ind.outside) > 0) { i.pos[ind.outside] <- 0 j.pos[ind.outside] <- icon.ncol } # extra space in margin pad.dir <- ifelse(fill.direction == "fromright", "padding-right", "padding-left") label.float.align.horizontal <- ifelse(fill.direction == "fromright", "right", "left") i.pos <- i.pos + 0.5 j.pos <- j.pos #fstr.width <- font.whratio * (label.float.font.size * nchar(label.float.text)) #f.mspace <- max(f.mspace, fstr.width[ind.outside]) #if (length(ind.outside) > 0) # cat("f.mspace increased to", f.mspace, "to fit labels of length", fstr.width[ind.outside], "\n") label.float.position <- sprintf("%.2f:%.2f", i.pos, j.pos) label.float.str <- sprintf("\"floatingLabels\":[{\"position\":\"%s\", \"text\":\"%s\", \"font-size\":\"%fpx\",\"font-weight\":\"%s\", \"%s\": \"4em\", \"font-family\":\"%s\", \"font-color\":\"%s\", \"horizontal-align\":\"%s\", \"vertical-align\":\"center\"}],", label.float.position, label.float.text, label.float.font.size, label.float.font.weight, pad.dir, label.float.font.family, label.float.font.color, label.float.align.horizontal) } # Calculate size of table cells # The units should roughly be equal to 1 px = 1/72 inch # Note that icons will resize automatically to fill table cell # But label font sizes are in fixed px if (is.null(label.left)) label.left.font.size <- 0 if (is.null(sublabel.left)) sublabel.left.font.size <- 0 if (is.null(label.right)) label.right.font.size <- 0 if (is.null(sublabel.right)) sublabel.right.font.size <- 0 if (is.null(label.top)) label.top.font.size <- 0 if (is.null(label.bottom)) label.bottom.font.size <- 0 if (!show.label.data || !(label.data.position %in% c("header","footer"))) label.data.font.size <- 0 max.font.size <- max(label.left.font.size + sublabel.left.font.size, label.right.font.size + sublabel.right.font.size, 1) size.warning <- 0 # tracker so we only give one size warning if(is.na(label.top.height)) label.top.height <- label.top.font.size*1.0 if(is.na(label.bottom.height)) label.bottom.height <- label.bottom.font.size*1.0 if (any(is.na(row.height))) row.height <- paste0("\"proportion:", floor(icon.nrow/tot.icon.nrow*1000)/1000, "\"") if (any(is.na(column.width))) column.width <- rep("\"flexible:graphic\"", m) # Calculating padding/alignment pad.left <- matrix(0, n, m) pad.right <- matrix(0, n, m) pad.top <- matrix(0, n, m) pad.bottom <- matrix(0, n, m) #pad.right[,m] <- f.mspace # Compensating for rowGutters/pad.row # This additional padding is required to ensure that all rowheights are the same and # rowlabels on the top and bottom of the table remain vertically centered # It also ensures that lines are visible at the top and bottom of the table lab.tpad <- rep(0, n) lab.bpad <- rep(0, n) if (length(label.top) == 0 || all(nchar(label.top) == 0)) { pad.top[1,] <- pad.top[1,] + pad.row/2 lab.tpad[1] <- lab.tpad[1] + pad.row/2 } if (length(label.bottom) == 0 || all(nchar(label.bottom) == 0)) { pad.bottom[n,] <- pad.bottom[n,] + pad.row/2 lab.bpad[n] <- lab.bpad[n] + pad.row/2 } # Preparing labels # Dimensions of all table components are expected to be fixed by now if (length(label.top) > 0) label.top.str <- sprintf("{\"type\":\"label\", \"value\":{\"text\":\"%s\", \"font-family\":\"%s\",\"font-size\":\"%fpx\",\"font-weight\":\"%s\", \"font-color\":\"%s\", \"horizontal-align\":\"%s\", \"vertical-align\":\"%s\"}}", label.top, label.top.font.family, label.top.font.size, label.top.font.weight, label.top.font.color, label.top.align.horizontal, label.top.align.vertical) if (length(label.bottom) > 0) label.bottom.str <- sprintf("{\"type\":\"label\", \"value\":{\"text\":\"%s\", \"font-family\":\"%s\",\"font-size\":\"%fpx\",\"font-weight\":\"%s\", \"font-color\":\"%s\",\"horizontal-align\":\"%s\", \"vertical-align\":\"%s\"}}", label.bottom, label.bottom.font.family, label.bottom.font.size, label.bottom.font.weight, label.bottom.font.color, label.bottom.align.horizontal, label.bottom.align.vertical) if (length(label.left) > 0 || length(sublabel.left) > 0) { text.str <- "" config1.str <- sprintf("\"font-size\": \"%fpx\", \"font-weight\":\"%s\", \"horizontal-align\":\"%s\"", label.left.font.size, label.left.font.weight, label.left.align.horizontal) config2.str <- sprintf("\"font-size\": \"%fpx\", \"font-weight\":\"%s\", \"horizontal-align\":\"%s\"", sublabel.left.font.size, sublabel.left.font.weight, sublabel.left.align.horizontal) config12.str <- sprintf("\"font-family\":\"%s\",\"font-color\":\"%s\"", label.left.font.family, label.left.font.color) if (length(label.left) > 0 && length(sublabel.left) == 0) text.str <- paste("\"text\":\"", label.left, "\",", config1.str, ",", config12.str, sep="") if (length(label.left) == 0 && length(sublabel.left) > 0) text.str <- paste("\"text\":\"", sublabel.left, "\",", config2.str, ",", config12.str, sep="") if (length(label.left) > 0 && length(sublabel.left) > 0) text.str <- sprintf("\"labels\": [{\"text\":\"%s\", %s, %s},{\"text\": \"%s\", %s, %s}]", label.left, config1.str, config12.str, sublabel.left, config2.str, config12.str) label.left.str <- sprintf("{\"type\":\"label\", \"value\":{\"padding-right\":%f, \"padding-top\":%f, \"padding-bottom\":%f, \"vertical-align\":\"%s\", %s}}", label.left.pad, lab.tpad, lab.bpad, label.left.align.vertical, text.str) } if (length(label.right) > 0 || length(sublabel.right) > 0) { text.str <- "" config1.str <- sprintf("\"font-size\": \"%fpx\", \"font-weight\":\"%s\", \"horizontal-align\":\"%s\"", label.right.font.size, label.right.font.weight, label.right.align.horizontal) config2.str <- sprintf("\"font-size\": \"%fpx\", \"font-weight\":\"%s\", \"horizontal-align\":\"%s\"", sublabel.right.font.size, sublabel.right.font.weight, sublabel.right.align.horizontal) config12.str <- sprintf("\"font-family\":\"%s\",\"font-color\":\"%s\"", label.right.font.family, label.right.font.color) if (length(label.right) > 0 && length(sublabel.right) == 0) text.str <- paste("\"text\":\"", label.right, "\",", config1.str, ",", config12.str, sep="") if (length(label.right) == 0 && length(sublabel.right) > 0) text.str <- paste("\"text\":\"", sublabel.right, "\",", config2.str, ",", config12.str, sep="") if (length(label.right) > 0 && length(sublabel.right) > 0) text.str <- sprintf("\"labels\": [{\"text\":\"%s\", %s, %s},{\"text\": \"%s\", %s, %s}]", label.right, config1.str, config12.str, sublabel.right, config2.str, config12.str) label.right.str <- sprintf("{\"type\":\"label\", \"value\":{\"padding-left\":%f, \"padding-top\":%f, \"padding-bottom\":%f, \"vertical-align\":\"%s\", %s}}", label.right.pad, lab.tpad, lab.bpad, label.right.align.vertical, text.str) } # Preparing data labels label.data.str <- "" if (show.label.data) label.data.str <- sprintf("\"text-%s\":{\"text\":\"%s\", \"font-size\":\"%fpx\",\"font-weight\":\"%s\", \"font-family\":\"%s\", \"font-color\":\"%s\", \"horizontal-align\":\"%s\"},", label.data.position, label.data.text, label.data.font.size, label.data.font.weight, label.data.font.family, label.data.font.color, label.data.align.horizontal) row.str <- sprintf("{\"type\":\"graphic\", \"value\":{\"proportion\":%f,\"numImages\":%d, \"variableImage\":\"%s:%s%s:%s\", %s %s, %s %s \"columnGutter\":%f, \"rowGutter\":%f, \"padding\":\"%f %f %f %f\"}}", prop, total.icons, image.type, fill.icon.color.str, fill.direction, fill.image, base.image.str, layout.str, label.data.str, label.float.str, pad.icon.col, pad.icon.row, pad.top, pad.right, pad.bottom, pad.left) row.str <- matrix(row.str, n, m) # Adding left/right labels empty.str <- "{\"type\":\"label\", \"value\":{\"text\":\"\"}}" corner.tl <- NULL corner.tr <- NULL corner.bl <- NULL corner.br <- NULL if (length(label.left) > 0 || length(sublabel.left) > 0) { row.str <- cbind(label.left.str, row.str) corner.tl <- empty.str corner.bl <- empty.str column.width <- c("\"flexible:label\"", column.width) } if (length(label.right) > 0 || length(sublabel.right) > 0) { row.str <- cbind(row.str, label.right.str) corner.tr <- empty.str corner.br <- empty.str column.width <- c(column.width, "\"flexible:label\"") } # Adding legend # Does not work because we need to calculate leg.vpad (based on icon.height) # Ask Kyle about aligning within a table cell # Or maybe play around with hidden base image + floating labels? #leg.rpad <- 0 #if (nchar(legend.text) == 0) # legend.text <- " " #if (show.legend) #{ # row.str <- cbind(row.str, matrix(empty.str, nrow(row.str), 3)) # leg.row <- ceiling(nrow(row.str)/2) # leg.col <- ncol(row.str) # legend.col.str <- "" # if (nchar(legend.icon.color) > 0) # legend.col.str <- paste(legend.icon.color[1], ":", sep="") # # leg.vpad <- (row.height[leg.row]-icon.height)/2 # row.str[leg.row, leg.col] <- sprintf("{\"type\":\"label\", \"value\":{\"text\":\"%s\",\"font-family\":\"%s\", # \"font-size\":\"%fpx\",\"font-weight\":\"%s\",\"font-color\":\"%s\", # \"horizontal-align\":\"left\", \"vertical-align\":\"center\"}}", # legend.text, legend.font.family, legend.font.size, legend.font.weight, legend.font.color) # row.str[leg.row, leg.col-1] <- sprintf("{\"type\":\"graphic\", \"value\":{\"proportion\":1,\"numImages\":1, # \"variableImage\":\"%s:%s:%s%s\", \"padding\":\"%f %f %f %f\"}}", # image.type, legend.col.str, fill.direction[1], fill.image[1], # leg.vpad, 0, leg.vpad, 0) # column.width <- c(column.width, pad.legend, icon.width, font.whratio*legend.font.size*nchar(legend.text)) # leg.rpad <- sum(tail(column.width, 3)) #} # Adding lines to make table lines.str <- "" # legendgap.str <- "" if (show.lines) { # if (show.legend) # legendgap.str <- paste("\"padding-right\":", 3*pad.col+leg.rpad, ",") lines.str <- paste("\"lines\":{\"horizontal\":[", paste((0:n)+any(nchar(label.top)>0), collapse = ","), "],", "\"vertical\":[0,1,2],", # legendgap.str, "\"style\": \"stroke:", line.color, ";stroke-width:", line.width, "\"}, ", sep = "") } # Adding top/bottom labels if (any(nchar(label.top) > 0)) row.height <- c(label.top.height, row.height) if (any(nchar(label.bottom) > 0)) row.height <- c(row.height, label.bottom.height) row.str <- apply(row.str, 1, paste, collapse = ",") # Exact dimensions should not matter as long as aspect ratio is correct dim.str <- "" if (!is.na(graphic.width.inch) && !is.na(graphic.height.inch)) dim.str <- paste0("\"width\":", graphic.width.inch * graphic.resolution, ", \"height\":", graphic.height.inch * graphic.resolution, ",") json.str <- paste("{", dim.str, "\"background-color\":\"", background.color, "\",", "\"table\":{\"rowHeights\":[", paste(row.height, collapse = ","), "],", "\"rowGutterLength\":", pad.row, ",\"columnGutterLength\":", pad.col, ",", "\"colWidths\":[", paste(column.width, collapse = ","), "],", sep = "") json.str <- paste(json.str, lines.str, "\"rows\":[[", sep = "") if (any(nchar(label.top) > 0)) json.str <- paste(json.str, paste(c(corner.tl, label.top.str, corner.tr), collapse = ","), "],[", sep = "") json.str <- paste(json.str, paste(row.str, collapse = "],["), sep = "") if (any(nchar(label.bottom) > 0)) json.str <- paste(json.str, "],[", paste(c(corner.bl, label.bottom.str, corner.br), collapse = ","), sep = "") json.str <- paste(json.str, "]]}}", sep = "") if (print.config) cat(json.str, "\n") return(json.str) }
dce4f2712b1cb826893c77c47d951a25d763630d
[ "R" ]
25
R
Displayr/flipPictographs
b416b465b3bd603cf85bdbe11995eed21ae59fc5
dacfad5c35df6bb8dfad1deb397052616a461178
refs/heads/master
<file_sep># ENTRefreshControl This document contains information about `ENTRefreshControl` class to use external `UIView` instead of native view usually bind with `UIScrollView` ## Pod ``` pod "ENTRefreshControl" ``` ## Initialise Every things with `ENTRefreshControl` works just the same as native `UIRefreshControl` but with few changes. 1: You can assign your custom view to display and animate with refresh controls' pull state. For this all you need is to create your custom view and place it some where on Screen e.g on `UINavigationBar` or any where you want. After that just pass the reference of that view to `ENTRefreshControl` object `loaderView`. ``` let refreshControl = ENTRefreshControl() refreshControl.loaderView = yourCustomView refreshControl.rotationSpeed = .double ``` 2: You can also slow down or faster the rotation of your custom view when you are pulling to refresh. For this we have enumeration with values. ``` enum Speed { case same case half case double } ``` 3: You can stop your view's animation without calling `refreshControl.endRefreshing()` function and start animation without calling `refreshControl.beginRefreshing()` like this. ``` refreshControl.startRotate // to start your animation refreshControl.stopRotate // to end your animation ``` >starting animation without calling `refreshControl.beginRefreshing()` will give you `false` when you will triger `refreshControl.isRefreshing()` function. 4: You can now register a completion handler to get current state of Control which will invoke when ever an event is occur on refresh control. ``` refControl.pullState = { state, frame in //state is an enumeration with name PullState and defined below. //frame is the current of of refreshControl with respect to its superview. } ``` `PullState` is an enumeration which contains information about the state of refresh control's pulling state. E.g User is pulling downward, upward, isLoading or none. ``` public enum PullState{ case up case down case loading case none } ``` <file_sep>// // ViewController.swift // ENTRefreshControl // // Created by etDev24 on 03/15/2018. // Copyright (c) 2018 etDev24. All rights reserved. // import UIKit import ENTRefreshControl class ViewController: UIViewController { @IBOutlet weak var loadingView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var label: UILabel! let refControl = ENTRefreshControl() override func viewDidLoad() { super.viewDidLoad() refControl.loaderView = loadingView tableView.addSubview(refControl) refControl.addTarget(self, action: #selector(refreshing), for: .valueChanged) // Do any additional setup after loading the view, typically from a nib. } @objc func refreshing() { label.text = "Started Refreshing" } @IBAction func didStopRefresh() { label.text = "Stoped Refreshing" refControl.endRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // ENTRefreshControl.swift // CreateLink // // Created by mac on 3/15/18. // Copyright © 2018 mac. All rights reserved. // import UIKit public enum Speed: CGFloat { case same = 0.85 case half = 1.2 case double = 0.5 } public enum PullState{ case up case down case loading case none } public typealias ENTRefreshControlPullStateResponse = (PullState, CGRect)->() public class ENTRefreshControl: UIRefreshControl { //MARK: - Private Properties/Methods fileprivate var shouldEndRefresh = true fileprivate var isAnimating = false fileprivate var yAxis: CGFloat { return frame.origin.y } fileprivate var currentState = PullState.none fileprivate func rotateView(_ angle: CGFloat, _ view: UIView) { let radians = angle / 180.0 * CGFloat(Double.pi) let rotation = self.transform.rotated(by: radians) view.transform = rotation } var previous: CGFloat = 0 fileprivate func changeLoaderViewsDirection(_ frame: CGRect) { if let view = loaderView { if !isAnimating { if let state = self.pullState { if yAxis > previous { currentState = .up }else { currentState = .down } previous = yAxis invokeCurrentState }else { if yAxis < -3 { rotateView(yAxis / rotationSpeed.rawValue, view) view.isHidden = false }else { rotateView(0, view) view.isHidden = true } } } } } @available(iOS 10.0, *) fileprivate var vibrateDevice: Void { if shouldVibrate { let generator = UIImpactFeedbackGenerator(style: .light) generator.impactOccurred() } return } //MARK: - Public Properties/Methods public var rotationSpeed = Speed.same public var shouldVibrate: Bool = false { didSet{ if #available(iOS 10.0, *) { self.vibrateDevice } } } public var loaderView: UIView? { willSet(newValue) { if newValue != nil { self.alpha = 0 }else { self.alpha = 1 } changeLoaderViewsDirection(frame) } } public var startRotate: Void { let duration: Double = 1.5 if loaderView?.layer.animation(forKey: kRotationAnimationKey) == nil { let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation") rotationAnimation.fromValue = 0.0 rotationAnimation.toValue = Float.pi * 2.0 rotationAnimation.duration = duration rotationAnimation.repeatCount = Float.infinity loaderView?.layer.add(rotationAnimation, forKey: kRotationAnimationKey) } return } public var stopRotate: Void { if loaderView?.layer.animation(forKey: kRotationAnimationKey) != nil { loaderView?.layer.removeAnimation(forKey: kRotationAnimationKey) } } public var pullState: ENTRefreshControlPullStateResponse? //MARK: - Public Overrides var invokeCurrentState: Void { if let state = self.pullState { state(self.currentState, frame) } } override public func beginRefreshing() { currentState = .loading loaderView?.isHidden = false startRotate super.beginRefreshing() shouldEndRefresh = true isAnimating = true invokeCurrentState endRefreshing() } override public var isRefreshing: Bool { return isAnimating } override public func endRefreshing() { if shouldEndRefresh { super.endRefreshing() shouldEndRefresh = false return } currentState = .none loaderView?.isHidden = true stopRotate isAnimating = false super.endRefreshing() invokeCurrentState } override public init() { super.init() addTarget(self, action: #selector(beginRefreshing), for: .valueChanged) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private let kRotationAnimationKey = "rotationanimationkey" override public var frame: CGRect { didSet{ changeLoaderViewsDirection(frame) } } }
dced8177545b66e43ebf79a1e7a4d6d70b4c54f2
[ "Markdown", "Swift" ]
3
Markdown
syedqamara/ENTRefreshControl
c44fa5aa7503f38a8be2c2daddf962ffa9f01972
e56b0deaa66dbb3cf1c4194b5ef0a5d0e756824a
refs/heads/master
<repo_name>fariqM/RunAway-mobile<file_sep>/src/runbutton/StopRunButton.js import React, { Component, } from 'react'; import { View, Text, TouchableOpacity } from 'react-native'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; class StopSign extends Component { state = { color: 'tomato' } render() { return ( <View style={{ borderWidth: 2, borderColor: 'rgba(0,0,0,0.2)', alignItems: 'center', justifyContent: 'center', width: 80, height: 80, backgroundColor: '#ff6347', borderRadius: 75, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.8, shadowRadius: 5, }}> <MaterialCommunityIcons name="stop" size={50} style={{ paddingTop: 0 }} color={"#5018D9"} /> </View> ) } } export default class StopRunButton extends Component { render() { return ( <View style={{ paddingVertical: 7 }}> <TouchableOpacity delayLongPress={1000} onLongPress={this.props.onLongPress}> <View style={{ alignItems: 'center', paddingLeft: 150 }}> <StopSign /> <Text> Hold To End Run</Text> </View> </TouchableOpacity> </View> ) } }<file_sep>/src/reducers/SettingsReducer.js import {UPDATE_ALL_SETTINGS,} from '../actions/SettingsAction' import {RESET_ALL_SETTINGS,} from '../actions/SettingsAction' //Initial state of the store const initialState = { display_calories:false, display_distance: false, display_pace: false, display_time:false, metric:false, update_frequency:false, } //Modfies the store depending on actions const SettingsReducer = (state = initialState, action) => { switch (action.type) { case UPDATE_ALL_SETTINGS: console.log("SettingsReducer ( UPDATE_ALL_SETTINGS ): updating all settings fields") return { ...state, display_calories: action.display_calories, display_distance: action.display_distance, display_pace: action.display_pace, display_time: action.display_time, metric: action.metric, update_frequency: action.update_frequency, } case RESET_ALL_SETTINGS: console.log("SettingsReducer ( RESET_ALL_SETTINGS ): resetting all settings fields") return { ...state, display_calories:false, display_distance: false, display_pace: false, display_time:false, metric:false, update_frequency:false, } default: console.log("SettingsReducer (",action.type,"): default case (no change to state)") return state } } export default SettingsReducer;<file_sep>/src/screens/CreateAccount.js import React, { Component } from 'react'; import { Text, View, TextInput, Alert, StyleSheet, TouchableOpacity, KeyboardAvoidingView } from 'react-native'; import firebase from 'firebase' import firebaseConfig from '../config/firebaseConfig' import '@firebase/firestore'; import { connect } from 'react-redux' import { ScrollView } from 'react-native-gesture-handler'; //Firebase initialization firebaseConfig export class CreateAccount extends Component { state = { email:null, password:<PASSWORD>, confirmPassword:null, emailValid:false, passwordValid:false, confirmValid:false, } signUp = () => { console.log("CreateAccount: Attempting to sign in a new user") let e = this.state.email; let p = this.state.password; let p2 = this.state.confirmPassword; // Create new user with given username and password if (e != null && e.trim() != "" && p != null && p.trim() != "" && p2 != null && p2.trim() != "") { if (p === p2) { firebase .auth() .createUserWithEmailAndPassword(e, p) .then(() => { console.log("CreateAccount: Successfully signed up new user!") // Reset CreateAccount's state this.setState({email:null,password:null,confirmPassword:null,emailValid:false,passwordValid:false, confirmValid:false}) // Navigate to 'Main' this.props.navigation.navigate("InputPersonalInfo") }) .catch((error) => { Alert.alert(error.message) return }); } else { console.log("CreateAccount: password and confirmPassword do not match") Alert.alert("Passwords do not match") return } } else { console.log("CreateAccount: One of the fields (email, password, confirmPassword) is empty") Alert.alert("Please provide a email address and password") return } } updateEmail = (text) => { if (text.length >= 8) { this.setState({email:text, emailValid:true}) } else { this.setState({email:text, emailValid:false}) } } updatePassword = (text) => { if (text.length >= 8) { this.setState({password:text, passwordValid:true}) } else { this.setState({password:text, passwordValid:false}) } } updateConfirm = (text) => { if (text.length >= 8) { this.setState({confirmPassword:text, confirmValid:true}) } else { this.setState({confirmPassword:text, confirmValid:false}) } } render () { return ( <ScrollView contentContainerStyle={{flexGrow: 1}} keyboardShouldPersistTaps='handled'> <KeyboardAvoidingView style={{flex:1, marginHorizontal:20}} behavior='padding'> {/*SIMPLY RUN*/} <View style={{flex:1, justifyContent:'center', alignItems:'center'}}> <Text style={styles.titleText}>RunAway</Text> </View> <View style={{flex:2}}> {/*TextInput for email*/} <TextInput placeholder="Email" value={this.state.email} onChangeText={(text) => this.updateEmail(text)} autoCapitalize='none' returnKeyType={'next'} onSubmitEditing={() => { this.passwordInput.focus(); }} keyboardType='email-address' style={styles.textInput} /> {/*TextInput for password*/} <TextInput placeholder="Password" value={this.state.password} onChangeText={(text) => this.updatePassword(text)} secureTextEntry autoCapitalize='none' returnKeyType={'next'} ref={(input) => { this.passwordInput = input; }} onSubmitEditing={() => {this.confirm.focus()}} keyboardType='email-address' style={styles.textInput} /> {/*TextInput for confirmPassword*/} <TextInput placeholder="Confirm Password" value={this.state.confirmPassword} onChangeText={(text) => this.updateConfirm(text)} secureTextEntry autoCapitalize='none' returnKeyType={'done'} ref={(input) => { this.confirm = input; }} onSubmitEditing={() => {this.signUp()}} keyboardType='email-address' style={styles.textInput} /> {/*Button for signing up user*/} <TouchableOpacity onPress={() => this.signUp()} disabled={(this.state.emailValid && this.state.passwordValid && this.state.confirmValid ? false : true)}> <View style={{ height:50, backgroundColor: (this.state.emailValid && this.state.passwordValid && this.state.confirmValid ? "lightblue" : "lightgray"), justifyContent:'center', alignItems:'center', paddingHorizontal:15,}}> <Text style={{fontSize:20,color:'black'}}>Sign Up!</Text> </View> </TouchableOpacity> </View> </KeyboardAvoidingView> </ScrollView> ) } } export default connect()(CreateAccount); const styles = StyleSheet.create({ textInput: { borderWidth: 1, borderColor: 'lightgrey', height:50, maxHeight:50, justifyContent:'center', padding:5, }, titleText: { fontSize:40, fontWeight:'bold', fontStyle:'italic', } });<file_sep>/src/actions/PersonalInfoAction.js export const UPDATE_NAME = "UPDATE_NAME" export const UPDATE_BIRTH = "UPDATE_BIRTH" export const UPDATE_HEIGHT = "UPDATE_HEIGHT" export const UPDATE_WEIGHT = "UPDATE_WEIGHT" export const UPDATE_SEX = "UPDATE_SEX" export const UPDATE_EMAIL = "UPDATE_EMAIL" export const UPDATE_ALL_PERSONAL_INFO = "UPDATE_ALL_PERSONAL_INFO" export const RESET_ALL = "RESET_ALL" export const updateNameAction = (name) => { return { type: UPDATE_NAME, name:name, } } export const updateBirthdayAction = (birthday) => { return { type: UPDATE_BIRTH, birthday:birthday, } } export const updateHeightAction = (height) => { return { type: UPDATE_HEIGHT, height:height, } } export const updateWeightAction = (weight) => { return { type: UPDATE_WEIGHT, weight:weight, } } export const updateSexAction = (sex) => { return { type: UPDATE_SEX, sex:sex, } } export const updateEmailAction = (email) => { return { type: UPDATE_EMAIL, email:email, } } export const updateAllPersonalInfoAction = (personal) => { return { type: UPDATE_ALL_PERSONAL_INFO, name: personal.name, email: personal.email, birthday: personal.birthday.seconds, height: personal.height, weight: personal.weight, sex: personal.sex, } } export const resetAllAction = () => { return { type: RESET_ALL, } }<file_sep>/src/config/firebaseConfig.js import * as firebase from 'firebase'; import '@firebase/firestore'; /* * FIREBASE CONFIGURATION * This file is used for connecting the app to the firebase database using the API provided by firebase. */ const firebaseConfig = { apiKey: "<KEY>", authDomain: "runaway-fa0af.firebaseapp.com", databaseURL: "https://runaway-fa0af-default-rtdb.firebaseio.com", projectId: "runaway-fa0af", storageBucket: "runaway-fa0af.appspot.com", messagingSenderId: "918071183240", appId: "1:918071183240:web:125218a49ebbf3df355c3d" }; // Initialize Firebase export default firebase.initializeApp(firebaseConfig);<file_sep>/README.md # RunAway-mobile A run tracking application based on Android platform using React Native, Maps API, Firebase, Redux. How to install 1. git clone https://github.com/fariqM/RunAway-mobile.git 2. use npm version 6.14.8 and NodeJs version 14.15.0 (Optional) 3. cd RunAway-mobile 4. npm install 5. connect devices or emulator (Watch on youtub) 6. run application 7. npx react-native run-android -OR (if disconnect from server) 8. npx react-native start 9. npx react-native run-android # Demo <img src="https://user-images.githubusercontent.com/71390462/126753877-7f65b0e6-0624-40d3-9490-ab3689764d1e.jpeg" width="350" height="600"> <img src="https://user-images.githubusercontent.com/71390462/126753933-dbd24184-fc11-455f-9800-49dc91c686d1.jpeg" width="350" height="600"> <img src="https://user-images.githubusercontent.com/71390462/126753970-c6fe6531-4f54-411f-81b2-0e15dd44c99f.jpeg" width="350" height="600"> <img src="https://user-images.githubusercontent.com/71390462/126753980-b0e53bdd-19d5-4e05-a865-b25851bd7eb5.jpeg" width="350" height="600"> <img src="https://user-images.githubusercontent.com/71390462/126754011-b25be8cf-35b1-403d-8673-817e27e56d4c.jpeg" width="350" height="600"> <file_sep>/src/runbutton/StartButton.js import React, { Component, } from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; export default class StartButton extends Component { render() { return ( <TouchableOpacity style={{ borderWidth: 2, borderColor: 'rgba(0,0,0,0.2)', alignItems: 'center', justifyContent: 'center', width: 80, height: 80, backgroundColor: '#32cd32', borderRadius: 75, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.8, shadowRadius: 5, }} delayLongPress={1000} onPress={this.props.onPress} onLongPress={this.props.onLongPress} > {this.props.pauseButton ? <View style={{ flexDirection: "row", justifyContent: 'space-between' }}> <MaterialCommunityIcons name="pause" size={50} style={{ paddingTop: 0 }} color={"#5018D9"} /> </View> : <View> <MaterialCommunityIcons name="play" size={50} style={{ paddingTop: 0 }} color={"#5018D9"} /> </View> } </TouchableOpacity> ) } } <file_sep>/src/screens/SuccessLogin.js import React, {Component} from 'react'; import {View, Text, StyleSheet, Dimensions} from 'react-native'; import MapView, {Marker, Polyline, PROVIDER_GOOGLE} from 'react-native-maps'; import Geolocation from '@react-native-community/geolocation'; class Apps extends Component { constructor() { super(); this.state = { initialPosition: { latitude: 0, longitude: 0, latitudeDelta: 0.0102, longitudeDelta: 0.0101, }, marker: { latitude: 0, longitude: 0, }, }; } componentDidMount() { Geolocation.getCurrentPosition( position => { var lat = parseFloat(position.coords.latitude); var long = parseFloat(position.coords.longitude); var initialRegion = { latitude: lat, longitude: long, latitudeDelta: 0.0102, longitudeDelta: 0.0101, }; var Mymarker = { latitude: lat, longitude: long, }; this.setState({initialPosition: initialRegion}); this.setState({marker: Mymarker}); }, error => alert(JSON.stringify(error)), ); } render() { return ( <View style={styles.container}> <MapView style={styles.map} initialRegion={this.state.initialPosition}> <Marker coordinate={this.state.marker} title={'SAYA'}></Marker> </MapView> </View> ); } } const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'flex-end', alignItems: 'center', }, map: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, }, }); export default Apps; <file_sep>/src/navigation/endRunNavigator.js import * as React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import SimplyRun from '../screens/SimplyRun'; import EndRun from '../screens/EndRun'; const Stack = createStackNavigator(); const INITIAL_ROUTE_NAME = 'SimplyRun'; export default function endRunNavigator({ navigation, route }) { return ( <Stack.Navigator screenOptions={{ headerShown: false }} initialRouteName={INITIAL_ROUTE_NAME}> <Stack.Screen name="SimplyRun" component={SimplyRun} /> <Stack.Screen name="EndRun" component={EndRun} /> </Stack.Navigator> ); }<file_sep>/src/constants/ConversionFunctions.js const HEIGHT_RATIO = 0.393701; const WEIGHT_RATIO = 0.453592; export const convertInchesToCentimeters = (inches) => { // cm = in / 0.393701 console.log("ConversionFunctions: convertInchesToCentimeters ( inches=", inches,")") return Math.round(inches / HEIGHT_RATIO) } export const convertCentimetersToInches = (centimeters) => { // in = cm * 0.393701 console.log("ConversionFunctions: convertCentimetersToInches ( inches=", centimeters,")") return Math.round(centimeters * HEIGHT_RATIO) } export const convertPoundsToKilograms = (pounds) => { // kg = lb * 0.453592 console.log("ConversionFunctions: convertPoundsToKilograms ( pounds=", pounds,")") return Math.round(pounds * WEIGHT_RATIO) } export const convertKilogramsToPounds = (kilograms) => { // lb = km / 0.453592 console.log("ConversionFunctions: convertKilogramsToPounds ( kilograms=", kilograms,")") return Math.round(kilograms / WEIGHT_RATIO) }<file_sep>/src/screens/Login.js import React, { Component } from 'react'; import { Text, View, TextInput, TouchableOpacity, Alert, StyleSheet, KeyboardAvoidingView } from 'react-native'; import firebase from 'firebase'; import firebaseConfig from '../config/firebaseConfig' import { connect } from 'react-redux' import { ScrollView } from 'react-native-gesture-handler'; import { addRunAction } from '../actions/RunLogAction' import { updateAllPersonalInfoAction } from '../actions/PersonalInfoAction' import { updateAllSettingsAction } from '../actions/SettingsAction' import firestore from '@react-native-firebase/firestore'; //References to the root of the firestore database // const firestore = firebase.firestore(); //Firebase initialzation firebaseConfig export class Login extends Component { state = { email: null, password: <PASSWORD>, emailValid: false, passwordValid: false, } // Function to navigate to the CreateAcount Screen goToCreateAccount = () => { this.props.navigation.navigate('CreateAccount'); } // Function to navigate to the CreateAcount Screen gotToForgotPassword = () => { this.props.navigation.navigate('ForgotPassword'); } signIn = () => { console.log("Login: Attempting to sign in existing user") let e = this.state.email let p = this.state.password // Login existing user with given username and password if (e != null && p != null && e.trim() != "" && p != "") { firebase .auth() .signInWithEmailAndPassword(e, p) .then(() => { console.log("Login: Successfully signed in existing user!") let user = firebase.auth().currentUser // this.props.navigation.navigate("SuccessLogin") console.log("Login: Attempting to fetch user data for user with uid=", user.uid) let userRef = firestore().collection('users').doc(user.uid) // Fetch User Data from firestore database userRef.get().then((doc) => { console.log("Login: Successfully fetched user data for user with uid=", user.uid) let userData = doc.data() // Update all personal info in store this.props.dispatch(updateAllPersonalInfoAction(userData.personal)) // Update all settings info in store this.props.dispatch(updateAllSettingsAction(userData.settings)) // ***** Fetch RunLog from firestore database ***** userRef.collection("RunLog").get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { const run = { id: doc.id, note: doc.get("note"), time: doc.get("time"), distance: doc.get("distance"), pace: doc.get("pace"), calories: doc.get("calories"), start_time: doc.get("start_time").toDate(), end_time: doc.get("end_time").toDate(), route: doc.get("route"), } this.props.dispatch(addRunAction(run)) }) }).catch((error) => { console.log("Login: Error fetching run data:", error.message) Alert.alert("Login:"+error.message) }) // Navigate to main this.props.navigation.navigate("Main") }) .catch((error) => { console.log("Login: Error fetching user data:", error.message) Alert.alert(error.message) firebase.auth().signOut(); }) }) .catch((error) => { console.log("Login: Error signing in user:", error.message) Alert.alert(error.message) return }); // Reset Login's state this.setState({ email: null, password: <PASSWORD>, emailValid: false, passwordValid: false }) } else { console.log("Login: One of the fields (email, password) is empty") Alert.alert("Please provide a email address and password") return } } updateEmail = (text) => { if (text.length >= 8) { this.setState({ email: text, emailValid: true }) } else { this.setState({ email: text, emailValid: false }) } } updatePassword = (text) => { if (text.length >= 8) { this.setState({ password: text, passwordValid: true }) } else { this.setState({ password: text, passwordValid: false }) } } render() { return ( <ScrollView contentContainerStyle={{ flexGrow: 1 }} keyboardShouldPersistTaps='handled'> <KeyboardAvoidingView style={{ flex: 1, marginHorizontal: 20 }} behavior='padding'> {/*SIMPLY RUN*/} <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text style={styles.titleText}>Runaway</Text> </View> <View style={{ flex: 2 }}> {/*TextInput for email address*/} <TextInput placeholder="Email" value={this.state.email} onChangeText={(text) => this.updateEmail(text)} autoCapitalize='none' returnKeyType={"next"} onSubmitEditing={() => { this.passwordInput.focus(); }} keyboardType='email-address' style={styles.textInput} /> {/*TextInput for password*/} <TextInput placeholder="<PASSWORD>" value={this.state.password} onChangeText={(text) => this.updatePassword(text)} autoCapitalize='none' returnKeyType={'done'} ref={(input) => { this.passwordInput = input; }} onSubmitEditing={() => { this.signIn() }} keyboardType='email-address' secureTextEntry style={styles.textInput} /> {/*Button for signing user*/} <TouchableOpacity onPress={() => this.signIn()} disabled={(this.state.emailValid && this.state.passwordValid ? false : true)}> <View style={{ height: 50, backgroundColor: (this.state.emailValid && this.state.passwordValid ? "light<PASSWORD>" : "<PASSWORD>"), justifyContent: 'center', alignItems: 'center', paddingHorizontal: 15, }}> <Text style={{ fontSize: 20, color: 'black' }}>Sign In!</Text> </View> </TouchableOpacity> {/*Button for changing to the CreateAccount screen*/} <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 75 }}> <Text style={{ fontSize: 18 }}>Don't have an account?</Text> <Text style={{ fontSize: 18, color: '#076fd9', paddingLeft: 10 }} onPress={this.goToCreateAccount}>Sign Up!</Text> </View> {/*Button for resetting forgotten password*/} {/* <View style={{justifyContent:'center', alignItems:'center', height:25}}> <Text style={{fontSize:18, color:'#076fd9'}} onPress={this.gotToForgotPassword}>Forgot Password?</Text> </View> */} </View> </KeyboardAvoidingView> </ScrollView> ); } } export default connect()(Login) const styles = StyleSheet.create({ textInput: { borderWidth: 1, borderColor: 'lightgrey', height: 50, maxHeight: 50, justifyContent: 'center', padding: 8, }, titleText: { fontSize: 40, fontWeight: 'bold', fontStyle: 'italic', } });<file_sep>/App.js import * as React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import BottomTabNavigator from './src/navigation/BottomTabNavigator'; import Launch from './src/screens/Launch' import Login from './src/screens/Login'; import ForgotPassword from './src/screens/ForgotPassword'; import CreateAccount from './src/screens/CreateAccount' import SuccessLogin from './src/screens/SuccessLogin' import InputPersonalInfo from './src/screens/InputPersonalInfo' import { createStore } from 'redux' import { Provider } from 'react-redux' import rootReducer from './src/reducers' // Importing the index (do not need specifying) import { decode, encode } from 'base-64' if (!global.btoa) { global.btoa = encode } if (!global.atob) { global.atob = decode } //Create a stack navigator const Stack = createStackNavigator(); //Create a store using the rootReducer const store = createStore(rootReducer) export default function App() { return ( <Provider store={store}> <NavigationContainer > <Stack.Navigator > <Stack.Screen name="Launch" options={{headerLeft: null}} component={Launch}/> <Stack.Screen name="Login" options={{ headerLeft: null }} component={Login}/> <Stack.Screen name="CreateAccount" component={CreateAccount}/> <Stack.Screen name="ForgotPassword" component={ForgotPassword}/> <Stack.Screen name="InputPersonalInfo" component={InputPersonalInfo}/> <Stack.Screen name="SuccessLogin" component={SuccessLogin}/> <Stack.Screen name="Main" options={{ headerLeft: null }} component={BottomTabNavigator} /> </Stack.Navigator> </NavigationContainer> </Provider> ); } <file_sep>/src/screens/EndRun.js import React, { Component } from 'react'; import { Text, View, TextInput, TouchableOpacity, Alert, KeyboardAvoidingView } from 'react-native'; import firebaseConfig from '../config/firebaseConfig' import * as firebase from 'firebase'; // import '@firebase/firestore'; import firestore from '@react-native-firebase/firestore'; import { connect } from 'react-redux' import MapView, { Polyline } from 'react-native-maps'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import {addRunAction} from '../actions/RunLogAction' //Initialize firebase firebaseConfig // const Firestore = firebase.firestore(); class EndRun extends Component { state = { notes: "", distance: 0, pace: 0, timeToDisplay: "" } writeNote = (note) => { this.setState({ notes: note }) } sendToFirebase = () => { firestore().collection('users').doc(firebase.auth().currentUser.uid).collection("RunLog").add({ calories: this.props.calories, distance: this.props.distance, end_time: this.props.endTime, note: this.state.notes, route: this.props.route, start_time: this.props.startTime, time: this.props.time, pace: this.props.pace }).then((doc) => { const run = { id: doc.id, calories: this.props.calories, distance: this.props.distance, end_time: this.props.endTime, note: this.state.notes, route: this.props.route, start_time: this.props.startTime, time: this.props.time, pace: this.props.pace } this.props.addRun(run) }) } saveRun = () => { Alert.alert("Run Saved") this.sendToFirebase(); this.props.clearRun(); this.props.navigation.navigate('SimplyRun'); } dontSave = () => { this.props.clearRun(); this.props.navigation.navigate('SimplyRun') } discardRun = () => { Alert.alert( 'Are you sure you want to discard this run?', 'This cannot be undone', [ { text: 'Yes', onPress: () => { this.dontSave() } }, { text: 'No', style: 'cancel', } ], { cancelable: false }, ); } render() { return ( <View style={{ flex: 1, }}> <MapView showsUserLocation={true} style={{ flex: 2 }} followsUserLocation={true} > <Polyline coordinates={this.props.polyline} strokeWidth={5} /> </MapView> <KeyboardAvoidingView behavior='padding' keyboardVerticalOffset='100' style={{ alignItems: 'center', backgroundColor: '#A44CA0' }}> <View style={{ justifyContent: 'center', alignItems: 'center', backgroundColor: '#A44CA0' }} > <Text style={{ fontSize: 20, }} > {"Run Complete"} </Text> {this.props.display_time ?< Text > { "Time: " + ("" + this.props.hours).padStart(2, "0") + ":" + ("" + this.props.mins).padStart(2, "0") + ":" + ("" + this.props.secs).padStart(2, "0") + " hr:min:sec"} </Text>: null} {!this.props.metric && this.props.display_distance ? < Text style={{ left: 10 }}>{"Distance: " + this.props.distance.toFixed(2) + " miles"} </Text> : null} {this.props.metric && this.props.display_distance ? <Text style={{ left: 10 }}>{"Distance: " + (this.props.distance * 1.609).toFixed(2) + " km"} </Text> : null} {!this.props.metric && this.props.display_pace ? <Text style={{ left: 14 }}>{"Pace: " + (this.props.pace).toFixed(2) + " mins/mile"} </Text> : null} {this.props.metric && this.props.display_pace ? <Text style={{ left: 14 }}>{"Pace: " + (this.props.pace * .621).toFixed(2) + " mins/km"} </Text>: null} {this.props.display_calories? < Text style={{ left: 14, paddingBottom: 10 }}>{"Calories: " + this.props.calories.toFixed(0) + " cals"} </Text>: null} <TextInput style={{ paddingLeft: 7, borderWidth: 5, borderColor: 'black', right: 0, width: 200 }} placeholder="Notes " autoCapitalize="none" onChangeText={note => this.writeNote(note)} value={this.state.notes} multiline blurOnSubmit={true} /> <View style={{ paddingTop: 30, flexDirection: 'row', alignContent: 'space-between' }}> <TouchableOpacity style={{ right: 20, width: 90, height: 90, backgroundColor: '#FFD700', borderRadius: 200 / 2, alignItems: 'center' }} onPress={() => this.saveRun()}> <MaterialCommunityIcons name="check" size={50} style={{ paddingTop: 5 }} color={"#5018D9"} /> <Text style={{ paddingBottom: 0, color: "#5018D9" }}>Save Run </Text> </TouchableOpacity> <TouchableOpacity style={{ left: 20, width: 90, height: 90, backgroundColor: 'darkorange', borderRadius: 200 / 2, alignItems: 'center' }} onPress={() => this.discardRun()}> <MaterialCommunityIcons name="trash-can-outline" size={50} style={{ paddingTop: 5 }} color={"#5018D9"} /> <Text style={{ paddingVertical: 0, color: "#5018D9" }}>Discard</Text> </TouchableOpacity> </View> </View> </KeyboardAvoidingView > </View> ); } } class Circle extends Component { render() { return ( <View style={{ width: 75, height: 75, backgroundColor: 'darkcyan', borderRadius: 200 / 2 }} /> ) } } //Getting the states from the store and mapping it to props in the Login function mapStateToProps(state) { return { time: state.endRunReducer.time, distance: state.endRunReducer.distance, pace: state.endRunReducer.pace, calories: state.endRunReducer.calories, startTime: state.endRunReducer.startTime, endTime: state.endRunReducer.endTime, route: state.endRunReducer.route, hours: state.endRunReducer.hours, mins: state.endRunReducer.mins, secs: state.endRunReducer.secs, polyline: state.endRunReducer.polyline, display_calories: state.SettingsReducer.display_calories, display_distance: state.SettingsReducer.display_distance, display_pace: state.SettingsReducer.display_pace, display_time: state.SettingsReducer.display_time, metric: state.SettingsReducer.metric, update_frequency: state.SettingsReducer.update_frequency, } } //Sends actions to the reducer in the App.js file function mapDispatchtoProps(dispatch) { return { sendTime: (time) => dispatch({ type: "ENDRUN", time }), clearRun: () => dispatch({ type: "CLEARRUN" }), addRun: (run) => dispatch(addRunAction(run)) } } //Connecting the react components to the store in App.js export default connect(mapStateToProps, mapDispatchtoProps)(EndRun);<file_sep>/src/navigation/settingsNavigator.js import * as React from 'react'; import {NavigationContainer} from '@react-navigation/native'; import {createStackNavigator} from '@react-navigation/stack'; import Settings from '../screens/Settings'; import editSettings from '../screens/editSettings'; import UpdateEmailPassword from '../screens/updateEmailPassword'; const Stack = createStackNavigator(); const INITIAL_ROUTE_NAME = 'Settings'; export default function settingsNavigator({ navigation, route }) { return ( <Stack.Navigator screenOptions={{ headerShown: false }} initialRouteName={ INITIAL_ROUTE_NAME }> <Stack.Screen name="SETTINGS" component={Settings} /> <Stack.Screen name="EDIT" component={editSettings} /> <Stack.Screen name="EMAILPASSWORD" component={UpdateEmailPassword} /> </Stack.Navigator> ); } <file_sep>/src/calories/CalculateCalories.js //weight in kg //avgSpeed in km/hr //time in minutes export default function calculateCalories(weight, avgSpeed, time) { let met = 0 if (avgSpeed < 1.6) { met = 1 } else if (1.6 <= avgSpeed && avgSpeed < 3.2) { met = 2 } else if (3.2 <= avgSpeed && avgSpeed < 4.02) { met = 2.75 } else if (4.02 <= avgSpeed && avgSpeed < 4.82) { met = 3 } else if (4.82 <= avgSpeed && avgSpeed < 5.68) { met = 4 } else if (5.68 <= avgSpeed && avgSpeed < 6.43) { met = 5 } else if (6.43 <= avgSpeed && avgSpeed < 8.04) { met = 6.5 } else if (8.04 <= avgSpeed && avgSpeed < 8.36) { met = 8.3 } else if (8.36 <= avgSpeed && avgSpeed < 9.65) { met = 9 } else if (9.65 <= avgSpeed && avgSpeed < 10.78) { met = 9.8 } else if (10.78 <= avgSpeed && avgSpeed < 11.26) { met = 10.5 } else if (11.26 <= avgSpeed && avgSpeed < 12.07) { met = 11 } else if (12.06 <= avgSpeed && avgSpeed < 12.87) { met = 11.5 } else if (12.87 <= avgSpeed && avgSpeed < 13.84) { met = 11.8 } else if (13.84 <= avgSpeed && avgSpeed < 14.48) { met = 12.3 } else if (14.48 <= avgSpeed && avgSpeed < 16.09) { met = 12.8 } else if (16.09 <= avgSpeed && avgSpeed < 17.70) { met = 14.5 } else if (17.70 <= avgSpeed && avgSpeed < 19.31) { met = 16 } else if (19.31 <= avgSpeed && avgSpeed < 20.92) { met = 19 } else if (20.92 <= avgSpeed && avgSpeed < 22.53) { met = 19.8 } else { met = 23 } return ((weight*2.2)/200 * 7.7 * met * time/60) }// JavaScript source code <file_sep>/__mock_stores__/populatedRunsState.js import firebase from 'firebase'; export default { UserAuthenticationReducer: { signedIn:false, user:null, }, PersonalInfoReducer: { name:null, email: null, birthday: null, height: null, weight:100, sex:"male", }, SettingsReducer: { display_calories:false, display_distance: false, display_pace: false, display_time:false, metric:false, update_frequency:false, }, endRunReducer: { time: 0, distance: 0, pace: 0, calories: 0, startTime: "", endTime: "", route: [], hours: 0, mins: 0, secs: 0 }, RunLogReducer: { runs:[ { id: "testID", note: "well done Jon", time: 720, distance: 2.1, pace: 5.71428571, calories: 0, start_time: new Date("2020-03-22T12:48:54Z"), end_time: new Date("2020-03-22T13:00:54Z"), route: [new firebase.firestore.GeoPoint(43.073051,-89.40123), new firebase.firestore.GeoPoint(43.073451,-89.40123)], } ], total_time:0, total_distance:0, total_calories:0, } } <file_sep>/src/screens/Settings.js import React, { Component } from 'react'; import { Text, View, TouchableOpacity, StyleSheet, Alert, TextInput } from 'react-native'; import { ScrollView } from 'react-native-gesture-handler'; import { Button, Paragraph, Dialog, Portal, Provider } from 'react-native-paper'; import firebase from 'firebase'; import firestore from '@react-native-firebase/firestore'; import firebaseConfig from '../config/firebaseConfig'; import { connect } from 'react-redux'; import {convertInchesToCentimeters, convertPoundsToKilograms} from '../constants/ConversionFunctions'; import {resetAllAction} from '../actions/PersonalInfoAction'; import {resetRunsAction} from '../actions/RunLogAction'; import {resetAllSettingsAction} from '../actions/SettingsAction'; //References to the root of the firestore database // const firestore = firebase.firestore(); //Firebase initialzation firebaseConfig export class Settings extends Component { state = { visible: false, password: "", }; _showDialog = () => this.setState({ visible: true }); _hideDialog = () => this.setState({ visible: false, password: "" }); render() { return ( <Provider> <ScrollView> <View> <Text style = {styles.title}>My Profile</Text> <Text style = {styles.text}> Name: {this.props.name}</Text> <Text style = {styles.text}> Email: {this.props.email}</Text> <Text style = {styles.text}> Height: {(this.props.metric ? (Math.floor(this.props.height / 100) + "m " + Math.round(this.props.height % 100) + "cm") : (Math.floor(this.props.height / 12) + "' ") + Math.round(this.props.height % 12) + '"')}</Text> <Text style = {styles.text}> Weight: {this.props.weight} {(this.props.metric ? "kg" : "lbs")}</Text> <Text style = {styles.text}> Sex: {this.props.sex}</Text> <Text style = {styles.text}> Age: {this.props.age}</Text> <Text> </Text> <Text style = {styles.title}>Settings</Text> <Text style = {styles.text}> Unit: {(this.props.metric ? "Metric" : "Imperial")} </Text> <Text style = {styles.text}> Stats Displayed: {this.props.stats_to_display} </Text> {/* <Text style = {styles.text}> Audio Updates: {(this.props.update_frequency ? "On" : "Off")} </Text> */} {/* Button to update email address and/or password */} {/* <TouchableOpacity style={styles.updateButton} onPress={() => { this.props.navigation.navigate("EMAILPASSWORD"); } }> <Text style={styles.buttonText}>Update Email/Password</Text> </TouchableOpacity> */} {/* Button to edit non-email/password portions of profile */} <TouchableOpacity style={styles.editButton} onPress={() => { this.props.navigation.navigate("EDIT"); } }> <Text style={styles.buttonText}>Edit Profile</Text> </TouchableOpacity> {/* Logout button. Redirects to login screen. */} <TouchableOpacity style={styles.logoutButton} onPress={() => { this.props.dispatch(resetAllAction()); this.props.dispatch(resetRunsAction()); this.props.dispatch(resetAllSettingsAction()); firebase.auth().signOut().then(() => { console.log("Logout successful"); this.props.navigation.navigate("Login"); }).catch(() => { console.log("ERROR: problem logging user out"); }) } }> <Text style={styles.buttonText}>Logout</Text> </TouchableOpacity> {/* Allows user to delete their account. Requires re-authentication. Redirects to login screen once user provides password and confirms via dialog box. */} <View> {/* <TouchableOpacity style={styles.deleteButton} onPress={this._showDialog}> <Text style={styles.buttonText}>Delete Account</Text> </TouchableOpacity> */} {/* <Portal> <Dialog visible={this.state.visible} onDismiss={this._hideDialog}> <Dialog.Title>Delete Account</Dialog.Title> <Dialog.Content> <Paragraph>This action requires enhanced security. Please provide your password:</Paragraph> <TextInput placeholder="<PASSWORD>" value={this.state.password} onChangeText={(text) => this.setState({password: text})} textContentType='oneTimeCode' secureTextEntry autoCapitalize='none' returnKeyType={'next'} ref={(input) => { this.passwordInput = input; }} onSubmitEditing={() => {this.confirm.focus()}} keyboardType='email-address' style={styles.textInput} /> </Dialog.Content> <Dialog.Actions> <Button onPress={() => { var credential = firebase.auth.EmailAuthProvider.credential( this.props.email, this.state.password ); firebase.auth().currentUser.reauthenticateWithCredential(credential).then(() => { Alert.alert( 'Warning', 'Are you sure you want to delete your account? This cannot be undone.', [ { text: "Yes", onPress: () => { var user = firebase.auth().currentUser; var uid = user.uid; // deletes firestore entry, then deletes firebase auth object firestore().collection('users').doc(uid).delete().then(() => { console.log("Account " + this.props.name + " removed from firestore"); user.delete().then(() => { console.log("Account " + this.props.name + " from firebase auth."); }).catch(() => { console.log("ERROR: problem deleting user from firebase auth"); this._hideDialog; }) this.props.navigation.navigate('Login'); }).catch(() => { console.log("ERROR: problem deleting user from firestore."); this._hideDialog; }) } }, {text: 'No', style: 'cancel'} ], { cancelable: false } ); }).catch((error) => { console.log("DeleteAccount: An error occurred while reauthenticating"); Alert.alert("An error occurred while reauthenticating"); }); }}>Confirm</Button> <Button onPress={this._hideDialog}>Cancel</Button> </Dialog.Actions> </Dialog> </Portal> */} </View> </View> </ScrollView> </Provider> ); } } const styles = StyleSheet.create({ textInput: { borderWidth: 1, borderColor: 'lightgrey', height:50, maxHeight:50, justifyContent:'center', padding:5, margin: 5 }, title: { fontSize: 18, fontWeight: "bold", textAlign: "center", padding: 5 }, text: { textAlign: "center", padding: 2 }, editButton: { marginLeft: 104, marginRight: 104, marginTop:10, paddingTop:10, paddingBottom:10, backgroundColor:'#A44CA0', borderRadius:10, borderWidth: 1, borderColor: '#fff' }, updateButton: { marginLeft: 104, marginRight: 104, marginTop:10, paddingTop:10, paddingBottom:10, backgroundColor:'#C44CA0', borderRadius:10, borderWidth: 1, borderColor: '#fff' }, buttonText: { color:'#fff', textAlign:'center', paddingLeft : 25, paddingRight : 25 }, deleteButton: { marginLeft: 104, marginRight: 104, marginTop:10, paddingTop:10, paddingBottom:10, backgroundColor:'#F05353', borderRadius:10, borderWidth: 1, borderColor: '#fff' }, logoutButton: { marginLeft: 104, marginRight: 104, marginTop:10, paddingTop:10, paddingBottom:10, backgroundColor:'#FC0205', borderRadius:10, borderWidth: 1, borderColor: '#fff' } }); function mapStateToProps(state) { return { // all local states based on global props so that when editSettings changes them, they are updated here name: state.PersonalInfoReducer.name, email: state.PersonalInfoReducer.email, age: Math.floor(((Math.round(new Date().getTime()/1000)) - state.PersonalInfoReducer.birthday)/(3600*24*365)), height: ((state.SettingsReducer.metric) ? (convertInchesToCentimeters(state.PersonalInfoReducer.height)) : state.PersonalInfoReducer.height), weight: ((state.SettingsReducer.metric) ? (convertPoundsToKilograms(state.PersonalInfoReducer.weight)) : state.PersonalInfoReducer.weight), sex: state.PersonalInfoReducer.sex, stats_to_display: ("" + ((state.SettingsReducer.display_time) ? "Time, " : "") + ((state.SettingsReducer.display_pace) ? "Pace, " : "") + ((state.SettingsReducer.display_distance) ? "Distance, " : "") + ((state.SettingsReducer.display_calories) ? "Calories, " : "")).slice(0, -2), display_calories: state.SettingsReducer.display_calories, display_distance: state.SettingsReducer.display_distance, display_pace: state.SettingsReducer.display_pace, display_time: state.SettingsReducer.display_time, metric: state.SettingsReducer.metric, update_frequency: state.SettingsReducer.update_frequency, } } export default connect(mapStateToProps)(Settings);<file_sep>/src/reducers/endRunReducer.js import { END_RUN, } from '../actions/EndRunAction' const initialState = { time: 0, distance: 0, pace: 0, calories: 0, startTime: "", endTime: "", route: [], hours: 0, mins: 0, secs: 0, polyline: [] } //Modfies the store depending on actions const endRunReducer = (state = initialState, action) => { switch (action.type) { case END_RUN: return (state, { time: action.time, distance: action.distance, pace: action.pace, calories: action.calories, startTime: action.startTime, endTime: action.endTime, route: action.route, hours: action.hours, mins: action.mins, secs: action.secs, polyline: action.polyline }) case "CLEARRUN": return state default: return state } } export default endRunReducer;<file_sep>/src/screens/Launch.js import React, { Component } from 'react'; import { Text, View, Image, Alert, StyleSheet} from 'react-native'; import { ScrollView } from 'react-native-gesture-handler'; import firebase from 'firebase'; import firebaseConfig from '../config/firebaseConfig' import { connect } from 'react-redux' import firestore from '@react-native-firebase/firestore'; import {addRunAction} from '../actions/RunLogAction' import {updateAllPersonalInfoAction} from '../actions/PersonalInfoAction' import {updateAllSettingsAction} from '../actions/SettingsAction' //References to the root of the firestore database // const firestore = firebase.firestore(); //Firebase initialzation firebaseConfig export class Launch extends Component { constructor(props){ super(props) const user = firebase.auth().currentUser if (user) { console.log("Launch: Attempting to fetch user data for user with uid=", user.uid) let userData = firestore().collection('users').doc(user.uid) let runData = userData.collection('RunLog') // Fetch User Data from firestore database userData.get().then((doc) => { console.log("Launch: Successfully fetched user data for user with uid=", user.uid) let userData = doc.data() // Update all personal info in store this.props.dispatch(updateAllPersonalInfoAction(userData.personal)) // Update all settings info in store this.props.dispatch(updateAllSettingsAction(userData.settings)) // ***** Fetch Run Log from firestore database ***** runData.get().then((querySnapshot) => { querySnapshot.forEach((doc) => { const run = { id: doc.id, note: doc.get("note"), time: doc.get("time"), distance: doc.get("distance"), pace: doc.get("pace"), calories: doc.get("calories"), start_time: doc.get("start_time").toDate(), end_time: doc.get("end_time").toDate(), route: doc.get("route"), } this.props.dispatch(addRunAction(run)) }) }).catch((error) => { console.log("Launch: Error fetching run data:", error.message) // Alert.alert("Launch:"+error.message) }) // Navigate to main this.props.navigation.navigate("Main") }) .catch((error) => { console.log("Launch: Error fetching user data:", error.message) Alert.alert(error.message) firebase.auth().signOut(); this.props.navigation.navigate("Login") }) } else { console.log("Launch: No current user is signed in.") this.props.navigation.navigate("Login") } } render() { return ( <ScrollView contentContainerStyle={{flexGrow: 1}}> <View style={{flex:1, justifyContent:'center', alignItems:'center'}}> <Text style={styles.titleText}>Simply Run</Text> </View> <View style={{flex:3, justifyContent:'center', alignItems:'center'}}> <Image style={styles.runnerImage} source={require('../../assets/images/simple_runner.png')} /> </View> </ScrollView> ); } } export default connect()(Launch) const styles = StyleSheet.create({ runnerImage:{ width:200, height:250, resizeMode:'stretch', }, titleText: { fontSize:40, fontWeight:'bold', fontStyle:'italic', } });<file_sep>/src/reducers/index.js import { combineReducers } from 'redux' // 1. Import Reducers here // import exampleReducer from './exampleReducer' import endRunReducer from './endRunReducer' import SettingsReducer from './SettingsReducer' import PersonalInfoReducer from './PersonalInfoReducer' import RunLogReducer from './RunLogReducer' export default combineReducers({ RunLogReducer, endRunReducer, SettingsReducer, PersonalInfoReducer, })<file_sep>/src/screens/ForgotPassword.js import React, { Component } from 'react'; import { Text, View, TextInput, TouchableOpacity, Alert, StyleSheet, KeyboardAvoidingView} from 'react-native'; import { ScrollView } from 'react-native-gesture-handler'; import firebase from 'firebase'; import firebaseConfig from '../config/firebaseConfig' import { connect } from 'react-redux' //Firebase initialzation firebaseConfig export class ForgotPassword extends Component { state = { email:null, emailValid:false, } sendResetEmail = () => { // Steps: Send reset email if (this.state.emailValid) { // ERROR IN DOCUMENTATION: THIS METHOD IS SUPPOSED TO SEND A RESET CODE TO THE PROVIDED EMAIL, // BUT INSTEAD SENDS A LINK FROM WHICH THE USER CAN CHANGE THEIR PASSWORD... WORKS BUT NOT AS EXPECTED. firebase.auth().sendPasswordResetEmail(this.state.email) .then(() => { Alert.alert("A link to reset your password was sent to the email you provided.") this.props.navigation.navigate("Login") }) .catch((error) => { console.log(error) Alert.alert(error.message) }) } } updateEmail = (text) => { if (text.length >= 8) { this.setState({email:text, emailValid:true}) } else { this.setState({email:text, emailValid:false}) } } render() { return ( <ScrollView contentContainerStyle={{flexGrow: 1}} keyboardShouldPersistTaps='handled'> <KeyboardAvoidingView style={{flex:1, marginHorizontal:20}} behavior='padding'> {/*SIMPLY RUN*/} <View style={{flex:1, justifyContent:'center', alignItems:'center'}}> <Text style={styles.titleText}>Simply Run</Text> </View> <View style={{flex:2}}> <View style={{justifyContent:'center', alignItems:'center', height:75, paddingHorizontal:20}}> <Text style={{fontSize:18, textAlign:'center'}}>Enter the email you use for your Simply Run account.</Text> </View> {/*TextInput for email address OR reset code*/} <TextInput placeholder="Email" value={this.state.email} onChangeText={(text) => this.updateEmail(text.trim())} autoCapitalize='none' returnKeyType={"done"} keyboardType='email-address' style={styles.textInput} /> {/*Button entering for sending OR verifying the reset code */} <TouchableOpacity onPress={() => this.sendResetEmail()} disabled={(this.state.emailValid ? false : true)}> <View style={{ height:50, backgroundColor: (this.state.emailValid ? "lightblue" : "lightgray"), justifyContent:'center', alignItems:'center', paddingHorizontal:15}}> <Text style={{fontSize:20,color:'black'}}>Send Reset Email</Text> </View> </TouchableOpacity> </View> </KeyboardAvoidingView> </ScrollView> ); } } export default connect()(ForgotPassword) const styles = StyleSheet.create({ textInput: { borderWidth: 1, borderColor: 'lightgrey', height:50, maxHeight:50, justifyContent:'center', padding:8, }, titleText: { fontSize:40, fontWeight:'bold', fontStyle:'italic', } });<file_sep>/src/actions/EndRunAction.js export const END_RUN = "END_RUN" <file_sep>/src/constants/Date.js const yearRange = () => { let startYear = 1950 let endYear = new Date().getFullYear() - 10 let years = [] for (let i = endYear; i >= startYear; i--) { years.push({label:String(i),value:String(i)}) } return years } const monthRange = () => { let startMonth = 1 let endMonth = 31 let months = [] for (let i = startMonth; i <= endMonth; i++) { months.push({label:String(i),value:String(i)}) } return months } export const months = [ {label:'January',value:'January'}, {label:'February',value:'February'}, {label:'March',value:'March'}, {label:'April',value:'April'}, {label:'May',value:'May'}, {label:'June',value:'June'}, {label:'July',value:'July'}, {label:'August',value:'August'}, {label:'September',value:'September'}, {label:'October',value:'October'}, {label:'November',value:'November'}, {label:'December',value:'December'} ] export const days = monthRange() export const years = yearRange()<file_sep>/src/screens/RunLog.js import React, {Component} from 'react'; import { Modal, Text, TouchableOpacity, View, StyleSheet, TouchableHighlight, Alert, } from 'react-native'; import {ScrollView} from 'react-native-gesture-handler'; import {Table, TableWrapper, Row, Cell} from 'react-native-table-component'; import {connect} from 'react-redux'; import firebaseConfig from '../config/firebaseConfig'; import firebase from 'firebase'; import firestore from '@react-native-firebase/firestore'; import MapView, {Polyline} from 'react-native-maps'; import {deleteRunAction} from '../actions/RunLogAction'; export class RunLog extends Component { state = { tableHead: ['Date', 'Distance', 'Time', 'Pace'], tableData: [], modalVisible: false, modalData: [], date: null, route: [], lat: 0, long: 0, jan: 2, cok: 2, selectedRun: null, ascendingSort: true, }; //takes seconds and converts to HH:MM:SS format formatTime(time) { var hours = Math.trunc(time / 3600); time %= 3600; var minutes = Math.trunc(time / 60); var seconds = (time % 60).toFixed(); if (hours < 10) hours = '0' + hours; if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return hours + ':' + minutes + ':' + seconds; } //takes pace and converts to MM:SS format formatPace(time) { var seconds = Math.trunc((time * 60) % 60); var minutes = Math.trunc(time); if (seconds < 10) seconds = '0' + seconds; return minutes + ':' + seconds; } //takes date object and formats to MM/DD/YYYY formatDate(dateString) { const date = new Date(dateString); const year = date.getFullYear().toString(); const day = date.getDate().toString(); return date.getMonth() + 1 + '/' + day + '/' + year; } formatStats(rowData) { var formattedData = []; for (var i = 0; i < 4; i++) { switch (i) { case 0: formattedData.push(this.formatDate(new Date(rowData[0]).toString())); break; case 1: formattedData.push( this.props.metric ? (rowData[1] * 1.609).toFixed(2) + ' km' : rowData[1].toFixed(2) + ' mi', ); break; case 2: formattedData.push(this.formatTime(rowData[2])); break; case 3: formattedData.push( this.props.metric ? this.formatPace((rowData[3] * 0.621).toFixed(2)) + ' min/km' : this.formatPace(rowData[3]) + ' min/mi', ); break; } } return formattedData; } //sorts data in table based on column selected sortTable(field, ascending) { const sortedTableData = this.state.tableData.sort(function (a, b) { if (a[field] === b[field]) { return 0; } else if (ascending) { return a[field] < b[field] ? -1 : 1; } else return a[field] > b[field] ? -1 : 1; }); this.setState({ tableData: sortedTableData, ascendingSort: !this.state.ascendingSort, }); } async componentDidMount() { const tableData = []; this.props.runs.forEach(run => { const rowData = []; rowData.push(Date.parse(run.start_time)); rowData.push(run.distance); rowData.push(run.time); rowData.push(run.pace); rowData.push(run.id); tableData.push(rowData); }); await this.setState({ tableData: tableData, }); //sort by date by default this.sortTable(0, false); } async componentDidUpdate(prevProps, prevState) { //if amount of runs has changed after delete/add, update table if (prevProps.runs.length !== this.props.runs.length) { const tableData = []; this.props.runs.forEach(run => { const rowData = []; rowData.push(Date.parse(run.start_time)); rowData.push(run.distance); rowData.push(run.time); rowData.push(run.pace); rowData.push(run.id); tableData.push(rowData); }); this.state.tableData = tableData; //sort by date by default this.sortTable(0, true); } } //fetches run details and displays modal async setModalVisible(visible, id) { // console.log("row Id =>> "+id); this.RunDetails(id); this.setState({modalVisible: visible}); } ConfirmDeleteRun() { Alert.alert( 'Delete Run', 'Would you like to delete this run?', [ { text: 'No', style: 'cancel', }, { text: 'Yes', onPress: () => { firebaseConfig .firestore() .collection('users') .doc(firebaseConfig.auth().currentUser.uid) .collection('RunLog') .doc(this.state.selectedRun.id) .delete(); this.props.dispatch(deleteRunAction(this.state.selectedRun.id)); alert('Run deleted'); this.componentDidMount(); this.setState({modalVisible: !this.state.modalVisible}); }, }, ], {cancelable: false}, ); } //gets info for selected run RunDetails(id) { // console.log("Run Log details ==> " +id); // console.log("Run Log details ==> " + JSON.stringify(this.props.runs)); // let latid = 0; // let longi = 0; // let user = firebase.auth().currentUser; // let userRef = firestore().collection('users').doc(user.uid); // userRef // .collection('RunLog') // .doc(id) // .get() // .then(querySnapshot => { // this.props.runs[0].lat = querySnapshot.data().route[0].wc // // this.setState({ // // lat: querySnapshot.data().route[0].wc, // // long: querySnapshot.data().route[0].Rc, // // }); // }).catch(error => { // console.log('Login: Error fetching run data:', error.message); // Alert.alert(error.message); // }); this.props.runs.forEach(run => { if (run.id === id) { this.setState({selectedRun: run}, () => { if (this.state.selectedRun === null) { Alert.alert('Unable to load run details.'); return; } const modalData = []; modalData.push( 'Time: ' + this.formatTime(this.state.selectedRun.time) + '\n', ); modalData.push( 'Distance: ' + (this.props.metric ? (this.state.selectedRun.distance * 1.609).toFixed(2) + ' km\n' : this.state.selectedRun.distance.toFixed(2) + ' miles\n'), ); modalData.push( 'Pace: ' + (this.props.metric ? this.formatPace(this.state.selectedRun.pace * 0.621) + ' min/km\n' : this.formatPace(this.state.selectedRun.pace) + ' min/mi\n'), ); modalData.push( 'Calories: ' + this.state.selectedRun.calories.toFixed() + '\n', ); modalData.push('Notes: ' + this.state.selectedRun.note + '\n'); const date = this.formatDate(this.state.selectedRun.start_time); const lat = this.state.selectedRun.lat; const long = this.state.selectedRun.long; const route = this.state.selectedRun.route; // console.log('this is our lat in RunLog ' + JSON.stringify(route)); this.setState({ modalData: modalData, date: date, route: route, lat: lat, long: long }); // console.log("this is our state >>>> " + JSON.stringify(this.state.route)); // console.log( // 'this is our state in RunLog ' + JSON.stringify(this.state), // ); // console.log('this is our route in RunLog ' + JSON.stringify(this.state.selectedRun.route)); }); } }); // console.log("props runsss.... "+ JSON.stringify(this.props.runs[0])) } // koordinat() { // let user = firebase.auth().currentUser; // let userRef = firestore().collection('users').doc(user.uid); // userRef // .collection('RunLog') // .get() // .then(querySnapshot => { // querySnapshot.forEach(doc => { // const run = { // route: doc.get('route'), // }; // }); // }) // .catch(error => { // console.log('Login: Error fetching run data:', error.message); // Alert.alert(error.message); // }); // } render() { // console.log('before maps render ' + JSON.stringify(this.state.route)); return ( <ScrollView> <View> <Text style={styles.title}> Run Log </Text> <Text style={styles.totals}> {' '} Total Time: {this.formatTime(this.props.total_time)}{' '} </Text> <Text style={styles.totals}> {' '} Total Distance:{' '} {this.props.total_distance > 0 ? this.props.metric ? (this.props.total_distance * 1.609).toFixed(2) + ' km' : this.props.total_distance.toFixed(2) + ' miles' : '0.00' + (this.props.metric ? ' km' : ' miles')} </Text> <Text style={styles.totals}> {' '} Average Pace:{' '} {this.props.total_distance > 0 ? this.props.metric ? this.formatPace( this.props.total_time / 60 / (this.props.total_distance * 1.609), ) + ' min/km' : this.formatPace( this.props.total_time / 60 / this.props.total_distance, ) + ' min/mi' : '0:00' + (this.props.metric ? ' min/km' : ' min/mi')} </Text> <Text style={styles.totals}> {' '} Total Calories:{' '} {this.props.total_calories ? this.props.total_calories.toFixed() : '0'}{' '} </Text> <Table borderStyle={{borderWidth: 0}}> <TableWrapper style={styles.head}> {this.state.tableHead.map((title, index) => ( <Cell key={index} data={title} style={styles.head} textStyle={styles.tableTitles} onPress={() => this.sortTable(index, this.state.ascendingSort) } /> ))} </TableWrapper> {this.state.tableData.map((rowData, index) => ( <TouchableHighlight key={index} underlayColor="#AAAAAA" style={[index % 2 && {backgroundColor: '#DDDDDD'}]} onPress={() => // console.log("data on click => " + rowData[rowData.length - 1]) this.setModalVisible( !this.state.modalVisible, rowData[rowData.length - 1], ) }> <Row data={this.formatStats(rowData.slice(0, rowData.length - 1))} style={styles.table} textStyle={styles.text} /> </TouchableHighlight> ))} </Table> <Modal animationType="slide" transparent={false} visible={this.state.modalVisible}> <View style={{marginTop: 22}}> <View> <View style={{flexDirection: 'row'}}> <TouchableHighlight underlayColor="#AAAAAA" style={styles.backbutton} onPress={() => { this.setState({ modalVisible: !this.state.modalVisible, }); }}> <Text style={styles.buttonText}>Back</Text> </TouchableHighlight> {/* <TouchableHighlight underlayColor="#AAAAAA" style={styles.deletebutton} onPress={() => { this.ConfirmDeleteRun(); }}> <Text style={styles.buttonText}>Delete</Text> </TouchableHighlight> */} </View> <Text style={styles.title}>Run Details</Text> <MapView style={styles.map} region={{ latitude: this.state.lat, longitude: this.state.long, latitudeDelta: 0.0102, longitudeDelta: 0.0101, }}> <Polyline coordinates={ this.state.route.length > 0 ? this.state.route : [] } strokeColor="#000" strokeColors={[ '#7F0000', '#00000000', '#B24112', '#E5845C', '#238C23', '#7F0000', ]} strokeWidth={6} /> </MapView> <Text style={styles.date}>{this.state.date}</Text> <Text style={styles.totals}>{this.state.modalData}</Text> </View> </View> </Modal> </View> </ScrollView> ); } } const mapStateToProps = state => { return { user: state.user, metric: state.SettingsReducer.metric, runs: state.RunLogReducer.runs, total_time: state.RunLogReducer.total_time, total_distance: state.RunLogReducer.total_distance, total_calories: state.RunLogReducer.total_calories, }; }; //Connecting the react components to the store in App.js export default connect(mapStateToProps)(RunLog); const styles = StyleSheet.create({ container: {flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff'}, head: {height: 40, flex: 1, flexDirection: 'row', backgroundColor: '#A44CA0'}, table: {height: 40}, text: {margin: 6}, title: { fontSize: 26, textAlign: 'center', padding: 5, }, totals: { textAlign: 'center', fontSize: 16, padding: 2, }, date: { fontSize: 20, textAlign: 'center', padding: 5, }, tableTitles: { textAlign: 'center', padding: 2, fontSize: 18, }, text: { textAlign: 'center', padding: 2, }, button: { marginLeft: 120, marginRight: 120, marginTop: 10, paddingTop: 10, paddingBottom: 10, backgroundColor: '#BBBBBB', borderRadius: 10, borderWidth: 1, borderColor: '#fff', }, backbutton: { marginLeft: 15, marginTop: 10, paddingTop: 10, paddingBottom: 10, backgroundColor: '#BBBBBB', borderRadius: 5, borderWidth: 1, borderColor: '#fff', }, deletebutton: { marginRight: 15, marginLeft: 200, marginTop: 10, paddingTop: 10, paddingBottom: 10, backgroundColor: '#c5050c', borderRadius: 5, borderWidth: 1, borderColor: '#fff', }, buttonText: { color: '#fff', textAlign: 'center', paddingLeft: 25, paddingRight: 25, }, map: { position: 'relative', alignItems: 'center', height: 300, }, });
0fbe2461433baeeb9f4f8c19d1b39cead2ab78d7
[ "JavaScript", "Markdown" ]
24
JavaScript
fariqM/RunAway-mobile
cdc3c0f17bd3a1a9cc34e9f179f1c44728b56a80
9b0ebbed5b2136839e79948d5316f380ca6ad2c5
refs/heads/master
<file_sep>const assert = require('assert'); const Park = require('../models/park.js'); const Dinosaur = require('../models/dinosaur.js'); describe('Park', function() { let park; let dinosaur1; let dinosaur2; let dinosaur3; let dinosaur4; let dinosaur5; let dinosaur6; let dinosaurs; beforeEach(function () { dinosaur1 = new Dinosaur('t-rex', 'carnivore', 50); dinosaur2 = new Dinosaur('velociraptor', 'carnivore', 35); dinosaur3 = new Dinosaur('Dilophosaurus', 'carnivore', 15); dinosaur4 = new Dinosaur('triceratops', 'herbivore', 12); dinosaur5 = new Dinosaur('brachiosaurus', 'herbivore', 37); dinosaur6 = new Dinosaur('parasaurolophus', 'herbivore', 19); dinosaurs = [dinosaur1, dinosaur2, dinosaur3, dinosaur4]; park = new Park('Jurassic Park', 200, dinosaurs); }); it('should have a name', function(){ const actual = park.name; assert.strictEqual(actual, 'Jurassic Park'); }); it('should have a ticket price', function(){ const actual = park.ticketPrice; assert.strictEqual(actual, 200); }); it('should have a collection of dinosaurs', function(){ const actual = park.dinosaurs; assert.deepStrictEqual(actual, [dinosaur1, dinosaur2, dinosaur3, dinosaur4]) }); it('should be able to add a dinosaur to its collection', function(){ park.addDinosaurToPark(dinosaur5); const actual = park.dinosaurs; assert.deepStrictEqual(actual, [dinosaur1, dinosaur2, dinosaur3, dinosaur4, dinosaur5]); }); it('should be able to remove a dinosaur from its collection', function(){ park.removeDinosaurFromPark(dinosaur3); const actual = park.dinosaurs; assert.deepStrictEqual(actual, [dinosaur1, dinosaur2, dinosaur4]); }); it('should be able to find the dinosaur that attracts the most visitors', function(){ const actual = park.findMostPopularDinosaur(); assert.deepStrictEqual(actual, dinosaur1); }); it('should be able to find all dinosaurs of a particular species', function(){ const actual = park.findBySpecies('t-rex'); assert.deepStrictEqual(actual, [dinosaur1]); }); it('should be able to remove all dinosaurs of a particular species', function(){ const actual = park.removeDinosaursBySpecies('triceratops'); assert.deepStrictEqual(actual, [dinosaur1, dinosaur2, dinosaur3]); }); });
d93ef9f9e3f5304dd4883800d09a309dcc15057e
[ "JavaScript" ]
1
JavaScript
Rob-Marshall87/wk6_day2_homework
6eb0c126b2d168f4eaf4bfab43b4d6f556065e9e
df42740ea311ad83c7bd708f7d27590cdb58565c
refs/heads/master
<repo_name>nna774/scrapdown<file_sep>/app/controllers/wikis_controller.rb class WikisController < ApplicationController def index @wikis = Wiki.all.order(updated_at: :desc) end def new @name = Name.new(name: params[:name]) @page = Page.new(content: params[:content]) end def create pagename = wiki_params[:name][:name] content = wiki_params[:page][:content] if pagename.blank? # 適切なメッセージを出す方が良い(ブラウザのvalidation通ってるハズなので要らない?)。 render :new return end @name = Name.find_by(name: pagename) if @name # 既に同名のページが存在 # 名前がかぶっているというメッセージを出す。 redirect_to action: :new, name: pagename, content: content, status: 302 return end @wiki = Wiki.create @name = Name.create(name: pagename, wiki_id: @wiki.id) @page = Page.create(content: content, wiki_id: @wiki.id) # つながっているnameの抽出等をここでする。 redirect_to action: :show, name: pagename, status: 302 end def show @name = Name.find_by(name: params[:name]) if @name # そのタイトルのページ発見。 @wiki = @name.wiki if @wiki.nil? # 変更前のページタイトルなのでリダイレクトする。 render text: CGI.escapeHTML(@name.inspect) return end @page = @wiki.page render :wiki else # なかったので新規画面を出しとく。 @name = Name.new(name: params[:name]) @page = Page.new(content: params[:content]) render :new end end def edit @name = Name.find_by(name: params[:name]) @wiki = @name.wiki @page = @wiki.page render :edit end def update @name = Name.find(params.dig(:wiki, :name, :id)) @wiki = @name.wiki if @wiki.nil? # end @page = @wiki.page if params.dig(:wiki, :page, :id).to_i != @page.id puts "here!!" binding.pry # コンフリクト発生 end if (newname = params.dig(:wiki, :name, :name)) != @name.name && !newname.nil? # ページタイトル変更発生! oldname = @name.name @name.name = newname @name.save @name.reload Name.create!(name: oldname, changed_to: @name.id) # 古い名前のリダイレクト用エントリの作成 @wiki.touch @wiki.save end newcontent = params.dig(:wiki, :page, :content) if newcontent == @page.content # 変更無し redirect_to action: :show, name: @name.name, status: 302 return end newpage = Page.create(wiki_id: @wiki.id, content: newcontent) @wiki.page = newpage @wiki.save redirect_to action: :show, name: @name.name, status: 302 end private def wiki_params params.require(:wiki).permit(name: [:name], page: [:content]) end end <file_sep>/db/migrate/20170507082017_add_parent_to_pages.rb class AddParentToPages < ActiveRecord::Migration[5.0] def change add_column :pages, :parent, :integer end end <file_sep>/app/models/page_name.rb class PageName < ApplicationRecord belongs_to :page belongs_to :name end <file_sep>/app/models/wiki.rb class Wiki < ApplicationRecord has_one :name has_one :page def to_param name.name end end <file_sep>/app/models/page.rb class Page < ApplicationRecord has_many :page_name has_many :name, through: :page_name belongs_to :wiki, optional: true end <file_sep>/db/migrate/20170429145542_create_page_names.rb class CreatePageNames < ActiveRecord::Migration[5.0] def change create_table :page_names do |t| t.integer :page_id t.integer :name_id t.timestamps t.index [:page_id, :name_id], :unique => true end end end <file_sep>/app/models/name.rb class Name < ApplicationRecord has_many :page_name has_many :page, through: :page_name has_many :name_name, foreign_key: :parent_id has_one :name_name, foreign_key: :child_id has_many :children, through: :name_name, source: :child has_one :parent, through: :name_name, source: :parent belongs_to :wiki, optional: true end <file_sep>/app/models/name_name.rb class NameName < ApplicationRecord belongs_to :child, class_name: :Name belongs_to :parent, class_name: :Name end <file_sep>/db/migrate/20170429145221_create_names.rb class CreateNames < ActiveRecord::Migration[5.0] def change create_table :names do |t| t.string :name t.integer :wiki_id t.integer :changed_to t.timestamps t.index :name, :unique => true end end end
bd6e3222ecaa2a7f157af6473d324a94d3736b82
[ "Ruby" ]
9
Ruby
nna774/scrapdown
819746bd5c155fa38e681a0bf05a250781157517
aab97d28f96fb4cce65b97577094997ee1a03742
refs/heads/master
<file_sep># Machine-Learning-Enron-Data <file_sep>#!/usr/bin/python import sys import pickle import numpy as np import matplotlib.pyplot as plt sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit from tester import test_classifier, dump_classifier_and_data ### Task 1: Select what features you'll use. ### features_list is a list of strings, each of which is a feature name. features_list = ['poi', 'bonus', 'total_stock_value', 'exercised_stock_options'] ### Load the dictionary containing the dataset data_dict = pickle.load(open("final_project_dataset.pkl", "r") ) ### Task 2: Remove outliers - DONE ### Task 3: Create new feature(s) - DONE ### Store to my_dataset for easy export below. - DONE my_dataset = data_dict my_dataset.pop("TOTAL", 0) #removing outlier count = 0 count_poi = 0 count_notpoi = 0 #creating new features, percentage of emails to/from POI, Sum of emails to and from POI for i in my_dataset: if my_dataset[i]['from_messages'] == 'NaN' or my_dataset[i]['to_messages'] == "NaN": my_dataset[i]['POI_message_share'] = 0 else: my_dataset[i]['POI_message_share'] = (float(my_dataset[i]['from_poi_to_this_person']) + float(my_dataset[i]['from_poi_to_this_person'])) / (float(my_dataset[i]['from_this_person_to_poi']) + float(my_dataset[i]['to_messages'])) if my_dataset[i]['from_this_person_to_poi'] == "NaN" or my_dataset[i]['from_poi_to_this_person'] == "NaN": my_dataset[i]['sum_from_to_poi'] = 0 else: my_dataset[i]['sum_from_to_poi'] = float(my_dataset[i]['from_this_person_to_poi']) + float(my_dataset[i]['from_poi_to_this_person']) #counting size of dataset and number of POIs if my_dataset[i]['poi'] == 1: count_poi += 1 else: count_notpoi += 1 ### Extract features and labels from dataset for local testing data = featureFormat(my_dataset, features_list, sort_keys = True) labels, features = targetFeatureSplit(data) ### Task 4: Try a variety of classifiers ### Note that if you want to do PCA or other multi-stage operations, ### you'll need to use Pipelines. For more info: ### http://scikit-learn.org/stable/modules/pipeline.html ###testing Naive Bayes #from sklearn.naive_bayes import GaussianNB #clf = GaussianNB() from sklearn import tree, grid_search, cross_validation #GridSearchCV parameters testing ''' parameters = {'criterion':('gini', 'entropy'), 'splitter': ('best', 'random'), 'max_features':('auto', 'log2'), 'min_samples_split':[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]} dtc = tree.DecisionTreeClassifier() clf2 = grid_search.GridSearchCV(dtc, parameters) clf2.fit(features, labels) print'best parameters:', clf2.best_estimator_ ''' ### Task 5: Tune your classifier to achieve better than .3 precision and recall ### Because of the small size of the dataset, the script uses stratified ### shuffle split cross validation. For more info: ### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html #Cross Validation train-test split features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(features, labels, test_size=0.3, random_state=42) clf = tree.DecisionTreeClassifier(criterion = "entropy", max_features = 'log2', min_samples_split = 2) clf.fit(features_train, labels_train) pred = clf.predict(features_test) print clf.score(features_test, labels_test) print clf.feature_importances_ test_classifier(clf, my_dataset, features_list) ### Dump your classifier, dataset, and features_list so ### anyone can run/check your results. dump_classifier_and_data(clf, my_dataset, features_list)
3ebbaa5d3fed35b1bd4a03391ad54aaa1a14c8a2
[ "Markdown", "Python" ]
2
Markdown
zhibindai26/Machine-Learning-Enron-Data
229806ab8c9c29e0edc8cc1811cceba986125559
e402ba830984772dcd8b98f639f5d078e7c30eab
refs/heads/develop
<repo_name>emilyzeng1977/ag-grid-example<file_sep>/cellRendererFrameworkExample/src/app/app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {AgGridModule} from 'ag-grid-angular'; import {DemoAgRendererComponentComponent} from './demo-ag-renderer-component/demo-ag-renderer-component.component'; import {DatePipe, DecimalPipe} from "@angular/common"; @NgModule({ declarations: [ AppComponent, DemoAgRendererComponentComponent ], imports: [ BrowserModule, AgGridModule.withComponents([ DemoAgRendererComponentComponent ] ) ], providers: [ DatePipe, DecimalPipe ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/cellRendererFrameworkExample/src/app/demo-ag-renderer-component/demo-ag-renderer-component.component.ts import { Component } from '@angular/core'; import { AgRendererComponent } from 'ag-grid-angular'; import { ICellRendererParams } from 'ag-grid-community'; @Component({ selector: 'app-demo-ag-renderer-component', templateUrl: './demo-ag-renderer-component.component.html', styleUrls: ['./demo-ag-renderer-component.component.scss'] }) export class DemoAgRendererComponentComponent implements AgRendererComponent { params: any; constructor() { } agInit(params: ICellRendererParams): void { this.params = params; } refresh(params: any): boolean { return false; } } <file_sep>/cellRendererFrameworkExample/src/app/app.component.ts import { Component } from '@angular/core'; import { DatePipe, DecimalPipe } from "@angular/common"; import {DemoAgRendererComponentComponent} from "./demo-ag-renderer-component/demo-ag-renderer-component.component"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor(private dateFormatter: DatePipe, private numberFormatter: DecimalPipe) {} title = 'my-app'; columnDefs = [ {headerName: 'Make', field: 'make'}, { headerName: 'Model', field: 'model', cellRenderer: (params) => { return "TEST"; } }, { headerName: 'Price', field: 'price', cellRendererFramework: DemoAgRendererComponentComponent }, { headerName: 'Date', field: 'date', valueFormatter: (data) => this.dateFormatter.transform(data.value, 'shortDate') } ]; rowData = [ { make: 'Toyota', model: 'Celica', price: 35000, date: '2018-01-04'}, { make: 'Ford', model: 'Mondeo', price: 32000, date: '2019-06-14' }, { make: 'Porsche', model: 'Boxter', price: 72000, date: '2019-06-12' } ] }
472ec7fdd4e45a0eca93506dd0386aff33dce778
[ "TypeScript" ]
3
TypeScript
emilyzeng1977/ag-grid-example
14808bfe58321f35a5fccb76beb35e636fd26ae4
7d7da0c29c85919f0125955301e65973b1f98141
refs/heads/master
<file_sep> # *A TIC TAC TOE GAME* A Tic Tac Toe game, where the AI is as smart as human. #For Each move human has got 7 seconds #System also suggests a good move for human ### Prerequisites * Node.js insalled [DOWNLOAD AT] https://nodejs.org/en/ ## Built With * JavaScript(Node.js, ES6 Modules) * HTML5 * CSS ## Authors *<NAME> - [EVERNOX696](https://github.com/EVERNOX696) ## Acknowledgments * To understand the working of minimax alogrithm :https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-3-tic-tac-toe-ai-finding-optimal-move/?ref=rp * Inspiration: https://github.com/alialaa/js-tic-tac-toe * Inspiration:https://github.com/beaucarnes/fcc-project-tutorials <file_sep>import board from './board.mjs' import Players from './players.mjs' var initial_board; var human; var ai; var rdepth; var maxdepth =-1; var human_choice; const winCombos = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [6, 4, 2] ] //event handler cells const cells = document.querySelectorAll('.cell'); //call start game startGame(); /////timer const FULL_DASH_ARRAY = 283; const WARNING_THRESHOLD = 10; const ALERT_THRESHOLD = 5; const COLOR_CODES = { info: { color: "green" }, warning: { color: "orange", threshold: WARNING_THRESHOLD }, alert: { color: "red", threshold: ALERT_THRESHOLD } }; const TIME_LIMIT = 7; let timePassed = 0; let timeLeft = TIME_LIMIT; let timerInterval = null; let remainingPathColor = COLOR_CODES.info.color; //event handler :timer document.getElementById("app").innerHTML = ` <div class="base-timer"> <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <g class="base-timer__circle"> <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle> <path id="base-timer-path-remaining" stroke-dasharray="283" class="base-timer__path-remaining ${remainingPathColor}" d=" M 50, 50 m -45, 0 a 45,45 0 1,0 90,0 a 45,45 0 1,0 -90,0 " ></path> </g> </svg> <span id="base-timer-label" class="base-timer__label">${formatTime( timeLeft )}</span> </div> `; function time_up(){ document.getElementById("s_move").style.display="none"; for (var i = 0; i < cells.length; i++) { cells[i].style.backgroundColor = "green"; cells[i].removeEventListener('click', turnClick, false); } document.querySelector(".endgame").style.display = "block"; document.querySelector(".endgame .text").innerText = "GAME OVER"; } function resetTimer(){ timePassed=0; timeLeft = TIME_LIMIT; timerInterval = null; remainingPathColor = COLOR_CODES.info.color; } function stopTimer() { clearInterval(timerInterval); resetTimer(); document.getElementById("app").style.display="none"; } function onTimesUp() { clearInterval(timerInterval); resetTimer(); time_up(); } function startTimer() { document.getElementById("s_move").style.display = "none"; document.getElementById("app").style.display="block"; timerInterval = setInterval(() => { timePassed = timePassed += 1; timeLeft = TIME_LIMIT - timePassed; if (timeLeft <= 0) { onTimesUp(); } document.getElementById("base-timer-label").innerHTML = formatTime( timeLeft ); setCircleDasharray(); setRemainingPathColor(timeLeft); }, 1000); } //second conversion function formatTime(time) { const minutes = Math.floor(time / 60); let seconds = time % 60; if (seconds < 10) { seconds = `0${seconds}`; } return `${minutes}:${seconds}`; } // function setRemainingPathColor(timeLeft) { const { alert, warning, info } = COLOR_CODES; if (timeLeft <= alert.threshold) { document .getElementById("base-timer-path-remaining") .classList.remove(warning.color); document .getElementById("base-timer-path-remaining") .classList.add(alert.color); } else if (timeLeft <= warning.threshold) { document .getElementById("base-timer-path-remaining") .classList.remove(info.color); document .getElementById("base-timer-path-remaining") .classList.add(warning.color); } } function calculateTimeFraction() { const rawTimeFraction = timeLeft / TIME_LIMIT; return rawTimeFraction - (1 / TIME_LIMIT) * (1 - rawTimeFraction); } function setCircleDasharray() { const circleDasharray = `${( calculateTimeFraction() * FULL_DASH_ARRAY ).toFixed(0)} 283`; document .getElementById("base-timer-path-remaining") .setAttribute("stroke-dasharray", circleDasharray); } //MAIN FUNCtion of the game function startGame() { document.getElementById("s_move").style.display="none"; document.querySelector('.endgame').style.display = "none"; document.querySelector('.endgame .text').innerText =""; document.querySelector('.selectSym').style.display = "block"; for (let i = 0; i < cells.length; i++) { cells[i].innerText = ''; cells[i].style.removeProperty('background-color'); } } function gameOver(gameWon) { document.getElementById("s_move").style.display="none"; clearInterval(timerInterval); resetTimer(); for (let index of winCombos[gameWon.index]) { document.getElementById(index).style.backgroundColor = gameWon.player == human.svar? "blue" : "red"; } for (var i = 0; i < cells.length; i++) { cells[i].removeEventListener('click', turnClick, false); } declareWinner(gameWon.player == human.svar ? "You win!" : "You lose."); } //if user selects O function symo(){ human=new Players('O'); ai=new Players('X'); let origBoard = Array.from(Array(9).keys()); initial_board=new board(origBoard); for (let i = 0; i < cells.length; i++) { cells[i].addEventListener('click', turnClick, false); } document.querySelector('.selectSym').style.display = "none"; } //button event handler document.getElementById("so").addEventListener('click', symo); //if user selects X function symx(){ human=new Players('X'); ai=new Players('O'); let origBoard = Array.from(Array(9).keys()); initial_board=new board(origBoard); for (let i = 0; i < cells.length; i++) { cells[i].addEventListener('click', turnClick, false); } document.querySelector('.selectSym').style.display = "none"; } //button event handler document.getElementById("sx").addEventListener('click', symx); //replay button event handler document.getElementById("Replay").addEventListener('click', startGame); function turnClick(square) { document.getElementById("s_move").style.display="none"; if (typeof initial_board.state[square.target.id] == 'number') { stopTimer(); //document.getElementById("s_move").style.display = "none"; turn(square.target.id, human.svar); if (!initial_board.checkWin(human.svar) &&!checkTie(initial_board)) { turn(bestSpot(ai.svar), ai.svar); document.getElementById("s_move").style.display = "block"; document.getElementById("s_move").innerHTML=`<p class="pc" id="oho" >Hooman you better move to <span id="suggest_move_label" class="suggest-move_lable" style="color:blue"> ${human_choice}</span> block if you wanna win </p> `; human_choice=bestSpot(human.svar); human_choice=human_choice+1; document.getElementById("suggest_move_label").innerHTML =human_choice; //sugest move } } } //to call the minimax function bestSpot(player) { if (player==ai.svar) { return minimax(initial_board,ai.svar).index; } else if (player==human.svar){ return minimax(initial_board, human.svar).index; } } //MINIMAX WITH ALPHA BETHA PRUNING function minimax(initial_board, player,depth=0) { var availSpots = initial_board.emptySquares(); if (initial_board.checkWin( human.svar)||depth==rdepth) { return {score: -10}; } else if (initial_board.checkWin( ai.svar) || depth==rdepth) { return {score: 10}; } else if (availSpots.length === 0 ) { return {score: 0}; } var moves = []; for (var i = 0; i < availSpots.length; i++) { var move = {}; move.index = initial_board.state[availSpots[i]]; initial_board.state[availSpots[i]] = player; if (player == ai.svar) { var result = minimax(initial_board, human.svar,depth+1); move.score = result.score; } else { var result = minimax(initial_board, ai.svar,depth+1); move.score = result.score; } initial_board.state[availSpots[i]] = move.index; moves.push(move); } var bestMove; if(player === ai.svar) { var bestScore = -Infinity; for(var i = 0; i < moves.length; i++) { if (moves[i].score > bestScore) { bestScore = moves[i].score; bestMove = i; } } } else { var bestScore = Infinity; for(var i = 0; i < moves.length; i++) { if (moves[i].score < bestScore) { bestScore = moves[i].score; bestMove = i; } } } return moves[bestMove]; } function turn(squareId, player) { initial_board.state[squareId] = player; document.getElementById(squareId).innerText = player; let gameWon =initial_board.checkWin(player); //comment if (gameWon) {document.getElementById("s_move").style.display="none"; gameOver(gameWon)} else if(player==ai.svar){ startTimer(); } else if (player==human.svar){ stopTimer(); } } function declareWinner(who) { document.getElementById("s_move").style.display="none"; document.querySelector(".endgame").style.display = "block"; document.querySelector(".endgame .text").innerText = who; } function checkTie(board) { if (board.emptySquares().length == 0) { document.getElementById("s_move").style.display="none"; clearInterval(timerInterval); resetTimer(); for (var i = 0; i < cells.length; i++) { cells[i].style.backgroundColor = "green"; cells[i].removeEventListener('click', turnClick, false); } declareWinner("Tie Game!"); return true; } return false; }
d84296c751f84aa48ac03e29638045350d307f52
[ "Markdown", "JavaScript" ]
2
Markdown
EVERNOX696/tic-tac-toe-ai
922de03e7ba8532648b7fe7a95a1113ba139f7ce
000c53b01d712cee9cafc44802c7620ea455cdc8
refs/heads/master
<file_sep>// add this file to .gitignore module.exports = { google: { clientID: '1067071802055-6outk3kaudr8ncshj0bkmu3ho9u7kivd.apps.googleusercontent.com', clientSecret: '<KEY>' } }; <file_sep>var bodyparser = require('body-parser'); var urlencodedparser = bodyparser.urlencoded({extended:false}); module.exports = function(app){ app.get('/search',function(req,res){ res.render('search',{search:data}); }); app.get('/search',function(req,res){ res.render('search',{search:data}); }); app.post('/homeAdmin', urlencodedparser , function(req,res){ res.render('search',{search:data}); });
7e6734be4878a10a0cb3b0428854bf739b5b414f
[ "JavaScript" ]
2
JavaScript
ahmedaof/grad
bc27e1cbacd345ef0f17215692b1566863da07b9
7d76baeeb9982d729a0d1ff673a7c760a4a0c8ed
refs/heads/main
<repo_name>Sameer411/Weather-Web-Project<file_sep>/README.md # Weather-Web-Project Web Project where you can Search for Weather of Any State & City of India # Visit Bellow Link to check Project https://city-weather-check.netlify.app/ # Languages Used 1) HTML 2) CSS 3) JavaScript # Platform used for Hosting & Steps to Host Platform: Netlify Steps to Host: 1) Create Accont 2) Link GitHub Repository Want to Host 3) Click on Site Settings and edit Site Name 4) Done (Note: Only Static Websites are Hostable) # Images of Project ![](images/eg2.png) <file_sep>/app.js // api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key} const weatherApi = { key: "bab281d79e5f1e9755a68d754cc313e7", baseUrl: "https://api.openweathermap.org/data/2.5/weather", } const searchInputBox = document.getElementById('input-box'); // Event Listener Function on keypress searchInputBox.addEventListener('keypress', (event) => { if(event.keyCode == 13) { console.log(searchInputBox.value); getWeatherReport(searchInputBox.value); document.querySelector('.weather-body').style.display = "block"; } }); // Get Weather Report function getWeatherReport(city) { fetch(`${weatherApi.baseUrl}?q=${city}&appid=${weatherApi.key}&units=metric`) .then(weather => { return weather.json(); }).then(showWeatherReport); } // Show Weather Report function showWeatherReport(weather){ console.log(weather); let city = document.getElementById('city'); city.innerText = `${weather.name}, ${weather.sys.country}`; let temperature = document.getElementById('temp'); temperature.innerHTML = `${Math.round(weather.main.temp)}&deg;C`; let minMaxTemp = document.getElementById('min-max'); minMaxTemp.innerHTML = `${Math.floor(weather.main.temp_min)}&deg;C (min)/ ${Math.ceil(weather.main.temp_max)}&deg;C (max) `; let weatherType = document.getElementById('weather'); weatherType.innerText = `${weather.weather[0].main}`; let date = document.getElementById('date'); let todayDate = new Date(); date.innerText = dateManage(todayDate); if(weatherType.textContent == 'Clear') { document.body.style.backgroundImage = "url('images/clear.jpg')"; } else if(weatherType.textContent == 'Clouds') { document.body.style.backgroundImage = "url('images/cloud.jpg')"; } else if(weatherType.textContent == 'Haze') { document.body.style.backgroundImage = "url('images/cloud.jpg')"; } else if(weatherType.textContent == 'Rain') { document.body.style.backgroundImage = "url('images/rain.jpg')"; } else if(weatherType.textContent == 'Snow') { document.body.style.backgroundImage = "url('images/snow.jpg')"; } else if(weatherType.textContent == 'Thunderstorm') { document.body.style.backgroundImage = "url('images/thunderstorm.jpg')"; } } // Date manage function dateManage(dateArg) { let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; let year = dateArg.getFullYear(); let month = months[dateArg.getMonth()]; let date = dateArg.getDate(); let day = days[dateArg.getDay()]; return `${date} ${month} (${day}), ${year}`; }
0d754e63811dd41db075968cf0306455a35c300f
[ "Markdown", "JavaScript" ]
2
Markdown
Sameer411/Weather-Web-Project
2cd89f6da462ca29ad04edfcf29fd95a4ac16fed
a1f56e35d20e5160effbe21bfcb233f2f2bc6a27
refs/heads/master
<file_sep># vesna ("Spring" in *Ukrainian*) **Arduino 12 led clock** that shows Hours, Minutes and *Seconds*. Used [this](http://www.instructables.com/id/Arduino-powered-LED-Clock/) _Instructables_ tutorial for schematics and soldering, wrote my own code for _Arduino_ (Uno in this case, but does not matter really). Additionally a [DS1307 I2C RTC](http://www.sainsmart.com/arduino-i2c-rtc-ds1307-at24c32-real-time-clock-module-board-for-avr-arm-pic.html) module is used for precise time. <file_sep>#include <Wire.h> #include "RTClib.h" RTC_DS1307 RTC; void setup() { // put your setup code here, to run once: Serial.begin(9600); for (int i = 2; i < 14; i++) { pinMode(i,OUTPUT); digitalWrite(i, HIGH); } Wire.begin(); RTC.begin(); // If we remove the comment from the following line, we will set up the module time and date with the computer one RTC.adjust(DateTime(__DATE__, __TIME__)); } int hr = 0; void loop() { // put your main code here, to run repeatedly: DateTime now = RTC.now(); int hour = now.hour(); if(now.hour()>12){ hour = now.hour() - 12; } int min = now.minute()/5; int exMin = now.minute()%5; int sec = now.second()/5; int exSec = now.second()%5; int del = 0; bool hrchange = hr != hour; // === Start a hourly animation if there was a change in hours. if(hrchange){ // 5000 ms animation // blink twice for(int i = 0; i<2; i++){ for(int j = 2; j<14; j++){ digitalWrite(j, LOW); } delay(50); for(int j = 2; j<14; j++){ digitalWrite(j, HIGH); } delay(50); } // 200 ms // Circle fill clockwise. for(int i = 2; i<14; i++){ digitalWrite(i, LOW); delay(100); } // 1200 ms // Circle dim clockwise. for(int i = 2; i<14; i++){ digitalWrite(i, HIGH); delay(100); } // 1200 ms // (200+1200+1200 = 2600) if(hour == 0){ for(int i = 2; i<14; i++){ digitalWrite(i, LOW); delay(100);//1200 } // 1200 ms for(int i = 13; i>2; i--){ digitalWrite(i, HIGH); delay(100);//1100 } del = 100; }else{ for(int i = 2; i<=hour+2; i++){ digitalWrite(i, LOW); delay(100); } for(int i = hour+1; i>1; i--){ digitalWrite(i, HIGH); delay(100); } del = 2400-(100*(hour+2))-(100*(hour-1)); } // The end on the hourly animation }else{ for(int i=2; i<14; i++){ if(i!=hour+2 || i!=min+2){ digitalWrite(i, HIGH); } } digitalWrite(hour+2, LOW); digitalWrite(min+2, LOW); // Blinking extra minutes (if any); If, say, the time is 13:27, minutes led will blink 2 times. for(int i = 0; i<exMin; i++){ digitalWrite(min+2, LOW); delay(300); digitalWrite(min+2, HIGH); delay(200); } if (hour == min){ digitalWrite(min+2, LOW); // Keeping hours lit after minutes blinking. } // I played with seconds blinking, and decided to hardcode two quick blinks. for(int i = 0; i<3; i++){ digitalWrite(sec+2, LOW); delay(50); digitalWrite(sec+2, HIGH); delay(50); if(sec == hour){ digitalWrite(sec+2, LOW); // Keep the hour led lit after blinking seconds. } if (sec == min && exMin == 0) { digitalWrite(min+2, LOW); // Keep the minutes led lit after blinking seconds if if is aliquot to 5 (minutes modulo 5 equals 0). } } } // If there was no change in Hours, set the delay between cycles to // 5 seconds minus the time for different animations if(!hrchange){ del = 5000-(500*exMin)-300; } hr = hour; delay(del); }
3517989ea604afb699b7ec36f09cf97a850e9f3e
[ "Markdown", "C++" ]
2
Markdown
NerveClasp/vesna
3525f09ce03cc21ceb015386438a4a97ea3b25b6
9be2dd2613e19b3c0fcaf7ca2d3f622409421d60
refs/heads/master
<repo_name>ShariqAteeq/React-Learning<file_sep>/Next-Gen Javascript/person.js const per = { name:"harry" }; export default per;<file_sep>/redux/containers/Counter/Counter.js import React, { Component } from 'react'; import CounterControl from '../../components/CounterControl/CounterControl'; import CounterOutput from '../../components/CounterOutput/CounterOutput'; import {connect} from 'react-redux'; import * as actionCreators from '../../store/actions/index'; class Counter extends Component { // state = { // counter: 0 // } // counterChangedHandler = ( action, value ) => { // switch ( action ) { // // case 'inc': // // this.setState( ( prevState ) => { return { counter: prevState.counter + 1 } } ) // // break; // case 'dec': // this.setState( ( prevState ) => { return { counter: prevState.counter - 1 } } ) // break; // case 'add': // this.setState( ( prevState ) => { return { counter: prevState.counter + value } } ) // break; // case 'sub': // this.setState( ( prevState ) => { return { counter: prevState.counter - value } } ) // break; // } // } render () { return ( <div> <CounterOutput value={this.props.ctr} /> <CounterControl label="Increment" clicked={this.props.onIncrement} /> <CounterControl label="Decrement" clicked={this.props.onDecrement} /> <CounterControl label="Add 5" clicked={this.props.onAdd5} /> <CounterControl label="Subtract 5" clicked={this.props.onSub5} /> {/* <CounterControl label="Subtract 5" clicked={() => this.counterChangedHandler( 'sub', 5 )} /> this is previous method*/} <hr /> <button onClick = {() => this.props.onStoreResult(this.props.ctr)}>Store Results</button> <ul> {this.props.storedResults.map(str =>( <li key = {str.id} onClick = {() => this.props.onDeleteResult(str.id)} style = {{cursor : 'pointer'}}> {str.value} </li> ))} </ul> </div> ); } } const mapStateToProps = state => { return{ ctr : state.ctr.counter, //this state come from reducer.js storedResults : state.res.results }; }; const mapDispatchToProps = dispatch =>{ return{ onIncrement : () => dispatch(actionCreators.inc()), onDecrement : () => dispatch(actionCreators.dec()), onAdd5 : () => dispatch(actionCreators.add(5)), onSub5 : () => dispatch(actionCreators.sub(5)), onStoreResult : (result) => dispatch(actionCreators.store_result(result)), onDeleteResult : (id) => dispatch(actionCreators.delete_result(id)) }; }; export default connect(mapStateToProps , mapDispatchToProps)(Counter); //connect is used to connect container state wich is counter comp with global state which come from reducer.js // connect is a higherorder function which use in export<file_sep>/react-router/containers/Blog/Blog.js import React, { Component , Suspense } from 'react'; import { Route , NavLink , Switch, Redirect} from 'react-router-dom'; import './Blog.css'; import Posts from '../Blog/Posts/Posts'; //import NewPost from '../Blog/NewPost/NewPost'; import asyncComp from '../../hoc/asyncComponent'; //this is also for lazy routing const asyncPost = asyncComp(cmp=>{ return import('../Blog/NewPost/NewPost'); }); // const Newpos = React.lazy(()=>import('../Blog/NewPost/NewPost')); //this is for lazy routing mean dont fetch unnecessary files class Blog extends Component { state = { auth : true } render () { return ( <div className="Blog"> <header> <nav> <ul> <li><NavLink to= "/posts/" exact activeClassName= "my-active" activeStyle = {{ color:'brown', textDecoration : 'underLine' }} >Posts</NavLink></li> <li><NavLink to = {{ pathname : '/new-post', hash : '#submit', search : '?quick-submit=true' }}>NewPost</NavLink></li> </ul> </nav> </header> {/* <Route path = "/" exact render = {()=> <h3>Home</h3>} /> <Route path = "/" render = {()=> <h3>Home 2</h3>} /> exact basically pora exact path ko check krta he like jese uper hmne new-post ka ak path bnaya hua he agr hm exact use nh krenge tw / path override hjaega new-post wale path me kiuk newpost path me / he */} <Switch> {/* {this.state.auth ? <Route path = "/new-post" render = {() =>(<Suspense fallback = {<div>Loading!!!!</div>}> <Newpos /></Suspense>)} /> : null} */} {this.state.auth ? <Route path = "/new-post" component = {asyncPost} /> : null} <Route path = "/posts" component = {Posts} /> <Route render = {()=> <h1>Not Found</h1>} /> {/* when no route is defined it directly run that route which dont have path */} {/* <Route path = "/" component = {Posts} /> */} {/* same component for different routes */} {/* <Redirect from = "/" to = "/posts" /> */} </Switch> {/* /:myid :- after : we define our own variable which take dynamic parameters from url <Switch> runs only 1 route at at a time */} </div> ); } } export default Blog; /* 'then' method take 1 arguement and it runs when a rsult or response appears absolute path : occurs full path include domain like : abc.com/abc relative path : include only certain path of a respective file like /abc.html <link> tag is basically used as <a> tag but it doesnt include reloading while <a> include reload when clicks <NavLink> is like <link> but it include extra props for styling css */<file_sep>/Basic-to-Components/ValidateComponent/ValidateComponent.js import React from 'react'; const ValidateComponent = (props) =>{ let ValidateMsg = "Text long enough"; if(props.len <=5){ ValidateMsg = "text is short"; } return( <div> <p>Input Text Length is {props.len}</p> {ValidateMsg} </div> ); } export default ValidateComponent;<file_sep>/redux/store/actions/result.js import * as actionTypes from './actionType'; export const save_result = (res) => { return{ type : actionTypes.STORE_RESULT, result : res }; }; export const store_result = (res) => { return (dispatch , getState) => { setTimeout(() => { const oldCounter = getState().ctr.counter; console.log(oldCounter); dispatch(save_result(res)); },2000); } }; export const delete_result = (resID) => { return{ type : actionTypes.DELETE_RESULT, rsId : resID }; };<file_sep>/5/Practice.js import React , {useState} from 'react'; import './App.css'; import styled from 'styled-components'; //import './Person/Person.css'; const Practice = () =>{ const [accData , maniData] = useState({ person : [ {name : 'shariq' , age : 12}, {name : 'harry' , age : 11} ], other : 25, showData : false, }); const [charData , mchar] = useState({ some : 'hello-Bro' }); const buttonStyle = { backgroundColor : 'red', color : 'white', border : '1px solid black', padding : '7px', ':hover':{ backgroundColor : 'black', color : 'white' } } let printData = null; if(accData.showData){ printData = ( <div> { accData.person.map((p, ind) =>{ return <Person name = {p.name} age = {p.age} key = {ind} changeName = {(event) => changeNameEvent(event , ind)} DeleteData = {() =>DeleteDataEvent(ind)}/> }) }</div>); buttonStyle.backgroundColor = 'green'; buttonStyle[':hover'] ={ backgroundColor : 'red', color : 'white' } } const toggleDataEvent = () =>{ let show = accData.showData; maniData({showData : !show, person : [ {name : 'shariq' , age : 12}, {name : 'harry' , age : 11} ]} ); } const changeNameEvent = (event , id) =>{ const findPerson = { ...accData.person[id] } findPerson.name = event.target.value; const persons = [...accData.person]; persons[id] = findPerson; maniData({person : persons, showData : true}); } const DeleteDataEvent = (id) =>{ const data = [...accData.person]; data.splice(id , 1); maniData({person : data, showData : true}); } const inputCharHandler = (event) =>{ mchar({some : event.target.value}); } const delCharEvent = (id) =>{ const data = charData.some.split(''); data.splice(id , 1); const updateChar = data.join(''); mchar({some : updateChar}); } let charlist = ( <div> { charData.some.split('').map((ch , id) =>{ return <CharComp pri = {ch} key = {id} changeText = {inputCharHandler} delChar = {() => delCharEvent(id)}/> }) } </div> ); const classes = []; if(accData.person.length <= 2){ classes.push('red'); } if(accData.person.length <=1){ classes.push('bold'); } //join method combine 2 string with a single string return( <div className = 'App'> <h1>This is H1 Heading</h1> <p className = {classes.join(' ')}>this is paragraph</p> <button style = {buttonStyle} onClick = {toggleDataEvent}>Toggle Data</button> {printData} {charlist} </div> ); } // const heightSt = { // height : '20px', // marginTop : '20px' // } const StyleDiv = styled.div` width: 50%; margin: 10px auto; border: 2px solid #eee; box-shadow: 1px #ccc; text-align: center; padding: 10px; @media (min-width : 500px){ width : 450px } `; const Person = (props) =>{ // const PersonStyle = { // '@media(min-width : 500px)':{ // width : '450px' // } // } //styleroot is used for mediaquery not required for psuedo css return( <StyleDiv> <input type = 'text' onChange = {props.changeName} value = {props.name}></input> <p onClick = {props.DeleteData}>I'm {props.name} and I'm {props.age} Year Old</p> </StyleDiv> ); } const CharComp = (props) =>{ const sty = { display : 'inline-block', border : '1px solid black', width : '50px', height : '50px', margin : '10px', marginTop: '50px', } return( <div style = {sty} onClick = {props.delChar}> <p>{props.pri}</p> <input type = 'text' onChange = {props.changeText}></input> </div> ); } export default Practice; <file_sep>/redux/store/actions/actionType.js export const INC = 'INC'; export const DEC = 'DEC'; export const ADD = 'ADD'; export const SUB = 'SUB'; export const STORE_RESULT = 'STORE_RESULT'; export const DELETE_RESULT = 'DELETE_RESULT'; export const ADD_PERSON = 'ADD_PERSON'; export const REMOVE_PERSON = 'REMOVE_PERSON'; <file_sep>/Basic-to-Components/hoc/withClass.js import React from 'react'; // const withClass = props =>( // <div className = {props.classes}> // {props.children} // </div> // ); const withClass = (WrappedComponent , className) =>{ return props =>( <div className = {className}> <WrappedComponent {...props} /> {/*it auto take all props using spread operator*/} </div> ); }; export default withClass;<file_sep>/Basic-to-Components/LifeCycleMethods.js import React ,{Component} from 'react'; import def from './containers/App.css'; class Product extends Component{ constructor(props){ super(props); this.state = {pId : '' , qty : 0 , isCart : true}; } addToCart = (pid) =>{ this.setState(props=> ( { pId : pid, qty : props.qty+1 })); }; removeCart=()=>{ this.setState({isCart : false}); }; render(){ return( <div className = {def.App}> <h2>LifeCycle Methods of Component</h2> <button onClick = {()=>this.addToCart("p1")}>Add to Cart</button> <button onClick = {()=>this.addToCart("p2")}>Add to Cart</button> <button onClick = {()=>this.addToCart("p3")}>Add to Cart</button> <button onClick = {this.removeCart}>Remove Cart</button> {this.state.isCart ? <Cart pId = {this.state.pId} qty = {this.state.qty}/> : null } </div> ); } } class Cart extends Component{ constructor(props){ super(props); this.state = {qty : this.props.qty}; } static getDerivedStateFromProps(props , state){ //it runs when our state is dependent on props if(props.qty !== state.qty){ return {qty : props.qty, }; } return null; } shouldComponentUpdate(nextProps , nextState){ // it runs when new state or props are encountered if(this.props.qty !== nextProps.qty){ console.log("should component updated"); return true; } return false; } componentDidMount(){ //it runs when component is rendered or after rendering component console.log("COmponentDidMount"); } componentDidUpdate(prevProps , prevState){ //it runs when state or component update if(this.props.pId !== prevProps.pId){ console.log("componentDidUpdate") } } componentWillUnmount(){ console.log("Cart components destroyed"); } // updateQty = () =>{ // this.setState((props)=>( // { // qty : props.qty+1 // })); // }; render(){ return( <div className = {def.App}> <h3>Cart Items {this.state.qty}</h3> </div> ); } } export default Product;<file_sep>/Basic-to-Components/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; //import App from './App'; import registerServiceWorker from './registerServiceWorker'; //import Practice from './Practice'; //import Practice from './Practice'; import Japp from './containers/wb'; // import Product from './LifeCycleMethods'; //import Ass2 from './Ass2'; ReactDOM.render(<Japp appTitle = "Person Manager"/>, document.getElementById('root')); registerServiceWorker(); <file_sep>/Next-Gen Javascript/script.js //let and const let s = 10; //const value once define that never change const v = 25; console.log(s,v); //arrowfunction //the main advantage of arrow function is to resolve this keyword problem const printMyName = (name , age) => { console.log(name, age); } //if there is exactly one arguement so we can write this const MyName = name => { console.log(name); } //for returning 1 arguement we can write like this const mult = (num) => num * 2; const add = (num1, num2) => { return num1+num2; } printMyName("harry",33); MyName("shariq"); console.log(mult(4)); console.log(add(2,3)); //import and export //classes //inherit name class with age class Age{ constructor(){ this.age = 16; } //method printAge(){ console.log(this.age); } } class Name extends Age{ //constructor is a keyword constructor(name){ //super is used to take parent class parameters; super(); this.name = name; // console.log(this.name); } //method printname(){ console.log(this.name); } } let p = new Name("harry"); p.printname(); p.printAge(); //ES6 and ES7 syntax for methods or variables within class class anim { name = "lion"; PrintAnime = () => { console.log(this.name); } } class quan extends anim{ quantity = 10; printAnimeQuantity = () =>{ console.log(this.quantity); } } const animal = new quan(); animal.PrintAnime(); animal.printAnimeQuantity(); //spread and rest operator //spread operator is used to add old array element with new array or object properties //spread extract all element and store them ina variable let arr= [1,2,3,4,5]; let arr2 = [...arr,6,7,8,9]; console.log(arr2); let obj1 = { name:"shariq", age:14 }; let obj2 = { ...obj1, gender:"male" }; console.log(obj2); //rest is used to take function arguements and convert them into list const sortArray = (...ele) => { return ele.sort(); } console.log(sortArray(4,1,6,8,3,9,1)); //destruncturing is to extract single elemnt let num = [1,3,4]; [a,b] = num; //it will skip second elemnt and 4 will be stored in f [e, ,f] = num; console.log(a,b); console.log(e,f); //referenceing //Must remember arrays and objects dont copy the value they copy the pointer or address see e.g let z = { name : "harry" }; let p1 = z; //if we change p here then p1 will auto change z.name = "shariq"; console.log(p1); //but if wee want to copy the object we have to create new object using spread operator as wee see above //refreshing array function let newArray = [1,2,3,4,5]; //map function takes an array and access every eleemnt of an array and perform some operation then //store them in a brand new array let DoubleNewArray = newArray.map((val) => { return val+val; }); console.log(newArray); console.log(DoubleNewArray);<file_sep>/redux/store/reducers/counter.js import * as actionTypes from '../actions/actionType'; import {updateObject} from '../utility'; const InitialState = { counter : 0, } const reducer = (state = InitialState, action) => { switch(action.type){ case actionTypes.INC : return updateObject(state , {counter : state.counter+1} ); case actionTypes.DEC : return updateObject(state , {counter: state.counter-1}); case actionTypes.ADD : return updateObject(state , {counter: state.counter+action.val}); case actionTypes.SUB : return updateObject(state , {counter: state.counter-action.val}); } return state; } export default reducer;<file_sep>/redux/store/actions/counter.js //actionCreators import * as actionTypes from './actionType'; export const inc = () => { return{ type: actionTypes.INC }; }; export const dec = () => { return{ type: actionTypes.DEC }; }; export const add = (value) => { return{ type : actionTypes.ADD, val : value }; }; export const sub = (value) => { return{ type : actionTypes.SUB, val : value }; }; <file_sep>/react-hooks/components/Ingredients/Ingredients.js import React , {useEffect , useCallback , useReducer , useMemo} from 'react'; import IngredientForm from './IngredientForm'; import IngredientList from './IngredientList'; import Search from './Search'; import ErrorModal from '../UI/ErrorModal'; const IngredientReducer = (currentIng , action) => { switch(action.type){ case 'add': return [...currentIng , action.ingredient]; case 'delete': return currentIng.filter(ing => ing.id !== action.id); case 'set' : return action.ingredients; default : throw new Error('Something Wrong'); } }; const HttpReducer = (currHttpState , action) => { switch(action.type){ case 'send': return {loading : true , error : null}; case 'response': return {...currHttpState , loading : false}; case 'clear': return {loading : false , error : null}; case 'ErroR': return {loading : false , error : action.errorMsg}; default: throw new Error('Something Went Wrong!'); } }; const Ingredients = () => { const [userIng , dispatch] = useReducer(IngredientReducer , []); const [httpState , dispatchHttp] = useReducer(HttpReducer , {loading : false , error : null}); //const [userIng , setIng] = useState([]); // const [loading , setLoading] = useState(false); // const [error , setError] = useState(); //loading or getting Ingredients or states from browser or firebase using fetch //useEffect work as a componentDidupdate it renders after re-render cycle //but when we add [] empty [] it become componentDidmount mean it renders once time // ye hr render cycle pr render hta he jb tk k hm iski depencies na btaden useEffect(() => { fetch('https://react-hooks-update-5d594.firebaseio.com/ingredients.json').then( response => response.json()) .then(responseData => { const loadedIng = []; for(let key in responseData){ loadedIng.push({ id : key, title : responseData[key].title, amount : responseData[key].amount }); } dispatch({type : 'set' , ingredients : loadedIng}); }).catch(err => { //setError(err.message); dispatchHttp({type : 'ErroR' , errorMsg : err.message}); }); } , []); // useEffect(() => { // console.log('Rendering Ingredients' , userIng); // } , [userIng]); //it changes when usserIng changes //Sending Ingredients or states to the firebase or browser using fetch const filterIngandler = useCallback(filtIng => { dispatch({type : 'set' , ingredients : filtIng}); } , []); //usecallback performance optimization k loye use kia jata h jese agr addIng wala compo render krna ho tw // removeIng wala comp render na ho to isi unneccesary render se bchne k liye hm callback use krte hen //memo bh performmance optimization k liye lagya jata he.. const addIng = useCallback(ings => { //setLoading(true); dispatchHttp({type : 'send'}); fetch('https://react-hooks-update-5d594.firebaseio.com/ingredients.json' , { method : 'POST', body : JSON.stringify(ings), headers : {'Content-Type' : 'application/json'} }).then(response => { //setLoading(false); dispatchHttp({type : 'response'}); return response.json(); }).then(responseData => { // setIng(prevIng => // [...prevIng, // { // id : responseData.name , // ...ings // } // ]); dispatch({ type : 'add' , ingredient : { id : responseData.name , ...ings }}); }).catch(err => { // setError("Something Went Wrong!!!"); dispatchHttp({type : 'ErroR' , errorMsg : 'Something Wrong!'}); }); }, []); const removeIng = useCallback(ingId => { dispatchHttp({type : 'send'}); fetch(`https://react-hooks-update-5d594.firebaseio.com/ingredients/${ingId}.json` , { method : 'DELETE', }).then(response => { dispatchHttp({type : 'response'}); // setIng(prevIng => prevIng.filter(ing => ing.id !== ingId)); dispatch({type : 'delete' , id : ingId}); }).catch(err => { dispatchHttp({type : 'ErroR' , errorMsg : 'Something Wrong!'}); }); }, []); const clear = useCallback(() => { // setError(null); // setLoading(false); dispatchHttp({type : 'clear'}); }); const ingredientList = useMemo(() => { return( <IngredientList ingredients = {userIng} onRemoveItem = {removeIng}/> ); } , [userIng , removeIng]); return ( <div className="App"> {httpState.error && <ErrorModal onClose = {clear}>{httpState.error}</ErrorModal>} <IngredientForm onAddIng = {addIng} onLoading = {httpState.loading}/> <section> <Search onLoadIngs = {filterIngandler}/> {ingredientList} </section> </div> ); } export default Ingredients;<file_sep>/redux/store/actions/index.js export { inc, dec, add, sub } from './counter'; export { store_result, delete_result } from './result';<file_sep>/react-router/containers/Blog/Posts/Posts.js import React, {Component} from 'react'; import axios from '../../../axios'; import Post from '../../../components/Post/Post'; import './Posts.css'; import {Route} from 'react-router-dom'; import FullPost from '../FullPost/FullPost'; import {Link} from 'react-router-dom'; class Posts extends Component{ state = { posts : [], selectedPostId : null, err : false }; componentDidMount(){ console.log(this.props); axios.get('/posts').then(response =>{ const selectedPosts = response.data.slice(0,4); const updatedPosts = selectedPosts.map(post=>{ return{ ...post, author : 'Shariq' }; }); this.setState({posts : updatedPosts}); //console.log(response); }).catch(err =>{ //catch is used to catch error this.setState({err: true}); }); } selectedPostHandler = (id) =>{ this.setState({selectedPostId : id}); // this.props.history.push('/'+id); } render(){ let allPost= <p style = {{textAlign : 'center'}}>Something Went Wrong!!</p> if(!this.state.err){ allPost = this.state.posts.map(post => { return ( <Link to = {'/posts/'+post.id} key = {post.id}> <Post title = {post.title} author = {post.author} clicked = {() => this.selectedPostHandler(post.id)} /> </Link> ); }); } return( <div> <section className="Posts"> {allPost} </section> <Route path = {this.props.match.url + '/:id'} exact component = {FullPost} /> {/* it is nested route because it is inside post route */} </div> ); } } export default Posts; /* withRouter :- includes all props of components in which we didnt define use :- export default withRouter(post); */<file_sep>/redux/components/AddPerson/AddPerson.js import React , {Component} from 'react'; import './AddPerson.css'; class AddPerson extends Component { state = { name : '', age : '' } nameHandler = (event) => { this.setState({name : event.target.value}) } ageHandler = (event) => { this.setState({age : event.target.value}) } render(){ return( <div className="AddPerson"> <input type = 'text' placeholder = 'Your Name' onChange = {this.nameHandler} value = {this.state.nameHandler} /> <input type = 'number' placeholder = 'age' onChange = {this.ageHandler} value = {this.state.age} /> <button onClick={() => this.props.personAdded(this.state.name , this.state.age)}>Add Person</button> </div> ); } } export default AddPerson;<file_sep>/Basic-to-Components/components/Persons/Persons.js //=================Class Component===============\\ import React , {PureComponent} from 'react'; // PureComponent has ability of shouldComponent Method it chhecks // old props and states with new propes and states so after writing // pureComp we dont need to write shouldCOmponent //Real dom is rendered when render method is called import Wperson from './Wperson/Wperson'; class Persons extends PureComponent { //for checking all props we use pure component // static getDerivedStateFromProps(props,state){ // console.log("[persons.js getDerivedSTatefromprops"); // return state; // } componentWillReceiveProps(nextProps){ console.log("[Update Persons.js] componentwillrecieveprops",nextProps); } // shouldComponentUpdate(nextProps , nextState){ // console.log("[Persons.js] shouldComponentupdate"); // return nextProps.person !== this.props.person || // nextProps.changed !== this.props.changed || // nextProps.clicked !== this.props.clicked; // } componentWillUpdate(nextProps,nextState){ console.log("[Persons.js] compnentWillUpdate",nextProps,nextState); } // getSnapshotBeforeUpdate(prevProps , prevState){ // console.log("[persons.js] getSnapshot"); // return null; // } componentDidUpdate(){ console.log("[persons.js] componentDidUpdate"); } componentWillUnmount(){ console.log('[wb.js] componentWillUnmount'); } render(){ console.log('[Persons.js] rendering...'); return this.props.person.map((per,ind) => { return ( <Wperson name = {per.name} age = {per.age} click = {() => this.props.clicked(ind)} key = {per.id} position = {ind} changed = {(event) => this.props.changed(event , per.id)} /> ); }); }; } export default Persons; //===========FUnctional Componenet =================\\ // import React, { Component } from 'react'; // import Wperson from './Wperson/Wperson'; // const lpersons = (props) => props.person.map((per,ind) => { // return ( // <Wperson name = {per.name} age = {per.age} // click = {() => props.clicked(ind)} key = {per.id} // changed = {(event) => props.changed(event , per.id)} /> // ); // }); // export default lpersons;<file_sep>/Basic-to-Components/Person/Person.js import React from 'react'; const person = (props) =>{ return( <div className = "Person"> <p onClick = {props.click}>I m {props.name} and I am {props.age} years old </p> <p>{props.children}</p> <input type = "text" onChange = {props.changeName} value = {props.name}></input> </div> ); //we can write it in component //<p>I'm a Person! and I'm {Math.floor(Math.random()*30)+1} years old </p> }; export default person;<file_sep>/Basic-to-Components/containers/wb.js import React , {PureComponent} from 'react'; import def from './App.css'; import Persons from '../components/Persons/Persons'; import Cockpit from '../components/cockpit/cockpit'; import withClass from '../hoc/withClass'; import Auxiliary from '../hoc/Auxiliary'; import AuthContext from '../context/auth-context'; //import ErrorBoundary from '../ErrorBoundary/ErrorBoundary'; //const Wb = () =>{ // const [Wper ,SetWper] = useState({ // person : [ // {name : "harry", age : 11}, // {name : "shariq", age : 21}, // {name : "james", age : 61} // ], // showPerson : false // }); // const switchName = (newName) =>{ // SetWper({ // person : [ // {name : newName, age : 11}, // {name : "pakistan", age : 21}, // {name : "james-and", age : 61} // ] // }) // } // const nameChange = (event) =>{ // SetWper({ // person : [ // {name :"harry", age : 11}, // {name : event.target.value, age : 21}, // {name : "james-and", age : 61} // ] // }) // } // const togglePerson = () =>{ // const doesShow = Wper.showPerson; // SetWper({showPerson : !doesShow}); // } // const style = { // backgroundColor : "blue", // color : "White" // }; // let persons = null; // if(Wper.showPerson){ // persons = ( // <div> // {Wper.person.map(per => { // return <Wperson name = {per.name} age = {per.age} /> // }) // } // </div> // ); // } // return( // <div className = "App"> // <h1>Welcome Back to React</h1> // <button style = {style} onClick = {togglePerson}>Switch Name</button> // {/* <Wperson click = {switchName.bind(this,"I'm Clicked!")} name = {Wper.person[0].name} age = {Wper.person[0].age}>Hello This my Bio</Wperson> // <Wperson changed = {nameChange} name = {Wper.person[1].name} age = {Wper.person[1].age}>Hello This my Bio</Wperson> // <Wperson click = {switchName.bind(this,"I'm Clicked!")} name = {Wper.person[2].name} age = {Wper.person[2].age}>Hello This my Bio</Wperson> */} // {persons} // </div> // ); // } // const StyledButton = Styled.button` // background-color : ${props => props.alt ? 'red' : 'green'}; // width : 100px; // height : 50px; // font : inherit; // padding : 5px; // border : 1px solid black; // &:hover{ // background-color : ${props => props.alt ? 'blue' : 'black'}; // color : white; // } // `; export const AuthenContext = React.createContext(false) class Japp extends PureComponent{ constructor(props){ super(props); console.log('[wb.js] constructor'); } ; state = { person : [ {id : "22" , name : "harry", age : 11}, {id : "222" , name : "shariq", age : 21}, {id : "32" , name : "james", age : 61} ], showPerson : false, showCockpit : true, changeCounter : 0, toggleClicked : 0, isAuthenticated : false }; static getDerivedStateFromProps(props , state){ console.log('[wb.js] getDerivedStateFromProps',props); return state; } // componentWillMount(){ // console.log('[wb.js] componentWillMount'); // } componentDidMount(){ console.log('[wb.js] componentDidMount'); } // shouldComponentUpdate(nextProps , nextState){ // console.log("[wb.js] shouldComponentUpdate"); // return true; // // return nextState.person !== this.state.person || // // nextState.showPerson !== this.state.showPerson; // } componentDidUpdate(){ console.log("[wb.js] componentDIdUpdate"); } togglePerson = () =>{ const doesShow = this.state.showPerson; this.setState((prevState,props)=>{ return { showPerson : !doesShow, toggleClicked : prevState.toggleClicked+1 } } ); } deletePerson = (pindex) =>{ const persons = [...this.state.person]; persons.splice(pindex,1); this.setState({person : persons}); } changeName = (event, id) =>{ const personIndex= this.state.person.findIndex(p =>{ return p.id === id; }); const getPerson = { ...this.state.person[personIndex] }; getPerson.name = event.target.value; const persons = [...this.state.person]; persons[personIndex] = getPerson; this.setState((prevState , props) =>{ return { person : persons, changeCounter: prevState.changeCounter+1 }; }); }; loginHandler = () =>{ this.setState({isAuthenticated:true}); }; render(){ console.log('[wb.js] render'); let persons = null; if(this.state.showPerson){ persons = ( <div> <Persons personLength = {this.state.person.length} clicked = {this.deletePerson} changed = {this.changeName} person = {this.state.person} /> </div> ); } return( <Auxiliary> {/* <button onClick = {()=>{ this.setState({showCockpit : false}); }}>RemoveCockpit</button> */} <button onClick = {()=>{this.setState({showPerson : true})}}>Show Persons</button> <AuthContext.Provider value = {{ authenticated : this.state.isAuthenticated, login : this.loginHandler }}> {this.state.showCockpit ? <Cockpit title = {this.props.appTitle} showPerson = {this.state.showPerson} clicked = {this.togglePerson} login = {this.loginHandler} /> : null} {persons} {/* <AuthenContext.Provider value = {this.state.isAuthenticated}> {persons}</AuthenContext.Provider> */} </AuthContext.Provider> </Auxiliary> ); } } export default withClass(Japp,def.App); // return React.createElement("div",{className : "App"}, React.createElement("h1",null,"Wao! Its Working")); // const style = { // backgroundColor : "green", // width : "100px", // height : "50px", // font : "inherit", // padding : "5px", // border : "1px solid black", // ':hover':{ // backgroundColor : "black", // color : "white" // } // }; <file_sep>/1-4/Practice.js import React , {useState} from 'react'; import './App.css'; //import person from './Person/Person'; const Practice = () =>{ const [accData , maniData] = useState({ person : [ {name : 'shariq' , age : 12}, {name : 'harry' , age : 11} ], other : 25, showData : false, }); const [charData , mchar] = useState({ some : 'hello-Bro' }); let printData = null; if(accData.showData){ printData = ( <div> { accData.person.map((p, ind) =>{ return <Person name = {p.name} age = {p.age} key = {ind} changeName = {(event) => changeNameEvent(event , ind)} DeleteData = {() =>DeleteDataEvent(ind)}/> }) }</div>); } const toggleDataEvent = () =>{ let show = accData.showData; maniData({showData : !show, person : [ {name : 'shariq' , age : 12}, {name : 'harry' , age : 11} ]} ); } const changeNameEvent = (event , id) =>{ const findPerson = { ...accData.person[id] } findPerson.name = event.target.value; const persons = [...accData.person]; persons[id] = findPerson; maniData({person : persons, showData : true}); } const DeleteDataEvent = (id) =>{ const data = [...accData.person]; data.splice(id , 1); maniData({person : data, showData : true}); } const inputCharHandler = (event) =>{ mchar({some : event.target.value}); } const delCharEvent = (id) =>{ const data = charData.some.split(''); data.splice(id , 1); const updateChar = data.join(''); mchar({some : updateChar}); } let charlist = ( <div> { charData.some.split('').map((ch , id) =>{ return <CharComp pri = {ch} key = {id} changeText = {inputCharHandler} delChar = {() => delCharEvent(id)}/> }) } </div> ); return( <div className = 'App'> <h1>This is H1 Heading</h1> <p>this is paragraph</p> <button onClick = {toggleDataEvent}>Toggle Data</button> {printData} {charlist} </div> ); } const Person = (props) =>{ return( <div> <p onClick = {props.DeleteData}>I'm {props.name} and I'm {props.age} Year Old</p> <input type = 'text' onChange = {props.changeName} value = {props.name}></input> </div> ); } const CharComp = (props) =>{ const sty = { display : 'inline-block', border : '1px solid black', width : '50px', height : '50px', margin : '10px', marginTop: '50px', } return( <div style = {sty} onClick = {props.delChar}> <p>{props.pri}</p> <input type = 'text' onChange = {props.changeText}></input> </div> ); } export default Practice; <file_sep>/redux/App.js import React, { Component } from 'react'; // import AddPerson from './components/AddPerson/AddPerson'; import Counter from './containers/Counter/Counter'; import './App.css'; //import Person from './containers/Persons'; class App extends Component { render() { return ( <div className = 'App'> <Counter /> </div> ); } } export default App; <file_sep>/react-hooks/components/Ingredients/Search.js import React, { useEffect, useState , useRef } from 'react'; import Card from '../UI/Card'; import './Search.css'; const Search = React.memo(props => { const {onLoadIngs} = props; const [enteredFilter , setFilter] = useState(''); const inputRef = useRef(); useEffect(() => { const timer = setTimeout(() => { if(enteredFilter === inputRef.current.value){ const query = enteredFilter.length === 0 ? '' :`?orderBy="title"&equalTo="${enteredFilter}"`; fetch('https://react-hooks-update-5d594.firebaseio.com/ingredients.json'+ query).then( response => response.json()) .then(responseData => { const loadedIng = []; for(let key in responseData){ loadedIng.push({ id : key, title : responseData[key].title, amount : responseData[key].amount }); } onLoadIngs(loadedIng); }); } } , 500); return () => { clearTimeout(timer); } } , [enteredFilter , onLoadIngs , inputRef]); return ( <section className="search"> <Card> <div className="search-input"> <label>Filter by Title</label> <input type="text" value = {enteredFilter} ref = {inputRef} onChange = {event => setFilter(event.target.value)} /> </div> </Card> </section> ); }); export default Search; //useRef define the current value
f22126b746f131348fe4498c4924628474d6a599
[ "JavaScript" ]
23
JavaScript
ShariqAteeq/React-Learning
8c11fda373f3eaf0028c2b0d3f1f30c6d592d817
3b3bcea21c2614da0714e395a0fd330159ce4a7b
refs/heads/master
<file_sep>$(document).ready(function(){ $("#search").click(function() { var term = $("#name").val(); var api = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + term + "&format=json&origin=*&callback=?"; $.ajax({ type:"GET", url: api, assync: false, dataType: "json", success: function(data){ $("#result").html(""); for(var i = 0; i<data[1].length; i++){ $("#result").prepend("<a href=" + data[3][i] + " target=blank_ class=list-group-item" + ">" + "<b>" + data[1][i] + "</b></br></br>" + data[2][i] + "</a>"); }; }, error: function(errorMessage){ alert("Error"); } }); $("#name").val(""); }); $("#name").keyup(function(event) { if (event.keyCode === 13) { $("#search").click(); }; }); });
666c6024bb5bbf68f431ceb2b9316b7cf13fd3d6
[ "JavaScript" ]
1
JavaScript
KLinowska/wikipedia-viewer
5c0d70c4769c2e1d8ab8cd03cf5cbfe11e88b97e
e568483625f059495b2474f1cf566e7e6c79fae3
refs/heads/master
<repo_name>cerutidavide/photomanager<file_sep>/com/ceruti/photomanager/photomanager.py #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3 -tt import sys import shutil import os import stat from pathlib import Path import time import re # # inserire il logging e ripulire i commenti e le procedure # # accetta in input un file con questo tracciato: # find mypath -type f -exec md5 {} \; def printFileDetails(filename): # print 'Nome file:' + filename print (stat.filemode (os.stat (filename).st_mode)) # stat.filemode(mode def loadHashFromFile(filename): f = open (filename , 'r' , encoding="utf-8") hashresult = {} alllines = f.readlines () rownumber = 0 keynumber = 0 for row in alllines: key = row.split ()[3] if key in hashresult.keys (): hashresult[key].append (row.split ()[1][1:-1]) else: hashresult[key] = row.split ()[1][1:-1].split () keynumber = keynumber + 1 rownumber = rownumber + 1 f.close () print ('Il numero delle linee lette è ' + str (rownumber)) print ('Il numero dei file univoci è ' + str (keynumber)) return hashresult pass def printHashKeysAndValuesFormatted(hashtable): for key in hashtable.keys (): print (key + "||" + '||'.join (hashtable[key])) print ('Hashtable contiene in totale ' + str (countHashValueItemsTotal (hashtable)) + ' oggetti') print ('Hashtable raggruppa tali oggetti in ' + str (len (hashtable)) + ' liste ') pass def countHashValueItemsTotal(hashtable): itemnumber = 0 for key in hashtable.keys (): itemnumber = itemnumber + len (hashtable[key]) # print('>>>>>>>>'+str(hashtable[key])) pass return itemnumber pass ########retrieveUniqFileHash(hashtable,destinationPath,preferredPathSubstr)## ####hashtable################################################################ ######## è un hash costruito con loadHashFromFile(filename) dove il file #### ######## filename ha questa struttura: ###################################### ######## MD5 (/albero/sottoalbero/nomefile) = MD5code ####################### ######## ad esempio ottenibile con find path -type f -exec md5 {} \; ######## ####destinationPath########################################################## ######## è il percorso su cui si vuole creare l'alberatura di cartelle e ######## file ######## contenente solo i file non duplicati ####preferredPathSubstr################# ######## è il path da cui preferibilmente si vogliono copiare i file ######## nel caso di file duplicati in percorsi origine differenti def retrieveUniqFileHash(hashtable , preferredPathSubstr): hashresult = {} strfield = '' for key in hashtable.keys (): if len (hashtable[key]) == 1: hashresult[key] = hashtable[key] else: for strfield in hashtable[key]: if strfield.find (preferredPathSubstr) > -1: hashresult[key] = strfield.split () else: if key in hashresult: pass else: hashresult[key] = strfield.split () pass pass return hashresult pass # ATTENZIONE check is_absolute() Path.chmod(mode)¶ Path.is_dir()¶ def copyUniqFileToFolder(hashtable , destinationPath): p = Path (destinationPath) if p.exists () and p.is_dir (): # print(destinationPath+' esiste') giro = 0 for key in hashtable.keys (): giro = giro + 1 # print('>>>>'+str(giro)) f = Path (hashtable[key][0]) print (str (f)) if f.exists () and f.is_file (): print (time.ctime (os.stat (f).st_mtime).split ()[1:5:3]) d1 = Path (destinationPath + '/' + time.ctime (os.stat (f).st_mtime).split ()[1:5:3][1] + '/') # print(d1) d1.mkdir (exist_ok=True) if d1.exists () and d1.is_dir (): d2 = Path (destinationPath + '/' + time.ctime (os.stat (f).st_mtime).split ()[1:5:3][1] + '/' + time.ctime (os.stat (f).st_mtime).split ()[1:5:3][0] + '/') print (d2) d2.mkdir (exist_ok=True) if d2.exists () and d2.is_dir (): # print('>>>>>>>>'+hashtable[key][0]) ext = '' m = re.search ('\..*$' , hashtable[key][0]) if m: ext = ext + m.group ().lower () print ('estensione: ' + ext) d = p.joinpath (d1).joinpath (d2).joinpath (key + ext) print ('>>>>>NOME FILE DA COPIARE>>>>>' + str (d)) if d.exists (): print ('GIA COPIATO IN PRECEDENZA') pass else: dst = shutil.copy2 (f , d) if Path (dst).exists (): print ('Il file ' + str (dst) + " è stato copiato correttamente") else: print ('Errore nella creazione del file') else: print ('Errore nella creazione della sottodirectory' + str (d2)) else: print ('Errore nella creazione della sottodirectory' + str (d1)) else: print ('Errore il file non esiste o non è accessibile' + str (f)) else: print ('errore il percorso di destinazione non esiste o non accessibile' + str (p)) def main(): # inserire controlli sui parametri di ingresso myhash = loadHashFromFile (sys.argv[1]) myreducedhash = retrieveUniqFileHash (myhash , sys.argv[3]) copyUniqFileToFolder (myreducedhash , sys.argv[2]) # printHashKeysAndValuesFormatted(myhash) # myhashresult=copyUniqFileToFolder(myhash,'/tmp','Photos') # printHashKeysAndValuesFormatted(myhashresult) if __name__ == '__main__': main () <file_sep>/com/ceruti/photomanager/fileDisplay.py ''' Created on Mar 13, 2018 @author: davideceruti ''' import sys import os import stat import time def main(): pass print(sys.argv[1]) def fileDisplay(nomefile): print(os.stat(nomefile)) def listFileNameMonthYear(listfname): print(stat.filemode(os.stat(listfname).st_mode)) #ctime=time.ctime(os.stat(listfname).st_ctime) #ctime=os.stat(listfname).st_ctime print(time.ctime(os.stat(listfname).st_mtime).split()[1:5:3]) pass if __name__ == '__main__': # fileDisplay(sys.argv[1]) listFileNameMonthYear(sys.argv[1]) pass<file_sep>/templateHashTabel.py ''' Created on Mar 9, 2018 @author: davideceruti ''' import sys def main(): filename=sys.argv[1] f=open(filename,'r') hashtable={} for line in f: key=line.split('=')[0] value=line.split('=')[1] if key in hashtable.keys(): hashtable[key]=hashtable[key].append(value) else: hashtable[key]=value f.close() print hashtable # # myhash={} #hashtable di input # myhash2={} #hashtable di output # aList=[] # aList.append('/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoDisco///010.jpg') # myhash['4d9f980b35232a3f8762f4a800b2459c']=['/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoDisco///010.jpg'] # myhash['a5866ca92bb05bbf9cfdecb2f092b278']=['/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoPhotos///MasterFotoPhotosOriginali/xyz.jpg','/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoDisco///xyz.jpg'] # print myhash.keys() # print myhash.values() # print myhash.items() # if len(myhash['a5866ca92bb05bbf9cfdecb2f092b278']) > 1: # print 'da cancellare' # myhash2['a5866ca92bb05bbf9cfdecb2f092b278']=myhash['a5866ca92bb05bbf9cfdecb2f092b278'][0] # else: # print 'singolo' # if len(myhash['4d9f980b35232a3f8762f4a800b2459c']) > 1: # print 'da cancellare' # myhash2['4d9f980b35232a3f8762f4a800b2459c']=myhash['4d9f980b35232a3f8762f4a800b2459c'][0] # else: # myhash2['4d9f980b35232a3f8762f4a800b2459c']=myhash['4d9f980b35232a3f8762f4a800b2459c'][0] # print 'singolo' # print myhash2 # #non serve nemmeno la if perch comunque devi inserire nell hash solo il primo elemento pass if __name__ == '__main__': main() <file_sep>/pythonMergeFiles.py #!/usr/bin/python -tt import sys def ConCat(filename1,filename2,filename3): f1=open(filename1, 'r') f2=open(filename2,'r') str1=f1.read() str2=f2.read() f3=open(filename3, 'w+') f3.write(str1+str2) def main(): ConCat(sys.argv[1],sys.argv[2],sys.argv[3]) if __name__ == '__main__': main()<file_sep>/strings1.py ''' Created on Mar 9, 2018 @author: davideceruti ''' def main(): print 'ciao' if __name__ == '__main__': main() myhash={} #hashtable di input myhash2={} #hashtable di output aList=[] aList.append('/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoDisco///010.jpg') myhash['4d9f980b35232a3f8762f4a800b2459c']=['/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoDisco///010.jpg'] myhash['a5866ca92bb05bbf9cfdecb2f092b278']=['/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoPhotos///MasterFotoPhotosOriginali/xyz.jpg','/Volumes/TOSHIBAEXT/MASTERFoto/MasterFotoDisco///xyz.jpg'] print myhash.keys() print myhash.values() print myhash.items() if len(myhash['a5866ca92bb05bbf9cfdecb2f092b278']) > 1: print 'da cancellare' myhash2['a5866ca92bb05bbf9cfdecb2f092b278']=myhash['a5866ca92bb05bbf9cfdecb2f092b278'][0] else: print 'singolo' if len(myhash['4d9f980b35232a3f8762f4a800b2459c']) > 1: print 'da cancellare' myhash2['4d9f980b35232a3f8762f4a800b2459c']=myhash['4d9f980b35232a3f8762f4a800b2459c'][0] else: myhash2['4d9f980b35232a3f8762f4a800b2459c']=myhash['4d9f980b35232a3f8762f4a800b2459c'][0] print 'singolo' print myhash2 #non serve nemmeno la if perchè comunque devi inserire nell'hash solo il primo elemento pass
aa00cfb9758be1bbbe76101f332a70389ca1c059
[ "Python" ]
5
Python
cerutidavide/photomanager
d1f06a69c5513f56c58f66c9bb6592da5612fe35
36b37cbd11e5272d9bd75494393264d0eb2197d3
refs/heads/master
<file_sep># zesty-menu <p align="center"><img src="/img/demo.gif?raw=true"/></p> Command Line for Zesty Menus ## Install ```bash > npm install -g zesty-menu ``` ## Setup You must set variable `ZESTY_ID` in your environment to your zesty client_id ## Usage There are no flags to use ```bash > zesty-menu ``` <file_sep>#!/usr/bin/env node const { h, render, renderToString, Component, Color, Fragment, Bold, span, div } = require('ink') const chalk = require('chalk') const Gradient = require('ink-gradient') const BigText = require('ink-big-text') const Divider = require('ink-divider') const Spinner = require('ink-spinner') const fetch = require('node-fetch') const addDays = require('date-fns/add_days') const format = require('date-fns/format') const ZESTY_ID = process.env.ZESTY_ID const ZESTY_ENDPOINT = 'https://api.zesty.com/client_portal_api' const YELLOW = '#FFFFA5' const GREEN = '#69FF94' const BLUE = '#D6ACFF' const RED = '#ffb3ba' if (!ZESTY_ID) { console.log( chalk.hex(YELLOW)( 'Please set environment variable "ZESTY_ID" as your Zesty client id first.' ) ) process.exit() } const getMealsByDate = (meals, startDate, endDate) => meals .filter(meal => { const date = new Date(meal.delivery_date) return date >= startDate && date <= endDate }) .reduce((acc, meal) => { const date = new Date(meal.delivery_date) if (!acc[format(date, 'YYYY/MM/DD')]) { acc[format(date, 'YYYY/MM/DD')] = [] } acc[format(date, 'YYYY/MM/DD')].push(meal) return acc }, {}) class DayHeader extends Component { render() { const { date } = this.props return ( <Divider title={renderToString( <Fragment> <Color hex={YELLOW}>{format(date, 'ddd')} </Color> <span>{format(date, 'MMM DD, YYYY')}</span> </Fragment> )} /> ) } } class MealView extends Component { render() { const { meal } = this.props return ( <div> <span> {format(meal.delivery_date, 'h:mma').padStart(10)} {' | '} </span> <Color hex={GREEN}>{meal.restaurant_name}</Color> <Color hex={BLUE}> [{meal.restaurant_cuisine}]</Color> </div> ) } } class Controls extends Component { constructor(props) { super(props) this.handleKeyPress = this.handleKeyPress.bind(this) } componentDidMount() { process.stdin.on('keypress', this.handleKeyPress) } componentWillUnmount() { process.stdin.removeListener('keypress', this.handleKeyPress) } handleKeyPress(_, key) { const { onPrev, onNext, prevEnabled, nextEnabled } = this.props if (key.name === 'left' && prevEnabled) { onPrev() } if (key.name === 'right' && nextEnabled) { onNext() } } render() { const { prevEnabled, nextEnabled } = this.props return ( <div> <Color hex={prevEnabled && GREEN}>{'<'.padEnd(6)}</Color> <span>'left' and 'right' to toggle through weeks</span> <Color hex={nextEnabled && GREEN}>{'>'.padStart(6)}</Color> </div> ) } } class WeekTable extends Component { constructor(props) { super(props) this.state = { meals: [], weekOffset: 0 } } componentWillMount() { const { zestyId } = this.props this.setState({ loading: true }) const fetchMeals = fetch( [ZESTY_ENDPOINT, 'meals'].join('/') + '?client_id=' + zestyId ) .then(res => res.json()) .then(res => this.setState({ meals: res.meals }) ) const fetchClient = fetch( [ZESTY_ENDPOINT, 'clients', zestyId].join('/') ) .then(res => res.json()) .then(res => this.setState({ clientInfo: res.client }) ) Promise.all([fetchMeals, fetchClient]) .then(() => this.setState({ loading: false }) ) .catch(err => { console.log( chalk.bold.hex(RED)( 'Something went wrong with the request to Zesty, check the error below to debug' ) ) console.error(err) process.exit() }) } render() { const { meals, clientInfo, loading, weekOffset } = this.state const currentDate = addDays(new Date(), weekOffset * 7) currentDate.setHours(0, 0, 0, 0) const monday = new Date(currentDate) const sunday = new Date(currentDate) monday.setDate(currentDate.getDate() - currentDate.getDay()) sunday.setDate(currentDate.getDate() + (7 - currentDate.getDay())) const mealsOfWeek = getMealsByDate(meals, monday, sunday) const weekKeys = Object.keys(mealsOfWeek) const firstMealsOfWeek = mealsOfWeek[weekKeys[0]] const lastMealsOfWeek = mealsOfWeek[weekKeys[weekKeys.length - 1]] if (loading) { return ( <div> <Spinner green /> Loading Meals </div> ) } return ( <Fragment> {clientInfo && ( <Gradient name="pastel"> <BigText text={clientInfo.name} font="chrome" /> </Gradient> )} {Object.keys(mealsOfWeek).map(key => { const mealsOfDay = mealsOfWeek[key] const date = new Date(key) return ( <Fragment> <DayHeader date={date} /> <br /> {mealsOfDay.map(m => ( <MealView meal={m} /> ))} <br /> </Fragment> ) })} <br /> <Controls prevEnabled={ (firstMealsOfWeek && firstMealsOfWeek[0].id) !== (meals[0] && meals[0].id) } nextEnabled={ (lastMealsOfWeek && lastMealsOfWeek[lastMealsOfWeek.length - 1].id) !== (meals[meals.length - 1] && meals[meals.length - 1].id) } onPrev={() => this.setState({ weekOffset: this.state.weekOffset - 1 }) } onNext={() => this.setState({ weekOffset: this.state.weekOffset + 1 }) } /> <br /> </Fragment> ) } } render(<WeekTable zestyId={ZESTY_ID} />)
374b8ca67f41a1e67aff0abb124fb68889e3124e
[ "Markdown", "JavaScript" ]
2
Markdown
CrokinoleMaster/zesty-menu
25708f7721ba3e89a660db44b1642f1146df59cc
316e9674f924d58a4a1b2004e911f48a15441b4c
refs/heads/master
<repo_name>sillypog/CraftCpp<file_sep>/makefile CFLAGS=-Wall -Wextra -std=c++1y INCLUDE_PATHS = -I/Users/sillypog/OpenGL/glfw/include -I/Users/sillypog/OpenGL/glew/glew-1.10.0-built/include -I/Users/sillypog/OpenGL/glm LIBRARY_PATHS = -L/Users/sillypog/OpenGL/glfw/build/src -L/Users/sillypog/OpenGL/glew/glew-1.10.0-built/lib LINKER_FLAGS = -lglew -lglfw3 -lpng -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo #DEFINES = -DGLM_MESSAGES all: g++ -v $(CFLAGS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(LINKER_FLAGS) $(DEFINES) src/main.cpp -o GLFWWindowCpp <file_sep>/src/main.cpp /* * main.cpp * * Created on: May 14, 2014 * Author: sillypog */ #define GLEW_STATIC #define GLFW_INCLUDE_GL3 /* don't drag in legacy GL headers. */ #define GLFW_NO_GLU /* don't drag in the old GLU lib - unless you must. */ #include <GL/glew.h> #include <GLFW/glfw3.h> #include <png.h> #include <glm/gtc/constants.hpp> // Wanted to use this for two_pi #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <cmath> // Needed for sin #include <fstream> // Needed to read files #include <iostream> // Needed to write to console #include <limits> // Needed to get lowest float value #include <sstream> // Needed for stringstream, to hold file contents as string buffer #include <string> // C++ strings using namespace std; // Create something to render // Vertexes are X, Y, R, G, B, texX, texY // Images are read upside down so the top of the shape has the bottom of the image float repeatX = 1.0f; float repeatY = 1.0f; float vertices[] = { -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, repeatY, // Top-left 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, repeatX, repeatY, // Top-right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, repeatX, 0.0f, // Bottom-right // 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right Don't need to repeat -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f // Bottom-left // -0.5f, 0.5f, 1.0f, 0.0f, 0.0f // Top-left Don't need to repeat }; // Form a square from 2 triangles GLuint elements[] = { 0, 1, 2, // tl, tr, br 2, 3, 0 // br, bl, tl }; string vertexShaderFile; string fragmentShaderFile; GLubyte *kittenImage; GLubyte *puppyImage; int frames = 0; float rotationStartTime = numeric_limits<float>::lowest(); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){ if (key == GLFW_KEY_SPACE && action == GLFW_PRESS && rotationStartTime < 0){ cout << "Pressed space" << endl; rotationStartTime = glfwGetTime(); } } void error_callback(int error, const char* description){ cout << "There was an error: " << error << ": " << description << endl; } void loadShader(string filename, string &shader){ cout << "Loading file: " << filename << endl; ifstream data(filename); if (data.bad() || !data.is_open()) { cerr << "Unable to open " << filename << endl; exit(EXIT_FAILURE); } stringstream buffer; buffer << data.rdbuf(); shader = buffer.str(); data.close(); } void checkShaderStatus(GLuint shader, string shaderName){ GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_TRUE){ cout << shaderName << " compiled successfully" << endl; } else { cout << shaderName << " compilation failed" << endl; char buffer[512]; glGetShaderInfoLog(shader, 512, NULL, buffer); cout << buffer; } } bool loadPngImage(char *name, int &outWidth, int &outHeight, bool &outHasAlpha, GLubyte **outData) { png_structp png_ptr; png_infop info_ptr; unsigned int sig_read = 0; int color_type, interlace_type; FILE *fp; if ((fp = fopen(name, "rb")) == NULL) return false; /* Create and initialize the png_struct * with the desired error handler * functions. If you want to use the * default stderr and longjump method, * you can supply NULL for the last * three parameters. We also supply the * the compiler header file version, so * that we know if the application * was compiled with a compatible version * of the library. REQUIRED */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { fclose(fp); return false; } /* Allocate/initialize the memory * for image information. REQUIRED. */ info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { fclose(fp); png_destroy_read_struct(&png_ptr, NULL, NULL); return false; } /* Set error handling if you are * using the setjmp/longjmp method * (this is the normal method of * doing things with libpng). * REQUIRED unless you set up * your own error handlers in * the png_create_read_struct() * earlier. */ if (setjmp(png_jmpbuf(png_ptr))) { /* Free all of the memory associated * with the png_ptr and info_ptr */ png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); /* If we get here, we had a * problem reading the file */ return false; } /* Set up the output control if * you are using standard C streams */ png_init_io(png_ptr, fp); /* If we have already * read some of the signature */ png_set_sig_bytes(png_ptr, sig_read); /* * If you have enough memory to read * in the entire image at once, and * you need to specify only * transforms that can be controlled * with one of the PNG_TRANSFORM_* * bits (this presently excludes * dithering, filling, setting * background, and doing gamma * adjustment), then you can read the * entire image (including pixels) * into the info structure with this * call * * PNG_TRANSFORM_STRIP_16 | * PNG_TRANSFORM_PACKING forces 8 bit * PNG_TRANSFORM_EXPAND forces to * expand a palette into RGB */ png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL); png_uint_32 width, height; int bit_depth; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); outWidth = width; outHeight = height; outHasAlpha = (color_type & PNG_COLOR_MASK_ALPHA); unsigned int row_bytes = png_get_rowbytes(png_ptr, info_ptr); *outData = (unsigned char*) malloc(row_bytes * outHeight); png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr); for (int i = 0; i < outHeight; i++) { // note that png is ordered top to // bottom, but OpenGL expect it bottom to top // so the order or swapped memcpy(*outData+(row_bytes * (outHeight-1-i)), row_pointers[i], row_bytes); } /* Clean up after the read, * and free any memory allocated */ png_destroy_read_struct(&png_ptr, &info_ptr, NULL); /* Close the file */ fclose(fp); /* That's it */ return true; } /** * t = current * b = beginning * c = change * d = total */ float easeOutQuad(float t, float b, float c, float d) { return -c *(t/=d)*(t-2) + b; } int main() { cout << "Hello World from C++!" << endl; glfwSetErrorCallback(error_callback); if (!glfwInit()){ exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL); if (!window){ glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwSetKeyCallback(window, key_callback); // Setup GLEW to handle modern OpenGL functions glewExperimental = GL_TRUE; glewInit(); // Test GLEW /*GLuint vertexBuffer; glGenBuffers(1, &vertexBuffer); printf("%u\n", vertexBuffer);*/ printf("OpenGL version supported by this platform (%s): \n", glGetString(GL_VERSION)); // Load texture image int widthKitten, heightKitten; bool hasAlphaKitten; char filename[] = "textures/sample.png"; bool success = loadPngImage(filename, widthKitten, heightKitten, hasAlphaKitten, &kittenImage); printf("Outcome of loading %s: %s \n ", filename, success ? "success" : "fail"); if (success){ cout << filename << ": " << widthKitten << "x" << heightKitten << ", hasAlpha: " << hasAlphaKitten << endl; } int widthPuppy, heightPuppy; bool hasAlphaPuppy; strcpy(filename, "textures/sample2.png"); // c way of reassigning char array, eg `filename = "..."` success = loadPngImage(filename, widthPuppy, heightPuppy, hasAlphaPuppy, &puppyImage); printf("Outcome of loading %s: %s \n ", filename, success ? "success" : "fail"); // Prepare things for rendering GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; // Vertex buffer object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Textures GLuint textures[2]; glGenTextures(2, textures); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, hasAlphaKitten ? GL_RGBA : GL_RGB, widthKitten, heightKitten, 0, hasAlphaKitten ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, kittenImage); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, hasAlphaPuppy ? GL_RGBA : GL_RGB, widthPuppy, heightPuppy, 0, hasAlphaPuppy ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, puppyImage); loadShader("shaders/vertex_shader.glsl", vertexShaderFile); loadShader("shaders/fragment_shader.glsl", fragmentShaderFile); GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); const char *vertexShader_cStr = vertexShaderFile.c_str(); // Have to convert to c pointer array to pass to function glShaderSource(vertexShader, 1, &vertexShader_cStr, NULL); glCompileShader(vertexShader); checkShaderStatus(vertexShader, "vertexShader"); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); const char *fragmentShader_cStr = fragmentShaderFile.c_str(); glShaderSource(fragmentShader, 1, &fragmentShader_cStr, NULL); glCompileShader(fragmentShader); checkShaderStatus(fragmentShader, "fragmentShader"); // Combine shaders GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); //glBindFragDataLocation(shaderProgram, 0, "outColor"); // Not needed as 0 is default buffer glLinkProgram(shaderProgram); // Saves changes glUseProgram(shaderProgram); // Only one can be used at a time // Once vertex array object is created, define how our vertex data is passed in GLint posAttrib = glGetAttribLocation(shaderProgram, "position"); glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); // position has 2 members of type float glEnableVertexAttribArray(posAttrib); GLint colAttrib = glGetAttribLocation(shaderProgram, "color"); glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); glEnableVertexAttribArray(colAttrib); GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord"); glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); glEnableVertexAttribArray(texAttrib); // Set color through uniform to be passed to fragment shader //GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor"); //glUniform3f(uniColor, 1.0f, 0.0f, 0.0f); glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0); glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1); GLint elapsed = glGetUniformLocation(shaderProgram, "elapsed"); glUniform1f(elapsed, 0.0f); // Make an element buffer to reuse vertices GLuint ebo; glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); // Create a transformation glm::mat4 model; // Apply the transformation GLint uniModel = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model)); // Create a view, which is the camera glm::mat4 view = glm::lookAt( glm::vec3(1.2f, 1.2f, 1.2f), // Camera position glm::vec3(0.0f, 0.0f, 0.0f), // Point to focus on glm::vec3(0.0f, 0.0f, 1.0f) // Define the "up" axis ); GLint uniView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view)); // Create a perspective projection glm::mat4 proj = glm::perspective(glm::radians(45.0f), 640.0f / 480.0f, 1.0f, 10.0f); GLint uniProj = glGetUniformLocation(shaderProgram, "proj"); glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj)); float startTime = glfwGetTime(); const float maxRotation = glm::two_pi<float>(); const float tweenLength = 2.0f; while(!glfwWindowShouldClose(window)){ // Keep running // Clear the screen to black glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); float time = glfwGetTime(); glUniform1f(elapsed, time); // Allow it to spin on space press if (rotationStartTime > 0){ // Decide how much to rotate float rotation = time - rotationStartTime; // Want to apply easing to this so it slows towards end of spin float tween = easeOutQuad(rotation, 0.0f, maxRotation, tweenLength); // Don't let us go past 360 degrees (2 pi radians) if (tween >= maxRotation || rotation >= tweenLength){ rotationStartTime = numeric_limits<float>::lowest(); rotation = 0.0f; cout << "Stopping rotation" << endl; } glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr( glm::rotate(model, tween, glm::vec3(1.0f, 0.0f, 0.0f)) )); } glDrawElements(GL_TRIANGLES, sizeof(elements), GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); frames++; } // Calculate average frames per second float endTime = glfwGetTime(); float fps = frames/(endTime - startTime); float mspf = ((endTime - startTime) * 1000) / frames; cout << "FPS: " << fps << " over " << (endTime-startTime) << " seconds." << endl; cout << "MSPF: " << mspf << " over " << frames << " frames." << endl; // Cleanup glDeleteProgram(shaderProgram); glDeleteShader(fragmentShader); glDeleteShader(vertexShader); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); // Cleanup GLFW glfwDestroyWindow(window); glfwTerminate(); return 0; }
6a8c3677d0c4cb088db24aabb554d478a23becfa
[ "Makefile", "C++" ]
2
Makefile
sillypog/CraftCpp
880bd95ba4fcca33267d8a9b1bcde22d63504c52
856f4da26f11954451e333d40aa89c66b12b1e64
refs/heads/master
<repo_name>77shell/dev-driver-practice<file_sep>/oled-ssd1308/am335/Makefile.inc CORTEX_FLAGS := -march=armv7-a -marm -mthumb-interwork -mfloat-abi=hard -mfpu=neon -mtune=cortex-a8 KDIR := ~/triton/board-support/ti-linux-kernel-4.1.y #SDK := ${HOME}/triton/toolchain/gcc-linaro-4.9-2015.05-x86_64_arm-linux-gnueabihf/arm-linux-gnueabihf SDK :=~/triton/toolchain/gcc-linaro-5.3.1-2016.05-x86_64_arm-linux-gnueabihf/arm-linux-gnueabihf CFLAGS := $(CORTEX_FLAGS) LIBSPATH := INCLUDEPATH := -I${SDK}/include CROSS_COMPILE := arm-linux-gnueabihf- CXX := $(CROSS_COMPILE)g++ CC := $(CROSS_COMPILE)gcc AR := $(CROSS_COMPILE)ar KBUILD_VERBOSE:= 0 export <file_sep>/oled-ssd1308/am335/setup.sh #!/bin/bash export SDK_DIR="${HOME}/triton/toolchain/gcc-linaro-4.9-2015.05-x86_64_arm-linux-gnueabihf" export PATH="$PATH:${SDK_DIR}/bin" export REMOTE_DIR=~/remote/tpsbuserver-prj/GigaController/FW/modules <file_sep>/oled-ssd1308/am335/Makefile # # # 2016-July-06 # Max <<EMAIL>> # # To build kernel module # include $(PWD)/Makefile.inc obj-m := cdata.o \ cdata_plat_dev.o \ cdata_fb_ssd1308.o \ cdata_fb_plat_dev.o \ oled_plat_dev.o \ oled_ssd1308.o cdata-y := ../cdata.o cdata_plat_dev-y := ../cdata_plat_dev.o cdata_fb_ssd1308-y := ../cdata_fb_ssd1308.o cdata_fb_plat_dev-y := ../cdata_fb_plat_dev.o oled_plat_dev-y := ../oled_plat_dev.o oled_ssd1308-y := ../oled_ssd1308_spi.o \ ../oled_ssd1308_ctrl.o \ ../oled_ssd1308_gpio.o \ ../oled_ssd1308_attr.o # turn on pr_debug() #CFLAGS_oled_ssd1308_spi.o += -DDEBUG #CFLAGS_oled_ssd1308_ctrl.o += -DDEBUG #CFLAGS_oled_ssd1308_gpio.o += -DDEBUG PWD := $(shell pwd) .PHONY: all all: @echo "\033[33m\tPWD : $(PWD)\033[0m" @echo "\033[33m\tCFLAG : $(CFLAGS)\033[0m" @echo "\033[33m\tCC : $(CC)\033[0m" @echo "\033[33m\tKDIR : $(KDIR)\033[0m" @echo "\033[33m\tobj-m : $(obj-m)\033[0m" @echo "\033[33m\toled_ssd1308-y : $(oled_ssd1308-y)\033[0m" $(MAKE) ARCH=arm -C $(KDIR) M=`pwd` modules clean: rm -rf ../*.o *.o *.ko .*cmd modules.* Module.* .tmp_versions *.mod.c .#* *~ .tmp_versions .PHONY: TAGS TAGS: rm -rf TAGS find ../ -regextype posix-egrep -iregex '.*\.(cpp|c|h)' | xargs etags -a find ~/triton/toolchain/gcc-linaro-4.9-2015.05-x86_64_arm-linux-gnueabihf/arm-linux-gnueabihf/include \ -type f | xargs etags -a find . -iname 'Makefile.*' -type f | xargs etags -a <file_sep>/cdata/VAR.sh #!/bin/bash declare -a DEVICE_NODES=( /dev/cdata-misc /dev/cdata-fb /dev/cdata.0 # /dev/oled-ssd1308 ) declare -a SYS_NODES=( /sys/devices/platform/cdata.0 # /sys/devices/platform/cdata-fb.0 # /sys/devices/platform/oled.0 ) # # Register platform driver first # then register platform device # declare -a KO=( cdata.ko cdata_plat_dev.ko # cdata_fb_ssd1308.ko # cdata_fb_plat_dev.ko # oled_ssd1308_spi.ko # oled_plat_dev.ko ) mesg_brown() { echo -e "\033[33m$1\033[0m" } mesg_red() { echo -e "\033[31m$1\033[0m" } mesg_green() { echo -e "\033[32m$1\033[0m" } error_msg() { echo -e "\033[31mErrooooor: $1\033[0m" } <file_sep>/test/test-oled-ssd1308-r1.cpp /************************************************************** * Name : test-oled-ssd1308.c * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : Test driver : oled-ssd1308 * * * History: ysh 7-28-2016 Create *************************************************************/ extern "C" { #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stropts.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/mman.h> #include <pthread.h> #include <linux/input.h> #include "oled_ssd1308_ioctl.h" } extern "C" { void open_input_event_device(void); void close_input_event_device(void); } #define __SYS_CALL_FSYNC sig_atomic_t child_exit_status; static void print_usage(FILE *stream) { fprintf(stream, "\nUsage: OLED test utility\n"); fprintf(stream, "SYSNOPSIS:\n" " test-oled-ssd1308\n" "\t-c\tclear screen\n" "\t-o\tturn on screen\n" "\t-i\tturn off screen\n" "\t-f feed-byte\tfeed screen with BYTE\n" "\t-r\treset screen\n" "\t-t\ttest times\n" "\t-u\tflush rate (ms)\n" "\t-m feed-byte\ttest mmap()\n" ); exit(0); } struct Threadpara_t { int fd; int row; unsigned char feed; pthread_t th_id; pthread_mutex_t mutex; }; static void* _thread_test_mmap(void *ptr) { struct Threadpara_t *th = (struct Threadpara_t*)ptr; size_t i, j, k, len = 128 * 64 / 8; size_t row_len = 128, row_start = th->row * row_len, row_end = row_start + row_len - 1; size_t grey_area = 0, grey_area_width = 8, grey_area_start = th->row * grey_area_width, grey_area_end; unsigned char *map; bool quit; const useconds_t _1s = 1000000; unsigned char a, b; map = (unsigned char*)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, th->fd, 0); if (map == MAP_FAILED) { printf("mmap() failed!\n"); return (void*)-1; } printf("map : %p, feed : 0x%X\n", map, th->feed); k = th->row; for (quit = false; !quit;) { if (pthread_mutex_trylock(&th->mutex) == 0) quit = true; #if 0 /* Bar */ for (j = 0; j < len; j++) { if (j == grey_area) { size_t i = 0; for (i = 0; i < 64; i++, j++) map[j] = 0; } else { map[j] = th->feed; } } grey_area += 64; if (grey_area >= len) grey_area = 0; #elif 0 /* Wave */ for (j=row_start; j<=row_end; j++) map[j] = 0xff; grey_area_start += grey_area_width; grey_area_start %= row_len; grey_area_end = grey_area_start + grey_area_width; j = row_start + grey_area_start; k = j + grey_area_width; for (; j<k; j++) map[j] = 0; #else /* Chess board */ j = row_start; k++; if (k % 2) { a = th->feed; b = 0; } else { a = 0; b = th->feed; } for (; j<=row_end; j++) { for (i=0; i<8; i++, j++) map[j] = a; if (j >= row_end) break; for (i=0; i<8; i++, j++) map[j] = b; } #endif #define LAST_ROW_INDEX 7 #ifdef __SYS_CALL_FSYNC if(th->row == LAST_ROW_INDEX) fsync(th->fd); #else if(th->row == LAST_ROW_INDEX) ioctl(th->fd, OLED_FLUSH_PANEL); #endif usleep(_1s); } munmap(map, len); printf("Thread (0x%lX) was terminated!\n", th->th_id); return (void*)0; } void clean_up_child_proc(int sig_number, siginfo_t *info, void *p) { /* Clean up the child process */ int status; pid_t child_pid; child_pid = wait(&status); printf("%s: Child PID %d\n", __func__, child_pid); child_exit_status = status; } int main(int argc, char *argv[]) { int fd, i, opt; char write_data[20] = { 0 }; ssize_t ret; const char *dev = "/dev/oled-ssd1308"; pid_t child; struct sigaction sigchld_action; const useconds_t _1s = 1000000; /* * If child process completes earlier than parent process, * Child process becomes a zombie process, parent process has to * clean up child process by calling wait(). */ memset(&sigchld_action, 0, sizeof(struct sigaction)); sigchld_action.sa_sigaction = clean_up_child_proc; sigaction (SIGCHLD, &sigchld_action, NULL); #if 0 child = fork(); if (child == 0) strcpy(write_data, "I'm a child"); else strcpy(write_data, "I'm parent"); #endif if ( (fd = open(dev, O_RDWR)) == -1 ) { fprintf(stderr, "Open %s failed~\n", dev); exit(EXIT_FAILURE); } fprintf(stderr, "Open %s successful!\n", dev); while( (opt = getopt(argc, argv, ":rct:oif:u:m:")) != -1 ) { switch(opt) { case ':': case '?': print_usage(stderr); break; case 'c': ioctl(fd, OLED_CLEAR); break; case 'o': ioctl(fd, OLED_ON); break; case 'i': ioctl(fd, OLED_OFF); break; case 'r': ioctl(fd, OLED_RESET); break; case 'f': { unsigned char feed; feed = (unsigned char)atoi(optarg); ioctl(fd, OLED_FEED, &feed); printf("Feed byte: 0x%X\n", feed); } break; case 't': { int run = atoi(optarg); printf("Run test %d times\n", run); for (i=0; i<run; i++) { unsigned char b = (unsigned char)i; ret = write(fd, &b, sizeof(unsigned char)); printf("%s : %d\n", __func__, i); usleep(_1s / 2); } } break; case 'u': { unsigned long rate; rate = (unsigned long)atoi(optarg); ioctl(fd, OLED_FLUSH_RATE, rate); printf("Flush rate : %lums\n", rate); } break; case 'm': { int i, c; const int thread_nr = 8; struct Threadpara_t para[thread_nr]; unsigned char feed = (unsigned char)atoi(optarg); int event; open_input_event_device(); for (i=0; i<thread_nr; i++) { para[i].fd = fd; para[i].row = i; para[i].feed = feed; pthread_mutex_init(&para[i].mutex, NULL); pthread_mutex_lock(&para[i].mutex); } for (i=0; i<thread_nr; i++) pthread_create(&para[i].th_id, NULL, &_thread_test_mmap, (void*)&para[i]); while ((c=getchar()) != 'a') { printf("getchar() = %c\n", c); usleep(_1s); } for (i=0; i<thread_nr; i++) pthread_mutex_unlock(&para[i].mutex); for (i=0; i<thread_nr; i++) pthread_join(para[i].th_id, (void**)&event); for (i=0; i<thread_nr; i++) pthread_mutex_destroy(&para[i].mutex); close_input_event_device(); } break; default: break; } } printf("Press any key to quit!"); getchar(); close(fd); exit(EXIT_SUCCESS); } <file_sep>/oled-ssd1308/oled_ssd1308_ctrl.c /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : MISC category driver for test OLED-SSD1308 * * * History: ysh 7-25-2016 Create *************************************************************/ #include <linux/delay.h> #include <linux/gpio.h> #include <linux/spi/spi.h> #include <linux/err.h> #include "oled_ssd1308_spi.h" #undef pr_fmt #define pr_fmt(fmt) "%s:"fmt enum DataCmd_e { eCommand, eData }; static int _spi_tx(u8 byte); static int _spi_tx_batch(u8 *pdata, ssize_t len); static void _set_dataMode(void); static void _set_cmdMode(void); static void _set_dc_pin(enum DataCmd_e data_cmd); static void _write_cmd(u8 cmd); static void _write_data_batch(u8 *pData, ssize_t len); static void _set_page_addr(u8 page); static void _set_lower_addr(u8 low); static void _set_high_addr(u8 high); static void _raise_reset(void); static void _release_reset(void); static u8 rotate(u8 x); static struct oled_platform_data_t *pOLED; static int _spi_tx(u8 byte) { int ret; if (IS_ERR(pOLED->spi)) return PTR_ERR(pOLED->spi); ret = spi_write(pOLED->spi, &byte, sizeof(u8)); if (ret) printk(KERN_WARNING "%s: error\n", __func__); return ret; } static int _spi_tx_batch(u8 *pData, ssize_t len) { int ret; if (IS_ERR(pOLED->spi)) return PTR_ERR(pOLED->spi); ret = spi_write(pOLED->spi, pData, len); if (ret) printk(KERN_WARNING "%s: error\n", __func__); return ret; } static void _set_dataMode(void) { gpio_set_value(pOLED->ad_pin, 1); } static void _set_cmdMode(void) { gpio_set_value(pOLED->ad_pin, 0); } static void _set_dc_pin(enum DataCmd_e data_cmd) { if(data_cmd == eCommand) _set_cmdMode(); else /* data_cmd == eData */ _set_dataMode(); } static void _write_cmd(u8 cmd) { _set_dc_pin(eCommand); _spi_tx(cmd); } void _write_data_batch(u8 *pData, ssize_t len) { _set_dc_pin(eData); _spi_tx_batch(pData, len); } void oled_on() { _write_cmd(0xafu); } void oled_off() { _write_cmd(0xaeu); } static void _set_page_addr(u8 page) { _write_cmd((page & 0x0fu) + 0xb0u); } static void _set_lower_addr(u8 low) { _write_cmd(low & 0x0fu); } static void _set_high_addr(u8 high) { _write_cmd((high & 0x0fu) + 0x10u); } static void _raise_reset() { gpio_set_value(pOLED->reset_pin, 0); } static void _release_reset() { gpio_set_value(pOLED->reset_pin, 1); } void oled_reset() { _raise_reset(); mdelay(1); _release_reset(); /* Sleep mode : AEh */ _write_cmd(0xaeu); /* display off */ _write_cmd(0xd5u); /* Set Display clocDivide Ratio/Oscillator Frequency */ _write_cmd(0x80u); /* 105Hz */ _write_cmd(0xa8u); /* Set Multiplex ratio */ _write_cmd(0x3fu); /* Set 64 mux */ _write_cmd(0xd9u); /* Set Pre-charge Period */ _write_cmd(0x22u); /* Default value */ _write_cmd(0x20u); /* Set Memory Addressing Mode */ _write_cmd(0x00u); /* Default value */ _write_cmd(0xa0u); /* 0xa0: seg re-map 0-->127; 0xa1: seg re-map 127-->0 */ _write_cmd(0xc0u); /* 0xc0: com scan direction COM0-->COM(N-1); 0xc8: com scan direction COM(N-1)-->COM0 */ _write_cmd(0xdau); /* Set Com Pins Hardware Configuration */ _write_cmd(0x12u); /* Default value */ _write_cmd(0xadu); /* External or Internal Iref Selection */ _write_cmd(0x00u); /* 0x00: External Iref ; 0x10: Internal Iref*/ _write_cmd(0x81u); /* Set Contrast Control */ _write_cmd(0x50u); /* 1..256£¬adjust in application */ _write_cmd(0xb0u); /* Set Page start Address for Page Addressing Monde */ _write_cmd(0xd3u); /* Set Display Offset */ _write_cmd(0x00u); /* offset=0, The value is default */ _write_cmd(0x21u); /* Set Column Address */ _write_cmd(0x00u); /* Column Start Address */ _write_cmd(0x7fu); /* Column End Address */ _write_cmd(0x22u); /* Set Page Address */ _write_cmd(0x00u); /* Page Start Address */ _write_cmd(0x07u); /* Page End Address */ _write_cmd(0x10u); /* Set Higher Column Start Address for Page Addressing Mode */ _write_cmd(0u); /* Set Lower Column Start Address for Page Addressing Mode */ _write_cmd(0x40u); /* Set Display Start Line */ _write_cmd(0xa6u); /* 0xa6: Display Normal; 0xa7: Display Inverse */ _write_cmd(0xa4u); /* 0xa4: Resume to RAM content display; 0xa5: Display 0xa5, ignores RAM content */ _write_cmd(0xdbu); /* Set VCOMH Level */ _write_cmd(0x30u); /* 0x00: 0.65Vcc; 0x20: 0.77Vcc; 0x30: 0.83Vcc */ oled_on(); printk(KERN_INFO "%s: complete\n", __func__); } void oled_flush() { ssize_t page, page_nr, pixel_x, fb_len, i, j; u8 *fb, *src_pg, *des_pg; pr_debug("enter\n", __func__); page_nr = pOLED->page_nr; pixel_x = pOLED->pixel_x; fb_len = pOLED->fb_size; if (pOLED->reverse_pixel) { for (i=0; i<fb_len; i++) pOLED->fb_reverse[i] = ~pOLED->fb[i]; fb = pOLED->fb_reverse; } else { fb = pOLED->fb; } if (pOLED->rotate == 180) { u8 pg_buf[pixel_x]; /* * Upside down */ for(page=0; page<page_nr/2; page++) { src_pg = fb + page * pixel_x; des_pg = pOLED->fb_rotate + (page_nr - page - 1) * pixel_x; for(j=0; j<pixel_x; j++) pg_buf[j] = rotate(src_pg[j]); /* * Rotate horizontally */ j = pixel_x - 1; for(i=0; i<pixel_x; i++, j--) des_pg[i] = pg_buf[j]; } for(; page<page_nr; page++) { src_pg = fb + page * pixel_x; des_pg = pOLED->fb_rotate + (page_nr - page - 1) * pixel_x; for(j=0; j<pixel_x; j++) pg_buf[j] = rotate(src_pg[j]); /* * Rotate horizontally */ j = pixel_x - 1; for(i=0; i<pixel_x; i++, j--) des_pg[i] = pg_buf[j]; } fb = pOLED->fb_rotate; } if (IS_ERR(fb)) { printk(KERN_WARNING "%s: fb error\n", __func__); return; } for(page=0; page<page_nr; page++) { _set_page_addr(page); _set_lower_addr(0); _set_high_addr(0); _write_data_batch(fb + page * pixel_x, pixel_x); } pr_debug("exit\n", __func__); } void oled_paint(u8 byte) { ssize_t page, page_offset, pixel, page_nr, pixel_x; u8 *fb; // down_interruptible(&pOLED->sem); pr_debug("enter\n", __func__); page_nr = pOLED->page_nr; pixel_x = pOLED->pixel_x; fb = pOLED->fb; if (IS_ERR(fb)) { printk(KERN_WARNING "%s: fb error\n", __func__); return; } for(page=0; page<page_nr; page++) { page_offset = page * pixel_x; pr_debug("page_offset: %d\n", __func__, page_offset); for(pixel=0; pixel<pixel_x; pixel++) fb[page_offset + pixel] = byte; } pr_debug("data copying done\n", __func__); // up(&pOLED->sem); pr_debug("exit\n", __func__); } void oled_init(struct oled_platform_data_t *oled) { pr_debug("enter\n", __func__); pOLED = oled; sema_init(&pOLED->sem, 1); oled_reset(); pr_debug("exit\n", __func__); } static u8 rotate(u8 x) { x = (x>>4)|(x<<4); x = ((x & 0xcc) >> 2) | ((x & 0x33)<<2); x = ((x & 0xaa) >> 1) | ((x & 0x55)<<1); return x; } <file_sep>/cdata/rmmod.sh #!/bin/bash . ./VAR.sh for i in ${KO[@]} do if sudo rmmod $i; then mesg_green "Uninstall module: $i" else mesg_red "Uninstall driver: $i failed~" fi done ls -l /dev/cdata* --color=auto <file_sep>/test/test-fb-ssd1308.c /***************************************************************** * Copyright (c) 2016 Delta Products * * THIS IS UNPUBLISHED PROPRIETARY TRADE SECRET SOURCE CODE OF * Delta Products * * The copyright above and this notice must be preserved in all copies of this * source code. The copyright notice above does not evidence any actual or * intended publication of such source code. This source code may not be * copied, disclosed, distributed, demonstrated or licensed except as expressly * authorized by Delta Products. ****************************************************************/ /************************************************************** * Name : test-fb-ssd1308.c * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : Test driver : cdata-fb-ssd1308 * * * History: ysh 7-07-2016 Create *************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> sig_atomic_t child_exit_status; void clean_up_child_proc(int sig_number, siginfo_t *info, void *p) { /* Clean up the child process */ int status; pid_t child_pid; child_pid = wait(&status); printf("%s: Child PID %d\n", __func__, child_pid); child_exit_status = status; } int main(int argc, char *argv[]) { int fd; char write_data[20] = { 0 }; ssize_t ret; char *dev = "/dev/cdata-fb"; pid_t child; struct sigaction sigchld_action; /* * If child process completes earlier than parent process, * Child process becomes a zombie process, parent process has to * clean up child process by calling wait(). */ memset(&sigchld_action, 0, sizeof(struct sigaction)); sigchld_action.sa_sigaction = clean_up_child_proc; sigaction (SIGCHLD, &sigchld_action, NULL); child = fork(); if (child == 0) strcpy(write_data, "I'm a child"); else strcpy(write_data, "I'm parent"); if ( (fd = open(dev, O_RDWR)) == -1 ) { fprintf(stderr, "Open %s failed~\n", dev); exit(EXIT_FAILURE); } fprintf(stderr, "Open %s successful!\n", dev); #if 0 child = fork(); if (child == 0) strcpy(write_data, "I'm a child"); else strcpy(write_data, "I'm parent"); #endif ret = write(fd, write_data, sizeof write_data); printf("%s : %d\n", write_data, ret); close(fd); exit(EXIT_SUCCESS); } <file_sep>/test/test.c #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #include "../cdata_ioctl.h" static void print_usage() { puts("test -d /dev/cdata.0"); } int main(int argc, char *argv[]) { int fd, i, opt; pid_t child; char str[20]; char *dev = "/dev/cdata.0"; useconds_t us; const useconds_t _100ms = 100000; const useconds_t _10ms = 10000; const useconds_t _1ms = 1000; while( (opt = getopt(argc, argv, "d:")) != -1 ) { switch(opt) { case ':': case '?': print_usage(); exit(EXIT_SUCCESS); case 'd': dev = optarg; printf("Device: %s\n", dev); break; } } strcpy(str, "______"); if ( (fd = open(dev, O_RDWR)) == -1) { fprintf(stderr, "Open %s failed~\n", dev); exit(EXIT_FAILURE); } child = fork(); printf("Child: %d\n", child); if(child) strcpy(str, "******"); //ioctl(fd, IOCTL_SYNC, 1); for(i=0; i<100; i++) { write(fd, (void *)str, strlen(str)); //usleep(_100ms); } printf("complete %d\n", child); //ioctl(fd, IOCTL_SYNC, 3); //ioctl(fd, IOCTL_EMPTY, 2); close(fd); exit(EXIT_SUCCESS); } <file_sep>/test/am335/build.sh #!/bin/bash # # 2016-7-07 # <EMAIL> # PROJ_ROOT=../.. error_msg() { echo -e "\033[31mErrooooor~ $1\033[0m" } declare -a TEST_APP=( test test-fb-ssd1308 test-oled-ssd1308 ) copy_files_to_remote() { if ! [ -d $REMOTE_DIR ]; then error_msg $REMOTE_DIR exit 1 fi # # Test applications # for i in ${TEST_APP[@]} do ! cp $i $REMOTE_DIR && \ error_msg $1 done echo -e "\033[33m$REMOTE_DIR\033[0m" ls -l $REMOTE_DIR --color } . ${PROJ_ROOT}/am335/setup.sh case $1 in install) copy_files_to_remote exit 0 ;; clean) make clean exit 0 ;; *) make V=0 ls -l --color echo -e "\033[33m\n\t./built.sh [ install | clean ]\n\033[0m" esac <file_sep>/oled-ssd1308/am335/rmmod.sh #!/bin/bash # # 2016-7-07 # <EMAIL> # # Uninstall kernel modules: # > cdata.ko # > cdata_plat_dev.ko # > cdata_fb_ssd1308.ko # > cdata_fb_plat_dev.ko # error_msg() { echo -e "\033[31mErrooooor: $1\033[0m" } declare -a DEVICE_NODES=( /dev/cdata-misc /dev/cdata-fb ) declare -a KO=( # cdata_plat_dev.ko # cdata.ko # cdata_fb_plat_dev.ko # cdata_fb_ssd1308.ko oled_ssd1308.ko oled_plat_dev.ko ) for i in ${KO[@]} do ! rmmod $i && \ error_msg $i done for i in ${DEVICE_NODES[@]} do [ -e $i ] && \ error_msg "$i is still there~" && \ exit 1 done echo -e "\033[33m" lsmod echo -e "\nUninstall modules\033[0m" <file_sep>/cdata/cdata_ioctl.h #ifndef _CDATA_IOCTL #define _CDATA_IOCTL #include <linux/ioctl.h> #define IOCTL_EMPTY _IO(0xaa, 0) #define IOCTL_SYNC _IO(0xaa, 1) #define IOCTL_NAME _IOW(0xaa, 2, char*) #define IOCTL_WRITE _IOR(0xaa, 3, char*) #endif <file_sep>/Makefile # # 2016-April-23 # Max <<EMAIL>> # # To build kernel module # > cdata.ko # > cdata_plat_dev.ko # > cdata_fb.ko # > cdata_fb_plat_dev.ko # obj-m := cdata.o \ cdata_plat_dev.o \ cdata_fb_ssd1308.o \ cdata_fb_plat_dev.o \ oled_plat_dev.o \ oled_ssd1308.o oled_ssd1308-objs := oled_ssd1308_spi.o \ oled_ssd1308_ctrl.o \ oled_ssd1308_gpio.o KDIR := /usr/src/linux-headers-$(shell uname -r) PWD := $(shell pwd) ccflag-y += "-iquote./" default: $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules clean: rm -rf *.o *.ko .*cmd modules.* Module.* .tmp_versions *.mod.c .#* *~ .PHONY: TAGS TAGS: rm -rf TAGS find . -regextype posix-egrep -iregex '.*\.(cpp|c|h)' | xargs etags -a find . -iname Makefile.* | xargs etags -a <file_sep>/cdata/cdata.c /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : Demostrate device driver * * * History: ysh 4-23-2016 Create *************************************************************/ #include <linux/module.h> #include <linux/version.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/delay.h> #include <linux/vmalloc.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/miscdevice.h> #include <linux/input.h> #include <linux/wait.h> #include <linux/platform_device.h> #include <asm/io.h> #include <asm/uaccess.h> #include <linux/slab.h> #include <linux/timer.h> #include "cdata_ioctl.h" #define CDATA_MAJOR 121 #define BUFSIZE 32 #define TIMEOUT_VALUE (1*HZ) //#define __WORK_QUEUE //#define __TIMER #define __TASKLET // #define __MKNOD #define __PLAT_DRIVER #if defined(__WORK_QUEUE) #undef __TIMER #undef __TASKLET #elif defined(__TIMER) #undef __WORK_QUEUE #undef __TASKLET #elif defined(__TASKLET) #undef __WORK_QUEUE #undef __TIMER #endif struct cdata_t { char *buf; unsigned int index; wait_queue_head_t write_queue; struct work_struct work; struct timer_list timer; struct tasklet_struct tasklet; spinlock_t spinlock; }; #ifdef __WORK_QUEUE static void wq_flush_data(struct work_struct *pWork) { struct cdata_t *cdata; int i; #if 1 printk(KERN_INFO "%s: in_softirq(): %s", __func__, in_softirq() ? "YES" : "NO"); printk(KERN_INFO "%s: in_interrupt(): %s", __func__, in_interrupt() ? "YES" : "NO"); printk(KERN_INFO "%s: in_serving_softirq(): %s", __func__, in_serving_softirq() ? "YES" : "NO"); #endif cdata = container_of(pWork, struct cdata_t, work); printk(KERN_INFO "%s: %s", __func__, cdata->buf); //spin_lock(&cdata->spinlock); { cdata->index = 0; for (i=0; i<BUFSIZE; i++) cdata->buf[i] = 0; } //spin_unlock(&cdata->spinlock); wake_up(&cdata->write_queue); } #endif #ifdef __TIMER static void timer_handle(unsigned long data) { struct cdata_t *cdata = (struct cdata_t*)data; int i; #if 1 printk(KERN_INFO "%s: in_softirq(): %s", __func__, in_softirq() ? "YES" : "NO"); printk(KERN_INFO "%s: in_interrupt(): %s", __func__, in_interrupt() ? "YES" : "NO"); printk(KERN_INFO "%s: in_serving_softirq(): %s", __func__, in_serving_softirq() ? "YES" : "NO"); #endif //printk(KERN_INFO "%s: %s", __func__, cdata->buf); printk(KERN_INFO "%s: cdata->index: %d", __func__, cdata->index); cdata->index = 0; for (i=0; i<BUFSIZE; i++) cdata->buf[i] = 0; if(cdata->index == 0) wake_up(&cdata->write_queue); } #endif /* __TIMER */ #ifdef __TASKLET static void tasklet_func(unsigned long data) { struct cdata_t *cdata = (struct cdata_t*)data; int i; #if 0 printk(KERN_INFO "%s: in_softirq(): %s", __func__, in_softirq() ? "YES" : "NO"); printk(KERN_INFO "%s: in_interrupt(): %s", __func__, in_interrupt() ? "YES" : "NO"); printk(KERN_INFO "%s: in_serving_softirq(): %s", __func__, in_serving_softirq() ? "YES" : "NO"); #else printk(KERN_INFO "%s: in_softirq(): %s\tin_interrupt(): %s\tin_serving_softirq(): %s", __func__, in_softirq() ? "YES" : "NO", in_interrupt() ? "YES" : "NO", in_serving_softirq() ? "YES" : "NO"); #endif printk(KERN_INFO "%s: consuming data, %s", __func__, cdata->buf); cdata->index = 0; for (i=0; i<BUFSIZE; i++) cdata->buf[i] = 0; wake_up(&cdata->write_queue); } #endif /* __TASKLET */ static int cdata_open(struct inode *inode, struct file *filp) { struct cdata_t *cdata; int i; /* Allocate memory to private_data */ cdata = kmalloc(sizeof(struct cdata_t), GFP_KERNEL); filp->private_data = cdata; cdata->buf = kmalloc(BUFSIZE, GFP_KERNEL); /* Init cdata_t content */ { cdata->index = 0; for (i=0; i<BUFSIZE; i++) cdata->buf[i] = 0; } init_waitqueue_head(&cdata->write_queue); spin_lock_init(&cdata->spinlock); #ifdef __WORK_QUEUE printk(KERN_INFO "%s: BH, Apply work queue\n", __func__); INIT_WORK(&cdata->work, wq_flush_data); #elif defined(__TIMER) /* Init timer */ { printk(KERN_ALERT "%s: BH, Apply timer\n", __func__); struct timer_list *pTimer; pTimer = &cdata->timer; init_timer(pTimer); pTimer->function = timer_handle; pTimer->data = (unsigned long)cdata; } #elif defined(__TASKLET) /* Init tasklet */ { printk(KERN_ALERT "%s: BH, Apply tasklet\n", __func__); tasklet_init(&cdata->tasklet, tasklet_func, (unsigned long)cdata); } #endif printk(KERN_ALERT "%s: cdata in open: filp = %p\n", __func__, filp); return 0; } static ssize_t cdata_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { struct cdata_t *cdata; char *file_buf; unsigned int data_index; cdata = filp->private_data; file_buf = cdata->buf; repeat: data_index = cdata->index; if (data_index + count >= BUFSIZE) { #if 0 /* * Traditional way of doing process scheduling * 1. Change current process state * 2. Put to wait-queue * 3. Call scheduler */ current->state = TASK_UNINTERRUPTIBLE; add_wait_queue(); schedule(); #endif #if 0 /* * Upon three statements can be replaced by following statement. * But this is not an atomic operaton, so it could result some problems. */ interrupt_sleep_on(&cdata->write_queue); #endif //schedule_work(&cdata->work); //schedule_work_on(0, &cdata->work); #ifdef __WORK_QUEUE schedule_work(&cdata->work); /* * Schedule work to a specific CPU */ // schedule_work_on(1, &cdata->work); #elif defined __TIMER cdata->timer.expires = jiffies + TIMEOUT_VALUE; add_timer(&cdata->timer); #elif defined __TASKLET tasklet_schedule(&cdata->tasklet); #endif /* * How does the event be checked? and how long? * * It was checked after calling wake_up(). * */ printk(KERN_INFO "PID:%i %s: wait_event_interruptible(), cdata->index: %d\n", current->pid, __func__, cdata->index); wait_event_interruptible(cdata->write_queue, cdata->index + count < BUFSIZE); goto repeat; /* Don't return -ENOTTY * It's inappropriate design. */ // return -ENOTTY; } if (copy_from_user(&file_buf[data_index], buf, count)) return 0; cdata->index += count; printk(KERN_INFO "PID:%i %s: write %d-byte, buffer-index: %d\n", current->pid, __func__, count, cdata->index); return count; } static long cdata_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { char *msg, *buf; struct cdata_t *p; unsigned int i, index; p = (struct cdata_t *)filp->private_data; buf = p->buf; index = p->index; switch (cmd) { case IOCTL_EMPTY: printk(KERN_ALERT "%s: empty: arg: %ld\n", __func__, arg); for (i=0; i<BUFSIZE; i++) buf[i] = 0; p->index = 0; return 0; case IOCTL_SYNC: printk(KERN_ALERT "%s sync: Buffer content: %s\n", __func__, buf); return 0; default: msg = "Unknow command"; return -ENOTTY; } return 0; } static int cdata_close(struct inode *inode, struct file *filp) { struct cdata_t *p; #ifdef __TIMER int ret; #endif p = filp->private_data; #ifdef __TIMER ret = del_timer_sync(&p->timer); if (ret == 0) printk(KERN_INFO "%s: timer has already been removed.\n", __func__); else if (ret > 0) printk(KERN_INFO "%s: timer has been removed before closing.\n", __func__); #endif printk(KERN_INFO "%s: Free cdata %s\n", __func__, p->buf); kfree(p->buf); kfree(p); return 0; } static struct file_operations cdata_fops = { owner: THIS_MODULE, open: cdata_open, write: cdata_write, // compat_ioctl: cdata_ioctl, unlocked_ioctl: cdata_ioctl, release: cdata_close }; #if !defined(__MKNOD) || defined(__PLAT_DRIVER) static struct miscdevice cdata_miscdev = { .minor = 199, /* Refer to miscdevice.h */ .name = "cdata.0", .fops = &cdata_fops /* .nodename = "cdata" */ }; #endif #ifdef __PLAT_DRIVER static int cdata_plat_probe(struct platform_device *dev) { int ret; ret = misc_register(&cdata_miscdev); if(ret < 0) { printk(KERN_ALERT "%s: registering failed\n", __func__); return -1; } printk(KERN_ALERT "%s: register MISC successful\n", __func__); return 0; } #endif #ifdef __PLAT_DRIVER static int cdata_plat_remove(struct platform_device *dev) { misc_deregister(&cdata_miscdev); printk(KERN_ALERT "%s: cdata was unregisted.\n", __func__); return 0; } #endif #ifdef __PLAT_DRIVER static struct platform_driver cdata_plat_driver = { .driver = { .name = "cdata", .owner = THIS_MODULE }, .probe = cdata_plat_probe, .remove = cdata_plat_remove }; #endif int __init cdata_init_module(void) { #ifdef __MKNOD if (register_chrdev(CDATA_MAJOR, "cdata", &cdata_fops)) { printk(KERN_ALERT "%s: cdata module: can't registered.\n", __func__); } #elif defined( __PLAT_DRIVER) platform_driver_register(&cdata_plat_driver); printk(KERN_INFO "%s: register platform driver successful\n", __func__); #else int ret; ret = misc_register(&cdata_miscdev); if(ret < 0) printk(KERN_ALERT "%s: registering failed\n", __func__); printk(KERN_ALERT "%s: register MISC successful\n", __func__); #endif return 0; } void __exit cdata_cleanup_module(void) { #ifdef __MKNOD unregister_chrdev(CDATA_MAJOR, "cdata"); printk(KERN_ALERT "cdata module: unregisterd.\n"); #elif defined(__PLAT_DRIVER) platform_driver_unregister(&cdata_plat_driver); printk(KERN_ALERT "%s: platform driver was unregisted.\n", __func__); #else misc_deregister(&cdata_miscdev); printk(KERN_ALERT "%s: MISC cdata was unregisted.\n", __func__); #endif } module_init(cdata_init_module); module_exit(cdata_cleanup_module); MODULE_LICENSE("GPL"); <file_sep>/oled-ssd1308/am335/print.sh #!/bin/bash cat /sys/class/oled/rotate echo 180 > /sys/class/oled/rotate <file_sep>/test/test-oled-ssd1308.c /************************************************************** * Name : test-oled-ssd1308.c * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : Test driver : oled-ssd1308 * * * History: ysh 7-28-2016 Create *************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stropts.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/mman.h> #include <pthread.h> #include "../oled_ssd1308_ioctl.h" #define __SYS_CALL_FSYNC sig_atomic_t child_exit_status; static void print_usage(FILE *stream) { fprintf(stream, "\nUsage: OLED test utility\n"); fprintf(stream, "SYSNOPSIS:\n" " test-oled-ssd1308\n" "\t-c\tclear screen\n" "\t-o\tturn on screen\n" "\t-i\tturn off screen\n" "\t-f feed-byte\tfeed screen with BYTE\n" "\t-r\treset screen\n" "\t-t\ttest times\n" "\t-u\tflush rate (ms)\n" "\t-m feed-byte\ttest mmap()\n" ); exit(0); } struct Threadpara_t { int fd; int row; unsigned char feed; pthread_t th_id; pthread_mutex_t mutex; }; static void* _thread_test_mmap(void *ptr) { struct Threadpara_t *th = (struct Threadpara_t*)ptr; size_t i, j, k, len = 128 * 64 / 8; size_t row_len = 128, row_start = th->row * row_len, row_end = row_start + row_len - 1; size_t grey_area = 0, grey_area_width = 8, grey_area_start = th->row * grey_area_width, grey_area_end; unsigned char *map; bool quit; const useconds_t _1s = 1000000; unsigned char a, b; map = (unsigned char*)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, th->fd, 0); if (map == MAP_FAILED) { printf("mmap() failed!\n"); return (void*)-1; } printf("map : %p, feed : 0x%X\n", map, th->feed); k = th->row; for (quit = false; !quit;) { if (pthread_mutex_trylock(&th->mutex) == 0) quit = true; #if 0 /* Bar */ for (j = 0; j < len; j++) { if (j == grey_area) { size_t i = 0; for (i = 0; i < 64; i++, j++) map[j] = 0; } else { map[j] = th->feed; } } grey_area += 64; if (grey_area >= len) grey_area = 0; #elif 0 /* Wave */ for (j=row_start; j<=row_end; j++) map[j] = 0xff; grey_area_start += grey_area_width; grey_area_start %= row_len; grey_area_end = grey_area_start + grey_area_width; j = row_start + grey_area_start; k = j + grey_area_width; for (; j<k; j++) map[j] = 0; #else /* Chess board */ j = row_start; k++; if (k % 2) { a = th->feed; b = 0; } else { a = 0; b = th->feed; } for (; j<=row_end; j++) { for (i=0; i<8; i++, j++) map[j] = a; if (j >= row_end) break; for (i=0; i<8; i++, j++) map[j] = b; } #endif #define LAST_ROW_INDEX 7 #ifdef __SYS_CALL_FSYNC if(th->row == LAST_ROW_INDEX) fsync(th->fd); #else if(th->row == LAST_ROW_INDEX) ioctl(th->fd, OLED_FLUSH_PANEL); #endif usleep(_1s); } munmap(map, len); printf("Thread (0x%lX) was terminated!\n", th->th_id); return (void*)0; } void clean_up_child_proc(int sig_number, siginfo_t *info, void *p) { /* Clean up the child process */ int status; pid_t child_pid; child_pid = wait(&status); printf("%s: Child PID %d\n", __func__, child_pid); child_exit_status = status; } int main(int argc, char *argv[]) { int fd, i, opt; char write_data[20] = { 0 }; ssize_t ret; char *dev = "/dev/oled-ssd1308"; pid_t child; struct sigaction sigchld_action; const useconds_t _1s = 1000000; /* * If child process completes earlier than parent process, * Child process becomes a zombie process, parent process has to * clean up child process by calling wait(). */ memset(&sigchld_action, 0, sizeof(struct sigaction)); sigchld_action.sa_sigaction = clean_up_child_proc; sigaction (SIGCHLD, &sigchld_action, NULL); #if 0 child = fork(); if (child == 0) strcpy(write_data, "I'm a child"); else strcpy(write_data, "I'm parent"); #endif if ( (fd = open(dev, O_RDWR)) == -1 ) { fprintf(stderr, "Open %s failed~\n", dev); exit(EXIT_FAILURE); } fprintf(stderr, "Open %s successful!\n", dev); while( (opt = getopt(argc, argv, ":rct:oif:u:m:")) != -1 ) { switch(opt) { case ':': case '?': print_usage(stderr); break; case 'c': ioctl(fd, OLED_CLEAR); break; case 'o': ioctl(fd, OLED_ON); break; case 'i': ioctl(fd, OLED_OFF); break; case 'r': ioctl(fd, OLED_RESET); break; case 'f': { unsigned char feed; feed = (unsigned char)atoi(optarg); ioctl(fd, OLED_FEED, &feed); printf("Feed byte: 0x%X\n", feed); } break; case 't': { int run = atoi(optarg); printf("Run test %d times\n", run); for (i=0; i<run; i++) { unsigned char b = (unsigned char)i; ret = write(fd, &b, sizeof(unsigned char)); printf("%s : %d\n", __func__, i); usleep(_1s / 2); } } break; case 'u': { unsigned long rate; rate = (unsigned long)atoi(optarg); ioctl(fd, OLED_FLUSH_RATE, rate); printf("Flush rate : %lums\n", rate); } break; case 'm': { int i, c; const int thread_nr = 8; struct Threadpara_t para[thread_nr]; unsigned char feed = (unsigned char)atoi(optarg); int event; for (i=0; i<thread_nr; i++) { para[i].fd = fd; para[i].row = i; para[i].feed = feed; pthread_mutex_init(&para[i].mutex, NULL); pthread_mutex_lock(&para[i].mutex); } for (i=0; i<thread_nr; i++) pthread_create(&para[i].th_id, NULL, &_thread_test_mmap, (void*)&para[i]); while ((c=getchar()) != 'a') { printf("getchar() = %c\n", c); usleep(_1s); } for (i=0; i<thread_nr; i++) pthread_mutex_unlock(&para[i].mutex); for (i=0; i<thread_nr; i++) pthread_join(para[i].th_id, (void**)&event); for (i=0; i<thread_nr; i++) pthread_mutex_destroy(&para[i].mutex); } break; default: break; } } printf("Press any key to quit!"); getchar(); close(fd); exit(EXIT_SUCCESS); } <file_sep>/oled-ssd1308/oled_plat_dev.c #include <linux/module.h> #include <linux/platform_device.h> #include <linux/spi/spi.h> #include <linux/slab.h> #include "oled_ssd1308_spi.h" struct oled_platform_data_t oled_platform_data = { .spi = NULL, .pixel_x = 128, .pixel_y = 64, .page_nr = 8, .reset_pin = 114, .ad_pin = 55, .led1_pin = 48, .led2_pin = 58, .reverse_pixel = 0, .rotate = 0, .fb_size = 0, .fb = NULL, .fb_reverse = NULL, .fb_rotate = NULL }; struct spi_board_info oled_board_info[] = { { .modalias = "oled-ssd1308", .platform_data = &oled_platform_data, .mode = SPI_MODE_0, .max_speed_hz = 5000000, .bus_num = 1, /* spidev1.X */ .chip_select = 0, /* spidevY.0 */ .mode = 0, } }; static int oled_plat_dev_init(void) { struct spi_master *master; struct spi_device *spi; #if 1 master = spi_busnum_to_master(oled_board_info[0].bus_num); if (!master) { printk(KERN_WARNING "%s: spi_busnum_to_master() failed~\n", __func__); return -ENODEV; } spi = spi_new_device(master, oled_board_info); if (!spi) { printk(KERN_WARNING "%s: spi_new_device() failed~\n", __func__); return -ENOTTY; } oled_platform_data.spi = spi; #else /* at booting stage, __init */ spi_register_board_info(oled_board_info, ARRAY_SIZE(oled_board_info)); #endif printk(KERN_WARNING "%s: complete\n", __func__); return 0; } static void oled_plat_dev_exit(void) { printk(KERN_INFO "%s\n", __func__); spi_unregister_device(oled_platform_data.spi); } module_init(oled_plat_dev_init); module_exit(oled_plat_dev_exit); MODULE_LICENSE("GPL"); <file_sep>/oled-ssd1308/oled_ssd1308_attr.c #include <linux/device.h> #include "oled_ssd1308_spi.h" extern struct oled_platform_data_t OLED; static ssize_t reverse_show(struct class *class, struct class_attribute *attr, char *buf) { return sprintf(buf, "%ld\n", OLED.reverse_pixel); } static ssize_t reverse_store(struct class *class, struct class_attribute *attr, const char *buf, size_t count) { long l; int ret; ret = kstrtol(buf, 0, &l); if (ret != 0 || l > 1 || l < 0) return 0; printk(KERN_INFO "%s: reverse %ld\n", __func__, l); OLED.reverse_pixel = l; oled_flush(); return 2; } ssize_t resolution_x_show(struct class *class, struct class_attribute *attr, char *buf) { return sprintf(buf, "%d\n", OLED.pixel_x); } ssize_t resolution_y_show(struct class *class, struct class_attribute *attr, char *buf) { return sprintf(buf, "%d\n", OLED.pixel_y); } static ssize_t rotate_show(struct class *class, struct class_attribute *attr, char *buf) { return sprintf(buf, "%d\n", OLED.rotate); } static ssize_t rotate_store(struct class *class, struct class_attribute *attr, const char *buf, size_t count) { long l; int ret; if(strlen(buf) == 0) return 0; ret = kstrtol(buf, 0, &l); if (ret != 0 || l > 360 || l < 0) { printk(KERN_WARNING "%s: invalid value(%ld) for rotatation\n", __func__, l); return 0; } printk(KERN_INFO "%s: rotate %ld degree, count:%d\n", __func__, l, count); OLED.rotate = l; oled_flush(); return count; } //static CLASS_ATTR(reverse, 0555, reverse_show, reverse_store); static CLASS_ATTR_RW(reverse); static CLASS_ATTR_RO(resolution_x); static CLASS_ATTR_RO(resolution_y); static CLASS_ATTR_RW(rotate); static struct class *oled_class; void oled_ssd1308_create_class_attr() { oled_class = class_create(THIS_MODULE, "oled"); if (IS_ERR(oled_class)) { pr_warn("%s: Unable to create OLED class; errno = %ld\n", __func__, PTR_ERR(oled_class)); } else { int error = 0; error = class_create_file(oled_class, &class_attr_reverse); error += class_create_file(oled_class, &class_attr_resolution_x); error += class_create_file(oled_class, &class_attr_resolution_y); error += class_create_file(oled_class, &class_attr_rotate); if(error) printk(KERN_WARNING "%s: create attributes error!\n", __func__); } } void oled_ssd1308_destroy_class_attr() { class_remove_file(oled_class, &class_attr_reverse); class_remove_file(oled_class, &class_attr_resolution_x); class_remove_file(oled_class, &class_attr_resolution_y); class_remove_file(oled_class, &class_attr_rotate); class_destroy(oled_class); } <file_sep>/tmp.sh #!/bin/bash case $1 in insmod) sudo insmod cdata_fb_plat_dev.ko lsmod | grep cdata ls -l /sys/devices/platform ;; rmmod) sudo rmmod cdata_fb_plat_dev lsmod | grep cdata ls -l /sys/devices/platform ;; esac <file_sep>/oled-ssd1308/oled_ssd1308_spi.c /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : MISC category driver for test OLED-SSD1308 * * * History: ysh 7-07-2016 Create *************************************************************/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/miscdevice.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/string.h> #include <linux/spi/spi.h> #include <linux/uaccess.h> #include <linux/gpio.h> #include <asm/io.h> #include <asm/page.h> #include "oled_ssd1308_spi.h" #include "oled_ssd1308_ioctl.h" #undef pr_fmt #define pr_fmt(fmt) "%s: "fmt #define FLUSH_RATE_DEFAULT 200 /* ms */ //#define __SINGLE_WQ //#define __SHARED_QU //#define __TIMER struct ssd1308_t { wait_queue_head_t wait_q; struct semaphore sem; struct work_struct worker; struct delayed_work dworker; struct timer_list timer; struct tasklet_struct tasklet; struct workqueue_struct *wq; int del_wq; int worker_count; int timer_count; int tasklet_count; unsigned long flush_rate_ms; struct oled_platform_data_t *platform_data; }; struct oled_platform_data_t OLED; extern int oled_init_gpios(struct oled_platform_data_t *oled); extern void oled_free_gpios(void); #ifdef __SINGLE_WQ static void worker_func(struct work_struct *pWork) { struct ssd1308_t *ssd; ssd = container_of(pWork, struct ssd1308_t, worker); while (ssd->del_wq != 1) { oled_flush(); msleep(ssd->flush_rate_ms); // printk(KERN_WARNING "*fb : 0x%X\n", *ssd->platform_data->fb); } ssd->del_wq = 2; pr_debug("exit, flush_rate: %ldms\n", __func__, ssd->flush_rate_ms); } #elif defined(__SHARED_QU) static void dworker_func(struct delayed_work *pWork) { struct ssd1308_t *ssd; ssd = container_of(pWork, struct ssd1308_t, dworker); oled_flush(); if (ssd->del_wq == 1) { pr_debug("receive killing message\n", __func__); ssd->del_wq = 2; return; } schedule_delayed_work(&ssd->dworker, ssd->flush_rate_ms * HZ / 1000); } #endif #ifdef __TIMER static void timer_func(unsigned long pSSD) { struct ssd1308_t *ssd = (struct ssd1308_t*)pSSD; unsigned long expired = jiffies + HZ / 10; ssd->timer_count++; oled_flush(); mod_timer(&ssd->timer, expired); } #endif static ssize_t oled_ssd1308_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { #define BUF_SIZE 64 struct ssd1308_t *ssd; int ret; long pixel; char str[BUF_SIZE]; size_t i; u8 b; ssd = (struct ssd1308_t*)filp->private_data; if (down_interruptible(&ssd->sem)) { pr_debug("interrupted", __func__); return 0; } #if 0 u8 b; if (!get_user(b, buf)) { printk(KERN_INFO "%s: count %d\n", __func__, count); printk(KERN_INFO "%s: buf %s\n", __func__, buf); printk(KERN_INFO "%s: user data %d\n", __func__, b); oled_paint(b); oled_flush(); } #else /* * Transform to hexidecimal */ if (count > BUF_SIZE - 1) { printk(KERN_WARNING "%s: user string is too long\n", __func__); goto _WRITE_DONE; } /* * Accept 0 ~ 9, assemble chars to a string */ for(i=0; i<count; i++) { get_user(b, buf + i); printk(KERN_INFO "buf[%d] : %d\n", i, b); if (b >= '0' && b <= '9') { str[i] = b; continue; } str[i] = '\0'; break; } ret = kstrtol(str, 0, &pixel); if (ret == 0) { printk(KERN_INFO "%s: pixel %lx\n", __func__, pixel); oled_paint((u8)pixel); oled_flush(); } else printk(KERN_WARNING "%s: kstrtol failed~\n", __func__); #endif _WRITE_DONE: up(&ssd->sem); return count; } ssize_t oled_ssd1308_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { struct ssd1308_t *ssd; ssd = (struct ssd1308_t*)filp->private_data; return count; } static long oled_ssd1308_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct ssd1308_t *ssd; ssd = (struct ssd1308_t*)filp->private_data; if(down_interruptible(&ssd->sem)) { pr_debug("interrupted", __func__); return 0; } switch(cmd) { case OLED_CLEAR: oled_paint((u8)0); break; case OLED_RESET: oled_reset(); break; case OLED_ON: oled_on(); break; case OLED_OFF: oled_off(); break; case OLED_FEED: { u8 feed; u8 __user *ptr = (void __user *)arg; if (get_user(feed, ptr)) { up(&ssd->sem); return -EFAULT; } oled_paint(feed); } break; case OLED_FLUSH_RATE: { struct ssd1308_t *ssd = (struct ssd1308_t*)filp->private_data; pr_debug("New flush rate : %ldms\n", __func__, arg); ssd->flush_rate_ms = arg; } break; case OLED_FLUSH_PANEL: { oled_flush(); } break; default: up(&ssd->sem); return -ENOTTY; } up(&ssd->sem); pr_debug("cmd-%x\n", __func__, cmd); return 0; } static int oled_ssd1308_mmap(struct file *filp, struct vm_area_struct *vma) { struct ssd1308_t *ssd = (struct ssd1308_t*)filp->private_data; struct oled_platform_data_t *oled = ssd->platform_data; int ret; phys_addr_t phys = virt_to_phys((void*)oled->fb); pr_debug("enter\n", __func__); pr_debug("oled->fb: %p\n", __func__, oled->fb); pr_debug("oled->fb_size: %d\n", __func__, oled->fb_size); pr_debug("virt_to_phys((void*)oled->fb) : %d >> PAGE_SHIFT : %d\n", __func__, phys, phys >> PAGE_SHIFT); pr_debug("vma->vm_end: %lx\n", __func__, vma->vm_end); pr_debug("vma->vm_start: %lx\n", __func__, vma->vm_start); pr_debug("size: %lu\n", __func__, vma->vm_end - vma->vm_start); ret = remap_pfn_range(vma, vma->vm_start, phys >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); if (ret < 0) { printk(KERN_WARNING "%s: remap_pfn_range failed\n", __func__); return -EIO; } pr_debug("exit\n", __func__); return 0; } static int oled_ssd1308_open(struct inode *inode, struct file *filp) { struct ssd1308_t *ssd; pr_debug("enter\n", __func__); /* Allocate memory to private data, and set memory to zero */ ssd = kzalloc(sizeof(struct ssd1308_t), GFP_KERNEL); ssd->platform_data = &OLED; filp->private_data = ssd; sema_init(&ssd->sem, 1); /* work queue */ ssd->del_wq = 0; ssd->flush_rate_ms = FLUSH_RATE_DEFAULT; #ifdef __SINGLE_WQ ssd->wq = create_singlethread_workqueue("oled-flush"); INIT_WORK(&ssd->worker, worker_func); queue_work(ssd->wq, &ssd->worker); #elif defined(__SHARED_QU) INIT_DELAYED_WORK(&ssd->dworker, dworker_func); schedule_delayed_work(&ssd->dworker, ssd->flush_rate_ms * HZ / 1000); //INIT_WORK(&ssd->worker, worker_func); //schedule_work(&ssd->worker); #elif defined(__TIMER) /* Init timer */ init_timer(&ssd->timer); ssd->timer.function = timer_func; ssd->timer.data = (unsigned long)ssd; timeout = HZ / 10; ssd->timer.expires = jiffies + timeout; add_timer(&ssd->timer); oled_paint(0xff); #endif pr_debug("exit\n", __func__); return 0; } static int oled_ssd1308_fsync(struct file *filp, loff_t a, loff_t b, int datasync) { struct ssd1308_t *ssd; ssd = (struct ssd1308_t*)filp->private_data; if(down_interruptible(&ssd->sem)) { pr_debug("interrupted", __func__); return -1; } oled_flush(); up(&ssd->sem); return 0; } static int oled_ssd1308_close(struct inode *inode, struct file *filp) { struct ssd1308_t *ssd; ssd = (struct ssd1308_t*)filp->private_data; pr_debug("enter\n", __func__); #ifdef __SINGLE_WQ ssd->del_wq = 1; msleep(ssd->flush_rate_ms); while (ssd->del_wq != 2) msleep(ssd->flush_rate_ms); flush_workqueue(ssd->wq); destroy_workqueue(ssd->wq); #elif defined(__SHARED_QU) ssd->del_wq = 1; while (!cancel_delayed_work(&ssd->dworker)) { msleep(ssd->flush_rate_ms); } pr_debug("delayed work has been canceled\n", __func__); #elif defined(__TIMER) del_timer_sync(&ssd->timer); #endif kfree(filp->private_data); pr_debug("exit\n", __func__); return 0; } static struct file_operations oled_fops = { .owner = THIS_MODULE, .write = oled_ssd1308_write, .read = oled_ssd1308_read, .unlocked_ioctl = oled_ssd1308_ioctl, .mmap = oled_ssd1308_mmap, .open = oled_ssd1308_open, .release = oled_ssd1308_close, .fsync = oled_ssd1308_fsync }; static struct miscdevice oled_ssd1308_miscdev = { .minor = 197, /* Refer to miscdev.h */ .name = "oled-ssd1308", .fops = &oled_fops }; static void _kzalloc_frame_buf(struct oled_platform_data_t *pOLED) { unsigned int x, y; ssize_t page_nr, fb; x = pOLED->pixel_x; y = pOLED->pixel_y / pOLED->page_nr; pOLED->fb_size = x * y; fb = pOLED->fb_size; for (page_nr = 1; fb > PAGE_SIZE; page_nr++, fb -= PAGE_SIZE); pOLED->fb = kzalloc(PAGE_SIZE * page_nr, GFP_KERNEL); pOLED->fb_reverse = kmalloc(PAGE_SIZE * page_nr, GFP_KERNEL); pOLED->fb_rotate = kmalloc(PAGE_SIZE * page_nr, GFP_KERNEL); } static int oled_ssd1308_probe(struct spi_device *spi) { int ret; struct oled_platform_data_t *pData; if (!spi) { printk(KERN_WARNING "%s: spi is null. Device is not accessible\n", __func__); return -ENODEV; } spi->bits_per_word = 8; ret = spi_setup(spi); if (ret) printk(KERN_WARNING "%s: spi_setup() failed~\n", __func__); pData = (struct oled_platform_data_t*)spi->dev.platform_data; OLED = *pData; pr_debug("%dx, %dy, %dreset, %dad, %p-spi\n", __func__, pData->pixel_x, pData->pixel_y, pData->reset_pin, pData->ad_pin, spi); OLED.spi = spi; pr_debug("spi_new_device(), 0x%lx successful~\n", __func__, (unsigned long)OLED.spi); _kzalloc_frame_buf(&OLED); oled_init_gpios(&OLED); oled_init(&OLED); pr_debug("before misc_register", __func__); ret = misc_register(&oled_ssd1308_miscdev); if (ret >= 0) { printk(KERN_INFO "%s: Register OLED miscdev successful!\n", __func__); oled_ssd1308_create_class_attr(); } else printk(KERN_WARNING "%s: Register OLED miscdev failed~\n", __func__); return ret; } static int oled_ssd1308_remove(struct spi_device *spi) { oled_ssd1308_destroy_class_attr(); oled_off(); oled_free_gpios(); kfree(OLED.fb); misc_deregister(&oled_ssd1308_miscdev); printk(KERN_INFO "%s: Unregister ssd miscdev successful~\n", __func__); return 0; } static const struct of_device_id oled_ssd1308_dt_ids[] = { { .compatible = "visionox,ssd1308" }, {} }; MODULE_DEVICE_TABLE(of, oled_ssd1308_dt_ids); static struct spi_driver oled_ssd1308_driver = { .driver = { .name = "oled-ssd1308", .owner = THIS_MODULE, .of_match_table = oled_ssd1308_dt_ids }, .probe = oled_ssd1308_probe, .remove = oled_ssd1308_remove }; module_spi_driver(oled_ssd1308_driver); MODULE_LICENSE("GPL"); <file_sep>/oled-ssd1308/oled_ssd1308_ioctl.h /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : * * * History: ysh 7-29-2016 Create *************************************************************/ #ifndef __OLED_SSD1308_IOCTL_H #define __OLED_SSD1308_IOCTL_H #include <linux/ioctl.h> #define OLED_CLEAR _IO(0xCE, 1) #define OLED_RESET _IO(0xCE, 2) #define OLED_ON _IO(0xCE, 3) #define OLED_OFF _IO(0xCE, 4) #define OLED_FEED _IOW(0xCE, 5, unsigned char) #define OLED_FLUSH_RATE _IOW(0xCE, 6, unsigned long) #define OLED_FLUSH_PANEL _IO(0xCE, 7) #endif /* __OLED_SSD1308_IOCTL_H */ <file_sep>/cdata/cdata_plat_dev.c #include <linux/module.h> #include <linux/platform_device.h> static struct resource ldt_resource[] = { }; static void ldt_dev_release(struct device *dev) { printk(KERN_INFO "%s", __func__); } static struct platform_device ldt_platform_device = { .name = "cdata", .resource = ldt_resource, .num_resources = ARRAY_SIZE(ldt_resource), .dev.release = ldt_dev_release }; static int ldt_plat_dev_init(void) { printk(KERN_INFO "%s", __func__); return platform_device_register(&ldt_platform_device); } static void ldt_plat_dev_exit(void) { printk(KERN_INFO "%s", __func__); return platform_device_unregister(&ldt_platform_device); } module_init(ldt_plat_dev_init); module_exit(ldt_plat_dev_exit); MODULE_LICENSE("GPL"); <file_sep>/cdata/my_mknod.sh #!/bin/bash # # Making device node : /dev/cdata # Change node permission to 666 # DEVICE_NODE=/dev/cdata mesg_brown "Creating device node: ${DEVICE_NODE}" if ! [ -e ${DEVICE_NODE} ] then sudo mknod $DEVICE_NODE c 121 32 echo -e "\033[32mMaking device node\033[0m" if ! [ -e $DEVICE_NODE ]; then echo -e "\033[31mMake cdata failed~\033[0m" exit 1 fi sudo chmod 666 $DEVICE_NODE ls -l $DEVICE_NODE --color=auto fi <file_sep>/cdata/cdata_fb_ssd1308.c /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : MISC category driver for test OLED-SSD1308 * * * History: ysh 7-07-2016 Create *************************************************************/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/delay.h> #include <linux/vmalloc.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/irq.h> #include <linux/miscdevice.h> #include <linux/input.h> #include <linux/wait.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/semaphore.h> #include <linux/interrupt.h> #include <linux/string.h> #include <linux/uaccess.h> #define __PLATFORM_DRIVER_HELPER_MACRO #define __WORKQUEUE #define PIXEL_X 128 #define PIXEL_Y 64 struct cdata_fb_t { wait_queue_head_t wait_q; struct semaphore sem; struct work_struct worker; struct timer_list timer; struct tasklet_struct tasklet; int worker_count; int timer_count; int tasklet_count; u8 data[PIXEL_X]; /* u8 pixel_buffer[PIXEL_X][PIXEL_Y]; */ }; static void worker_func(struct work_struct *pWork) { struct cdata_fb_t *cdata; cdata = container_of(pWork, struct cdata_fb_t, worker); printk(KERN_INFO "%s: %s\n", __func__, cdata->data); cdata->worker_count++; wake_up_interruptible(&cdata->wait_q); } static void timer_func(unsigned long pCdata) { struct cdata_fb_t *cdata = (struct cdata_fb_t*)pCdata; printk(KERN_INFO "%s: %s\n", __func__, cdata->data); cdata->timer_count++; wake_up_interruptible(&cdata->wait_q); } static void tasklet_func(unsigned long pCdata) { struct cdata_fb_t *cdata = (struct cdata_fb_t*)pCdata; printk(KERN_INFO "%s: %s\n", __func__, cdata->data); cdata->tasklet_count++; wake_up_interruptible(&cdata->wait_q); } static ssize_t cdata_fb_ssd1308_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { struct cdata_fb_t *cdata; int worker_count, timer_count, tasklet_count; unsigned long timeout; cdata = (struct cdata_fb_t*)filp->private_data; if (down_interruptible(&cdata->sem)) return 0; worker_count = cdata->worker_count; timer_count = cdata->timer_count; tasklet_count = cdata->tasklet_count; if (copy_from_user(cdata->data, buf, count)) return 0; /* * Schedule worker */ printk(KERN_INFO "%s: schedule worker\n", __func__); schedule_work(&cdata->worker); /* * Schedule kernel timer */ timeout = strstr(cdata->data, "child") != NULL /* Child process */ ? 1 * HZ /* Parent process */ : 7 * HZ; printk(KERN_INFO "%s: submit timer, timeout %ld\n", __func__, timeout); cdata->timer.expires = jiffies + timeout; add_timer(&cdata->timer); /* * Schedule tasklet */ printk(KERN_INFO "%s: schedule tasklet\n", __func__); tasklet_schedule(&cdata->tasklet); /* * Blocking I/O */ REPEAT: #define EVENTS() \ ( worker_count != cdata->worker_count \ && timer_count != cdata->timer_count \ && tasklet_count != cdata->tasklet_count ) wait_event_interruptible(cdata->wait_q, EVENTS()); if ( !EVENTS() ) goto REPEAT; printk(KERN_INFO "worker_count : %d %d, %s\n", worker_count, cdata->worker_count, cdata->data); printk(KERN_INFO "timer_count : %d %d, %s\n", timer_count, cdata->timer_count, cdata->data); printk(KERN_INFO "tasklet_count : %d %d, %s\n", tasklet_count, cdata->tasklet_count, cdata->data); printk(KERN_INFO "%s: complete, %s\n", __func__, cdata->data); up(&cdata->sem); return count; } static long cdata_fb_ssd1308_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { return 0; } static int cdata_fb_ssd1308_mmap(struct file *filp, struct vm_area_struct *vma) { return 0; } static int cdata_fb_ssd1308_open(struct inode *inode, struct file *filp) { struct cdata_fb_t *cdata; printk(KERN_INFO "%s\n", __func__); /* Allocate memory to private data, and set memory to zero */ cdata = kzalloc(sizeof(struct cdata_fb_t), GFP_KERNEL); filp->private_data = cdata; init_waitqueue_head(&cdata->wait_q); sema_init(&cdata->sem, 1); /* Init work queue */ INIT_WORK(&cdata->worker, worker_func); /* Init timer */ init_timer(&cdata->timer); cdata->timer.function = timer_func; cdata->timer.data = (unsigned long)cdata; /* Init tasklet */ tasklet_init(&cdata->tasklet, tasklet_func, (unsigned long)cdata); return 0; } static int cdata_fb_ssd1308_close(struct inode *inode, struct file *filp) { struct cdata_fb_t *cdata; cdata = (struct cdata_fb_t*)filp->private_data; printk(KERN_INFO "%s: %s\n", __func__, cdata->data); del_timer_sync(&cdata->timer); kfree(filp->private_data); return 0; } static struct file_operations cdata_fb_fops = { .owner = THIS_MODULE, .write = cdata_fb_ssd1308_write, .unlocked_ioctl = cdata_fb_ssd1308_ioctl, .mmap = cdata_fb_ssd1308_mmap, .open = cdata_fb_ssd1308_open, .release = cdata_fb_ssd1308_close }; static struct miscdevice cdata_fb_miscdev = { .minor = 198, /* Refer to miscdev.h */ .name = "cdata-fb", .fops = &cdata_fb_fops }; static int cdata_fb_plat_probe(struct platform_device *plat_dev) { int ret; ret = misc_register(&cdata_fb_miscdev); ret < 0 ? printk(KERN_INFO "%s: Register cdata miscdev failed~\n", __func__) : printk(KERN_INFO "%s: Register cdata miscdev successful~\n", __func__); return ret; } static int cdata_fb_plat_remove(struct platform_device *plat_dev) { misc_deregister(&cdata_fb_miscdev); printk(KERN_INFO "%s: Unregister cdata miscdev successful~\n", __func__); return 0; } static struct platform_driver cdata_fb_plat_driver = { .driver = { .name = "cdata-fb", .owner = THIS_MODULE }, .probe = cdata_fb_plat_probe, .remove = cdata_fb_plat_remove }; #ifndef __PLATFORM_DRIVER_HELPER_MACRO int __init cdata_fb_ssd1308_init_module(void) { int ret; printk(KERN_INFO "%s: Register cdata-fb platform driver successful\n", __func__); ret = platform_driver_register(&cdata_fb_plat_driver); return ret; } void __exit cdata_fb_ssd1308_cleanup(void) { printk(KERN_INFO "%s: Unregister cdata-fb platform driver successful\n", __func__); platform_driver_unregister(&cdata_fb_plat_driver); } #endif #ifdef __PLATFORM_DRIVER_HELPER_MACRO module_platform_driver(cdata_fb_plat_driver); #else module_init(cdata_fb_ssd1308_init_module); module_exit(cdata_fb_ssd1308_cleanup); #endif MODULE_LICENSE("GPL"); <file_sep>/test/Makefile CFLAGS += -pthread -lpthread BINS := test \ test-fb-ssd1308 \ test-oled-ssd1308 vpath %.c ./ all: $(BINS) .PHONY: clean clean: rm -rf $(BINS) .#* <file_sep>/cdata/cdata_fb_plat_dev.c /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : OLED-SSD1308 * * * History: ysh 7-08-2016 Create *************************************************************/ #include <linux/module.h> #include <linux/platform_device.h> static struct resource cdata_fb_resource[] = { }; static void cdata_fb_dev_release(struct device *dev) { printk(KERN_INFO "%s", __func__); } static struct platform_device cdata_fb_plat_device = { .name = "cdata-fb", .resource = cdata_fb_resource, .num_resources = ARRAY_SIZE(cdata_fb_resource), .dev.release = cdata_fb_dev_release }; static int cdata_fb_plat_init(void) { printk(KERN_INFO "%s", __func__); return platform_device_register(&cdata_fb_plat_device); } static void cdata_fb_plat_exit(void) { printk(KERN_INFO "%s", __func__); return platform_device_unregister(&cdata_fb_plat_device); } module_init(cdata_fb_plat_init); module_exit(cdata_fb_plat_exit); MODULE_LICENSE("GPL"); <file_sep>/oled-ssd1308/am335/build.sh #!/bin/bash # # 2016-7-07 # <EMAIL> # # REMOTE_DIR=~/remote/tpsbuserver-prj/GigaController/FW/modules declare -a KO_FILES=( # cdata_plat_dev.ko # cdata.ko # cdata_fb_plat_dev.ko # cdata_fb_ssd1308.ko oled_ssd1308.ko oled_plat_dev.ko ) declare -a SCRIPT_FILES=(insmod.sh rmmod.sh) error_msg() { echo -e "\033[31mErrooooor~ $1\033[0m" } copy_files_to_remote() { if ! [ -d $REMOTE_DIR ]; then error_msg $REMOTE_DIR exit 1 fi # # Kernel object # for i in ${KO_FILES[@]} do ! cp $i $REMOTE_DIR && \ error_msg $i done # # Scripts for target # for i in ${SCRIPT_FILES[@]}; do ! cp $i $REMOTE_DIR && \ error_msg $i done ls -l $REMOTE_DIR --color exit 0 } case $1 in install) copy_files_to_remote exit 0 ;; clean) make clean exit 0 ;; test) echo -e "\033[33m\nBuild test program\033[0m" pushd . cd ../test/am335 ./build.sh && ./build.sh install popd ;; *) . ./setup.sh make esac <file_sep>/cdata/insmod.sh #!/bin/bash . ./VAR.sh # Clean kernel message buffer sudo dmesg -C ./rmmod.sh > /dev/null for i in ${KO[@]} do ! sudo insmod $i \ && mesg_red "Install driver: $i failed~" done for i in ${DEVICE_NODES[@]} do if [ ! -e $i ]; then mesg_red "No device node, $i" else ! sudo chmod 666 $i && \ mesg_red "Change permission of $i failed~" fi done echo -e "\033[33mInstall modules complete." lsmod | grep cdata dmesg | tail -n 40 tree -hfC -H . --du -o dev.html /dev echo -e "\033[0m" mesg_green "Checking device nodes...." for i in ${DEVICE_NODES[@]} do if [ -e "$i" ]; then mesg_green "\t$i" sudo chmod 666 "$i" else mesg_red "No $i exists~" fi done mesg_green "Checking sysfs...." for i in ${SYS_NODES[@]} do if [ -d "$i" ]; then mesg_green "\t$i" else mesg_red "No $i exists~" fi done ls /dev/cdata* -l --color=auto <file_sep>/oled-ssd1308/oled_ssd1308_spi.h /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : * * * History: ysh 7-17-2016 Create *************************************************************/ #ifndef __OLED_SSD1308_SPI_H #define __OLED_SSD1308_SPI_H #include <linux/types.h> #include <linux/semaphore.h> #include <linux/ioctl.h> struct oled_platform_data_t { struct semaphore sem; struct spi_device *spi; unsigned int pixel_x; unsigned int pixel_y; unsigned int page_nr; unsigned reset_pin; unsigned ad_pin; unsigned led1_pin; unsigned led2_pin; long reverse_pixel; unsigned int rotate; unsigned int fb_size; u8 *fb; u8 *fb_reverse; u8 *fb_rotate; }; void oled_reset(void); void oled_on(void); void oled_off(void); void oled_paint(u8 byte); void oled_flush(void); void oled_init(struct oled_platform_data_t *); void oled_ssd1308_create_class_attr(void); void oled_ssd1308_destroy_class_attr(void); #endif /* __OLED_SSD1308_SPI_H */ <file_sep>/test/rolling-oled-ssd1308.cpp /************************************************************** * Name : test-oled-ssd1308.c * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : Test driver : oled-ssd1308 * * * History: ysh 7-28-2016 Create *************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stropts.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/mman.h> #include <pthread.h> #include "../oled_ssd1308_ioctl.h" #define __SYS_CALL_FSYNC sig_atomic_t child_exit_status; static void print_usage(FILE *stream) { fprintf(stream, "\nUsage: OLED test utility\n"); fprintf(stream, "SYSNOPSIS:\n" " rolling-oled-ssd1308\n" "\t-c\tclear screen\n" "\t-o\tturn on screen\n" "\t-i\tturn off screen\n" "\t-f feed-byte\tfeed screen with BYTE\n" "\t-r\treset screen\n" "\t-t\ttest times\n" "\t-u\tflush rate (ms)\n" "\t-m feed-byte\ttest mmap()\n" ); exit(0); } struct Threadpara_t { int fd; int row; unsigned char feed; pthread_t th_id; pthread_mutex_t mutex; }; static void* _thread_test_mmap(void *ptr) { struct Threadpara_t *th = (struct Threadpara_t*)ptr; size_t i, j, k, len = 128 * 64 / 8; size_t row_len = 128, row_start = th->row * row_len, row_end = row_start + row_len - 1; size_t grey_area = 0, grey_area_width = 8, grey_area_start = th->row * grey_area_width, grey_area_end; unsigned char *map; bool quit; const useconds_t _1s = 1000000; unsigned char a, b; map = (unsigned char*)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, th->fd, 0); if (map == MAP_FAILED) { printf("mmap() failed!\n"); return (void*)-1; } printf("map : %p, feed : 0x%X\n", map, th->feed); k = th->row; for (quit = false; !quit;) { if (pthread_mutex_trylock(&th->mutex) == 0) quit = true; #if 0 /* Bar */ for (j = 0; j < len; j++) { if (j == grey_area) { size_t i = 0; for (i = 0; i < 64; i++, j++) map[j] = 0; } else { map[j] = th->feed; } } grey_area += 64; if (grey_area >= len) grey_area = 0; #elif 0 /* Wave */ for (j=row_start; j<=row_end; j++) map[j] = 0xff; grey_area_start += grey_area_width; grey_area_start %= row_len; grey_area_end = grey_area_start + grey_area_width; j = row_start + grey_area_start; k = j + grey_area_width; for (; j<k; j++) map[j] = 0; #else /* Chess board */ j = row_start; k++; if (k % 2) { a = th->feed; b = 0; } else { a = 0; b = th->feed; } for (; j<=row_end; j++) { for (i=0; i<8; i++, j++) map[j] = a; if (j >= row_end) break; for (i=0; i<8; i++, j++) map[j] = b; } #endif #define LAST_ROW_INDEX 7 #ifdef __SYS_CALL_FSYNC if(th->row == LAST_ROW_INDEX) fsync(th->fd); #else if(th->row == LAST_ROW_INDEX) ioctl(th->fd, OLED_FLUSH_PANEL); #endif usleep(_1s); } munmap(map, len); printf("Thread (0x%lX) was terminated!\n", th->th_id); return (void*)0; } static const int thread_nr = 8; static struct Threadpara_t para[thread_nr]; void clean_up_threads(int sig_number, siginfo_t *info, void *p) { int event; fprintf(stderr, "%s: Clean up threads\n", __func__); for (int i=0; i<thread_nr; i++) pthread_mutex_unlock(&para[i].mutex); for (int i=0; i<thread_nr; i++) pthread_join(para[i].th_id, (void**)&event); for (int i=0; i<thread_nr; i++) pthread_mutex_destroy(&para[i].mutex); exit(EXIT_SUCCESS); } int main(int argc, char *argv[]) { int fd, i, opt; char write_data[20] = { 0 }; ssize_t ret; const char *dev = "/dev/oled-ssd1308"; pid_t child; struct sigaction sigchld_action; const useconds_t _1s = 1000000; memset(&sigchld_action, 0, sizeof(struct sigaction)); sigchld_action.sa_sigaction = clean_up_threads; sigaction (SIGINT, &sigchld_action, NULL); if ( (fd = open(dev, O_RDWR)) == -1 ) { fprintf(stderr, "Open %s failed~\n", dev); exit(EXIT_FAILURE); } fprintf(stderr, "Open %s successful!\n", dev); ioctl(fd, OLED_RESET); ioctl(fd, OLED_CLEAR); ioctl(fd, OLED_ON); usleep(_1s); unsigned char feed = 0xaa; ioctl(fd, OLED_FEED, &feed); fsync(fd); usleep(_1s); { int i, c; for (i=0; i<thread_nr; i++) { para[i].fd = fd; para[i].row = i; para[i].feed = feed; pthread_mutex_init(&para[i].mutex, NULL); pthread_mutex_lock(&para[i].mutex); } for (i=0; i<thread_nr; i++) pthread_create(&para[i].th_id, NULL, &_thread_test_mmap, (void*)&para[i]); } while(1) usleep(_1s); close(fd); exit(EXIT_SUCCESS); } <file_sep>/test/am335/Makefile # # # 2016-July-06 # Max <<EMAIL>> # # To build kernel module # > cdata.ko # > cdata_plat_dev.ko # include ../../am335/Makefile.inc DBG=y ifneq ($(DBG),y) DEBUG= OPTIMIZE=-O2 else DEBUG=-g OPTIMIZE=-O0 endif CFLAGS += -pthread -iquote../../ CPPFLAGS += -pthread -iquote../../ vpath %.c ../ vpath %.cpp ../ BINS := test \ test-fb-ssd1308 \ test-oled-ssd1308 \ test-oled-ssd1308-r1 \ rolling-oled-ssd1308 .PHONY: all all: $(BINS) test-oled-ssd1308-r1: test-oled-ssd1308-r1.o input-event.o $(CXX) $(CPPFLAGS) $^ -o $@ clean: rm -rf $(BINS) .#* *~ .PHONY: TAGS TAGS: rm -rf TAGS find ../ -regextype posix-egrep -iregex '.*\.(cpp|c|h)' | xargs etags -a find ~/triton/toolchain/gcc-linaro-5.3.1-2016.05-x86_64_arm-linux-gnueabihf/arm-linux-gnueabihf/libc/usr/include \ -type f | xargs etags -a find ~/triton/toolchain/gcc-linaro-5.3.1-2016.05-x86_64_arm-linux-gnueabihf/arm-linux-gnueabihf/include/c++/5.3.1 \ -type f | xargs etags -a find . -iname 'Makefile.*' -type f | xargs etags -a <file_sep>/oled-ssd1308/am335/insmod.sh #!/bin/bash # # 2016-7-07 # <EMAIL> # # Install kernel modules: # > cdata.ko # > cdata_plat_dev.ko # > cdata_fb_ssd1308.ko # > cdata_fb_plat_dev.ko # > oled_ssd1308_spi.ko # > oled_plat_dev.ko # error_msg() { echo -e "\033[31mErrooooor: $1\033[0m" } declare -a DEVICE_NODES=( #/dev/cdata-misc #/dev/cdata-fb /dev/oled-ssd1308 ) declare -a KO_FILE=( #cdata_plat_dev.ko #cdata.ko #cdata_fb_plat_dev.ko #cdata_fb_ssd1308.ko oled_plat_dev.ko oled_ssd1308.ko ) for i in ${KO_FILE[@]} do ! insmod $i && error_msg $i done for i in ${DEVICE_NODES[@]} do ! [ -e $i ] && \ error_msg "No $i exists~" && \ exit 1 done lsmod | grep cdata* #dmesg | tail -n 10 ls -l $DEVICE_NODE --color SYS_CLASS_DIR=/sys/class/oled [ -d ${SYS_CLASS_DIR} ] && \ ls -l ${SYS_CLASS_DIR} --color auto <file_sep>/oled-ssd1308/oled_ssd1308_gpio.c /************************************************************** * Author : * .. .. * / | / | ~~ * / |/ | /| \ / ~ * / | ~ | /.| x ~ * / ~ |~ / l / L * * Description : MISC category driver for test OLED-SSD1308 * * * History: ysh 7-29-2016 Create *************************************************************/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/gpio.h> #include "oled_ssd1308_spi.h" #undef pr_fmt #define pr_fmt(fmt) "%s:"fmt struct gpio_t { unsigned pin; unsigned long flag; char *label; }; static struct gpio_t *oled_gpios = NULL; static struct oled_platform_data_t *pOLED = NULL; static ssize_t oled_gpio_nr = 0; int oled_init_gpios(struct oled_platform_data_t *); void oled_free_gpios(void); int oled_init_gpios(struct oled_platform_data_t *oled) { ssize_t i; int err ; struct gpio_t gpios[] = { { oled->reset_pin, GPIOF_DIR_OUT, "OLED-Reset-Pin" }, { oled->ad_pin, GPIOF_DIR_OUT, "OLED-AD-Pin" }, { oled->led1_pin, GPIOF_DIR_OUT, "LED1-Pin" }, { oled->led2_pin, GPIOF_DIR_OUT, "LED2-Pin" } }; pOLED = oled; oled_gpio_nr = ARRAY_SIZE(gpios); oled_gpios = kzalloc(sizeof gpios, GFP_KERNEL); memcpy(oled_gpios, gpios, sizeof gpios); for (i=0; i<oled_gpio_nr; i++) { struct gpio_t *io = &gpios[i]; err = gpio_request_one(io->pin, io->flag, io->label); if (err) printk(KERN_WARNING "%s: Request GPIO-%d failed~\n", __func__, io->pin); } gpio_set_value(oled->led1_pin, 1); gpio_set_value(oled->led2_pin, 1); pr_debug("\n", __func__); return 0; } void oled_free_gpios() { ssize_t i; ssize_t gpio_nr = oled_gpio_nr; struct gpio_t *gpios = oled_gpios; gpio_set_value(pOLED->led1_pin, 1); gpio_set_value(pOLED->led2_pin, 1); for (i=0; i<gpio_nr; i++) gpio_free(gpios[i].pin); kfree(oled_gpios); pr_debug("\n", __func__); } <file_sep>/cdata/build.sh #!/bin/bash # # 2016-4-24 # <EMAIL> # # > Build device driver : cdata # > Make device node : /dev/cdata # > Remove previous kernel module : cdata.ko # > Install kernel module : cdata.ko # . ./VAR.sh clean_modules() { for i in ${KO[@]} do ! rm $i done mesg_brown "Delete modules" } case $1 in insmod) ./insmod.sh exit 0 ;; rmmod) ./rmmod.sh exit 0 ;; clean) clean_modules ;; --help) mesg_brown "\n\t./install.sh [ insmod | rmmod ]\n" exit 0 ;; esac if ! make then mesg_red "Make cdata failed~" exit 1 else echo -e "\033[33mMake cdata Okay~~" ls -l *.ko echo -e "\033[0m" fi if ! make test then mesg_red "Make test failed~" exit 1 fi [ $# -eq 0 ] && \ mesg_brown "\t./build.sh [ insmod | rmmod | clean ]\n"
63b4fe122eb984e4df2d3816a99e1b418a20b7ae
[ "C", "Makefile", "C++", "Shell" ]
34
Makefile
77shell/dev-driver-practice
76ef133f3f1a14e644de16e2e59e358bea6aadfe
7a3e7bb0cf25dec808aff0b0f5f6e0eb38ec83f5
refs/heads/master
<repo_name>GrayWizard/ExData_Plotting1<file_sep>/plot4.R #Read the data file full_data <- read.table("household_power_consumption.txt",header=TRUE,sep=";",na.strings="?") #Filter out the necessary data data <- full_data[full_data$Date=="1/2/2007" | full_data$Date=="2/2/2007",] #Convert date/time to the correct format data$Date <- as.Date(data$Date,format="%d/%m/%Y") data$Time <- strftime(strptime(data$Time,format="%H:%M:%S"),"%H:%M:%S") data$DateTime <- strptime(paste(data$Date, data$Time), "%Y-%m-%d %H:%M:%S") #Open the PNG device png(file="plot4.png",width=480,height=480) #Set up the 2x2 plot space par(mfrow=c(2,2)) #Plot the line graph (top-left) plot(data$DateTime,data$Global_active_power,type="n",ylab="Global Active Power (kilowatts)",xlab="") lines(data$DateTime,data$Global_active_power,type="l") #Plot the line graph (top-right) plot(data$DateTime,data$Voltage,type="n",ylab="Voltage",xlab="datetime") lines(data$DateTime,data$Voltage,type="l") #Plot the line graph (bottom-left) plot(data$DateTime,data$Sub_metering_1,type="n",ylab="Energy sub metering",xlab="") lines(data$DateTime,data$Sub_metering_1,type="l") lines(data$DateTime,data$Sub_metering_2,type="l",col="red") lines(data$DateTime,data$Sub_metering_3,type="l",col="blue") legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=1,bty="n") #Plot the line graph (bottom-right) plot(data$DateTime,data$Global_reactive_power,type="n",ylab="Global_reactive_power",xlab="datetime") lines(data$DateTime,data$Global_reactive_power,type="l") #Close the device dev.off()<file_sep>/plot3.R #Read the data file full_data <- read.table("household_power_consumption.txt",header=TRUE,sep=";",na.strings="?") #Filter out the necessary data data <- full_data[full_data$Date=="1/2/2007" | full_data$Date=="2/2/2007",] #Convert date/time to the correct format data$Date <- as.Date(data$Date,format="%d/%m/%Y") data$Time <- strftime(strptime(data$Time,format="%H:%M:%S"),"%H:%M:%S") data$DateTime <- strptime(paste(data$Date, data$Time), "%Y-%m-%d %H:%M:%S") #Open the PNG device png(file="plot3.png",width=480,height=480) #Plot the line graph plot(data$DateTime,data$Sub_metering_1,type="n",ylab="Energy sub metering",xlab="") lines(data$DateTime,data$Sub_metering_1,type="l") lines(data$DateTime,data$Sub_metering_2,type="l",col="red") lines(data$DateTime,data$Sub_metering_3,type="l",col="blue") legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=1) #Close the device dev.off()<file_sep>/plot2.R #Read the data file full_data <- read.table("household_power_consumption.txt",header=TRUE,sep=";",na.strings="?") #Filter out the necessary data data <- full_data[full_data$Date=="1/2/2007" | full_data$Date=="2/2/2007",] #Convert date/time to the correct format data$Date <- as.Date(data$Date,format="%d/%m/%Y") data$Time <- strftime(strptime(data$Time,format="%H:%M:%S"),"%H:%M:%S") data$DateTime <- strptime(paste(data$Date, data$Time), "%Y-%m-%d %H:%M:%S") #Open the PNG device png(file="plot2.png",width=480,height=480) #Plot the line graph plot(data$DateTime,data$Global_active_power,type="n",ylab="Global Active Power (kilowatts)",xlab="") lines(data$DateTime,data$Global_active_power,type="l") #Close the device dev.off()
84e8f4b684b0e475e17e09307be1f61a6d487bf3
[ "R" ]
3
R
GrayWizard/ExData_Plotting1
0276dd727f443c4e45281081d9cd3dd808260703
3f242114d2c64b193a6cc18cdfbbb09b9419a1c6
refs/heads/master
<file_sep>/* Problem 10 - Summation of Primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below 2000000. Developed using Sieve of Eratosthenes Algorithm Answer: 142913828922 Author: ravikumark815 */ #include <stdio.h> #include <stdlib.h> int main(void) { char *soe; unsigned i, j; size_t n = 2000000; unsigned long long sum = 0ULL; soe = calloc(n, sizeof *soe); for (i = 2; i < n; i++) { if (!soe[i]) { sum += i; for (j = i*2; j < n; j += i) { soe[j] = 1; } } } free(soe); printf("Result = %llu\n", sum); return 0; }<file_sep>/* If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. Author: https://github.com/ravikumark815 Answer: 21124 */ #include <stdio.h> #include <stdint.h> int32_t main() { uint8_t unit_lengths[] = { 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8}; uint8_t tens_lengths[] = { 6, 6, 5, 5, 5, 7, 6, 6}; int32_t s = 0; for (int32_t i = 1; i < 1001; ++i) { int32_t n = i; if (n == 1000) { s += 11; continue; } if (n%100 == 0) { s += unit_lengths[n/100-1] + 7; continue; } if (n > 100) { s += unit_lengths[n/100-1] + 10; n %= 100; } if (n >= 20) { s += tens_lengths[n/10-2]; if (n%10 > 0) s += unit_lengths[n%10-1]; } if (n < 20) s += unit_lengths[n-1]; } printf("Result: %d\n", s); return 0; }<file_sep>/* Problem 14 - Collatz sequence The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. Author: https://github.com/ravikumark815 Answer: 837799 */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> int32_t main() { uint64_t N = 1000000, longest = 0, answer, n, i, s; uint64_t *lengths = (uint64_t*) calloc(N, sizeof(uint64_t)); for (i = 0; i < N; ++i) lengths[i] = 0; for (i = 1; i < N+1; ++i) { n = i; s = 1; while (n > 1) { if (n < N && lengths[n-1] > 0) { s += lengths[n-1] - 1; break; } if (n&1) n = 3*n + 1; else n >>= 1; ++s; } lengths[i-1] = s; if (s > longest) { longest = s; answer = i; } } printf("Problem 14: %" PRIu64 "\n", answer); free(lengths); return 0; } <file_sep>/* Problem 6 - Sum Square Difference The sum of the squares of the first ten natural numbers is 385 The square of the sum of the first ten natural numbers is 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. Answer: 25164150 Author: ravikumark815 */ #include<stdio.h> int main() { int i=0,c=1,sum1=0,sum2=0; for(i=1;i<=100;i++) { sum1 = sum1+(i*i); sum2 = sum2+i; } printf("Result = %d\n",(sum2*sum2)-sum1); return 0; }<file_sep>/* Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. Answer: 443839 */ #include <inttypes.h> #include <stdio.h> #include <stdint.h> int32_t main() { uint64_t answer = 0, sum_powers, i, n, d; for (i = 2; i < 354295; ++i) { n = i; sum_powers = 0; while (n > 0) { d = n%10; n /= 10; d = d*d*d*d*d; sum_powers += d; } if (sum_powers == i) answer += i; } printf("Result: %" PRIu64 "\n", answer); return 0; }<file_sep>/* By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) Author: https://github.com/ravikumark815 Answer: 1074 */ #include <stdint.h> #include <stdio.h> #define SIZE 15 int32_t main() { /* At each number, we have 2 choice : left or right. So at each number, * the maximum path either comes from left or right value. We go in * reverse order, starting at bottom row and going to the top. For each * number, we add the value of the longest path between value left or * right. The final answer is the value at the top of the pyramid. */ int32_t triangle[SIZE][SIZE] = { {75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {95, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {17, 47, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {18, 35, 87, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {20, 04, 82, 47, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {19, 01, 23, 75, 03, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {88, 02, 77, 73, 07, 63, 67, 0, 0, 0, 0, 0, 0, 0, 0}, {99, 65, 04, 28, 06, 16, 70, 92, 0, 0, 0, 0, 0, 0, 0}, {41, 41, 26, 56, 83, 40, 80, 70, 33, 0, 0, 0, 0, 0, 0}, {41, 48, 72, 33, 47, 32, 37, 16, 94, 29, 0, 0, 0, 0, 0}, {53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14, 0, 0, 0, 0}, {70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57, 0, 0, 0}, {91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48, 0, 0}, {63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31, 0}, {04, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 04, 23} }; for (int32_t i = SIZE-2; i > -1; --i) for (int32_t j = 0; j < i+1; ++j) triangle[i][j] += (triangle[i+1][j] > triangle[i+1][j+1]) ? triangle[i+1][j] : triangle[i+1][j+1]; printf("Result: %d\n", triangle[0][0]); return 0; }<file_sep>/* Euler discovered the remarkable quadratic formula: n^2+n+41 It turns out that the formula will produce 40 primes for the consecutive integer values 0≤n≤39. However, when n=40,402+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,412+41+41 is clearly divisible by 41. The incredible formula n^2−79n+1601 was discovered, which produces 80 primes for the consecutive values 0≤n≤79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n2+an+b, where |a|<1000 and |b|≤1000 where |n| is the modulus/absolute value of n e.g. |11|=11 and |−4|=4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0. Answer: -59231 */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> int32_t main() { uint64_t N = 1000000, i, j; uint8_t *sieve = (uint8_t*)calloc(N, sizeof(uint8_t)); for (i = 0; i < N; ++i) sieve[i] = 1; for (i = 2; i < N; ++i) if (sieve[i-1]) for (j = 2*i; j < N+1; j += i) sieve[j-1] = 0; int32_t MAX = 1000, max_num_primes = 0, product, a, b, n, tmp; for (a = -MAX+1; a < MAX; ++a) for (b = -MAX+1; b < MAX; ++b) { n = 0; tmp = b; if (tmp < 0) tmp *= -1; while (sieve[tmp-1]) { ++n; tmp = n*n + a*n + b; if (tmp < 0) tmp *= -1; } if (n > max_num_primes) { max_num_primes = n; product = a*b; } } printf("Result: %d\n", product); free(sieve); return 0; } <file_sep>/* If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. Not all numbers produce palindromes so quickly. For example, 349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 That is, 349 took three iterations to arrive at a palindrome. Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers. Author: https://github.com/ravikumark815 Answer: 249 */ #include <stdio.h> #include <stdint.h> #include <string.h> #define SIZE 40 /* 50 iterations will use numbers with at most 40 digits */ #define N 10000 /* count the Lychrel numbers from 1 to 10'000 */ /* is_palindrom: return 1 if array ar is palindromic, 0 otherwise */ int32_t is_palindrom(uint8_t *ar, int32_t len) { int32_t i; for (i = 0; i <= len/2; ++i) if (ar[i] != ar[len-1-i]) return 0; return 1; } /* sum_reverse: compute n + reverse(n) where digits of n are stored in ar[]. * Store result in sum[]. Return the number of digits in sum[] */ int32_t sum_reverse(uint8_t *ar, uint8_t *sum, int32_t len) { int32_t carry, i; for (i = 0, carry = 0; i < len; ++i) { carry += ar[i] + ar[len-1 - i]; sum[i] = carry%10; carry /= 10; } while (carry > 0) { sum[i++] = carry%10; carry /= 10; } return i; } /* is_lychrel: return 1 if n is a Lychrel number (summing n and reverse(n) gives * a palindromic number) or n+reverse(n) is a Lychrel number. Return 0 otherwise * (not a Lychrel number, even after 50 iterations). */ int32_t is_lychrel(int32_t n) { uint8_t digits[SIZE] = {0}, sum[SIZE] = {0}; int32_t n_iter, i; /* store digits of n into an array */ for (i = 0; n > 0; ++i) { digits[i] = n%10; n /= 10; } for (n_iter = 0; n_iter < 50; ++n_iter) { i = sum_reverse(digits, sum, i); if (is_palindrom(sum, i)) return 1; memcpy(digits, sum, i * sizeof(uint8_t)); memset(sum, 0, i * sizeof(uint8_t)); } return 0; } /* print the number of non-Lychrel numbers between 1..10'000 */ int32_t main(void) { int32_t i, answer = 0; for (i = 0; i < N; ++i) if (!is_lychrel(i)) ++answer; printf("Problem 55: %d\n", answer); return 0; }<file_sep>/* Problem 2 - Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Answer: 4613732 Author: ravikumark815 */ #include<stdio.h> #include<stdlib.h> int main() { int i=1,j=2,res=0,c=2; while(c<=4000000) { if (c%2==0) res += c; c = i+j; i = j; j = c; } printf("Result = %d\n",res); return 0; }<file_sep>/* Problem 5 - Smallest Multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Answer: 232792560 Author: ravikumark815 */ #include<stdio.h> int main() { int i=0,c=1,res=2521; while(c) { c=0; for(i=11;i<20;i++) { if(res%i!=0) { c = 1; break; } } res+=1; } printf("Result = %d\n",res-1); }<file_sep>/* Problem 9 - Special Pythagorean Triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. Answer: 31875000 Author: ravikumark815 */ #include<stdio.h> int main() { int a=0,b=0,c=0; for(a=1;a<1000;a++) { for(b=a+1;b<1000-a;b++) { c=1000-(a+b); if((c*c)==(a*a)+(b*b)) { printf("Result = %d\n",a*b*c); } } } return 0; }<file_sep>/* Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? Author: https://github.com/ravikumark815 Answer: 5482660 */ #include <stdio.h> #include <stdint.h> #include <math.h> #define MAX 5000 /* is_pentagonal: return 1 if N is a pentagonal number, else 0 */ int64_t is_pentagonal(int64_t N) { /* If N is a pentagonal number, there exists an integer n such that * N = P(n) = (3n^2 - n) / 2 * * So n is a solution of the equation 3n^2 - n - 2N = 0. * We have D = (-1)^2 - 4(3 * (-2N)) = 24N + 1 * Two solutions: * - X1 = (1 - (sqrt(24N+1) ) / 6 * - X2 = (1 + (sqrt(24N+1) ) / 6 * * Only X2 is a positive solution. So if N is a pentagonal number, the * solution X2 must be an integer. */ double val = (sqrt(24*N+1) + 1) / 6; return val == (int) val; } int32_t main(void) { int64_t i, j; uint64_t min_diff, p[MAX]; /* pre-compute the first 5000 pentagonal numbers */ for (i = 1; i < MAX; ++i) p[i-1] = i * (3*i - 1) / 2; min_diff = INT64_MAX; for (j = 1; j < MAX; ++j) for (i = j-1; i >= 0; --i) if (is_pentagonal(p[j] - p[i]) && is_pentagonal(p[j] + p[i]) && p[j] - p[i] < min_diff) min_diff = p[j] - p[i]; printf("Problem 44: %ld\n", min_diff); return 0; }<file_sep>/* The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? Author: https://github.com/ravikumark815 Answer: 55 */ #include <stdio.h> #include <stdint.h> #define MAX 1000000 int8_t sieve[MAX]; int64_t rotate(int64_t n) { int32_t n_digits, m; m = n; for (n_digits = 0; m > 0; m /= 10) ++n_digits; for (m = 1; n_digits > 1; --n_digits) m *= 10; return m * (n%10) + n/10; } void init_sieve(void) { int32_t i, j; for (i = 0; i < MAX; ++i) sieve[i] = 1; sieve[0] = sieve[1] = 0; for (i = 2; i < MAX; ++i) if (sieve[i]) for (j = 2*i; j < MAX; j += i) sieve[j] = 0; } int32_t is_circular(int64_t n) { int64_t rotated; if (!sieve[n]) return 0; rotated = rotate(n); while (rotated != n) { if (!sieve[rotated]) return 0; rotated = rotate(rotated); } return 1; } int32_t main(void) { int32_t i, answer; init_sieve(); for (i = 0, answer = 0; i < MAX; ++i) if (is_circular(i)) ++answer; printf("Result: %d\n", answer); return 0; }<file_sep>/* Problem 1 - Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Answer: 233168 Author: ravikumark815 */ #include<stdio.h> int main() { int i=0,res=0; for(i=3;i<1000;i++) { if(i%3==0||(i%5==0)) res = res+i; } printf("Result = %d\n",res); }<file_sep>/* Problem 4 - Largest Prime Factor A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. Answer: 906609 Author: ravikumark815 */ #include<stdio.h> int palindrome(int n); int main() { int i=0,j=0,res=0; for(i=100;i<=999;i++) { for(j=100;j<=999;j++) { if(i*j==palindrome(i*j) && i*j>res) res = i*j; } } printf("Result = %d\n",res); return 0; } int palindrome(int n) { int rev=0; while(n){ rev = 10*rev+n%10; n/=10; } return rev; }<file_sep>/* Problem 3 - Largest Prime Factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? Answer: 6857 Author: ravikumark815 */ #include<stdio.h> #include<stdlib.h> int main() { unsigned long long n=600851475143; unsigned long long i; for(i=2ULL;i<n;i++) { while(n%i==0) { n/=i; } } printf("Result = %llu\n",n); return 0; }<file_sep>/* Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? Author: https://github.com/ravikumark815 Answer: 871198282 */ #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_VOCAB_SIZE 6000 /* Function used by qsort to sort alphabetically names. */ int32_t cmp_names(const void *a, const void *b) { return strcmp(*(const char **) a, *(const char **) b); } int32_t main() { /* Open file. */ FILE *file = fopen("names.txt", "r"); if (file == NULL) { printf("[ERROR] Unable to open names.txt, exiting.\n"); return 1; } /* Parse and store names. */ uint8_t **names, MAX_LENGTH = 50, l = 0; int32_t n_words = 0, c; names = (uint8_t**)calloc(MAX_VOCAB_SIZE, sizeof(uint8_t*)); names[0] = (uint8_t*)calloc(MAX_LENGTH, sizeof(uint8_t)); while ((c = getc(file)) != EOF) { if (c == ',') /* word separator */ { l = 0; names[++n_words] = (uint8_t*)calloc(MAX_LENGTH, sizeof(uint8_t)); } else if (c == '"') continue; else names[n_words][l++] = c; } /* No ',' after last word, but counter needs to be incremented. */ ++n_words; /* Sort words alphabetically. */ qsort(names, n_words, sizeof(const uint8_t*), cmp_names); /* Compute total sum of scores of all names. */ uint64_t total = 0, score; for (int32_t pos = 0; pos < n_words; ++pos) { score = 0; for (int32_t i = 0; names[pos][i] != 0; ++i) score += names[pos][i] - 'A' + 1; total += score * (pos+1); } printf("Result: %" PRIu64 "\n", total); /* Clear allocated memory. */ for (int32_t i = 0; i < n_words; ++i) free(names[i]); free(names); fclose(file); return 0; }<file_sep>/* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? Author: https://github.com/ravikumark815 Answer: 2783915460 */ #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> /* Return the factorial of n. */ int32_t factorial(int32_t n) { int32_t p = 1; while (n-- > 1) p *= (n+1); return p; } int32_t main() { int32_t N = 1000000-1, SIZE = 10, digits_left = SIZE, i, d; uint64_t answer = 0; uint8_t* digits = (uint8_t*)calloc(SIZE, sizeof(uint8_t)); for (i = 0; i < SIZE; ++i) digits[i] = i; for (i = 1; i < SIZE; ++i) { d = N/factorial(SIZE-i); N %= factorial(SIZE-i); answer = answer*10 + digits[d]; for (int32_t j = d; j < digits_left; ++j) digits[j] = digits[j+1]; --digits_left; if (N == 0) break; } for (int32_t j = 0; j < digits_left; ++j) answer = answer*10 + digits[j]; printf("Result: %" PRIu64 "\n", answer); free(digits); return 0; }<file_sep>/* Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? Author: https://github.com/ravikumark815 Answer: 932718654 */ #include <stdio.h> #include <stdint.h> int32_t is_pandigital(int64_t n) { int8_t digits[10] = {0}; while (n > 0) { ++digits[n%10]; n /= 10; } for (n = 1; n < 10; ++n) if (digits[n] != 1) return 0; return digits[0] == 0; } int64_t concatenate_products(int64_t n) { int64_t i, d, product = n; for (i = 2; product <= 100000000; ++i) { d = i * n; while (d > 0) { product = product * 10; d /= 10; } product += i * n; } return product; } int32_t main(void) { int64_t i, p, maximum = 0; for (i = 1; i < 100000; ++i) { p = concatenate_products(i); if (is_pandigital(p) && p > maximum) maximum = p; } printf("Problem 38: %ld\n", maximum); return 0; } <file_sep>/* The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? Author: https://github.com/ravikumark815 Answer: 162 */ #include <ctype.h> #include <stdio.h> #include <stdint.h> #include <math.h> #define MAXLEN 100 /* word_value: return the sum of each letter value in string s */ int32_t word_value(char *s) { int32_t val; for (val = 0; *s != '\0'; ++s) val += (*s - 'A' + 1); return val; } /* is_triangular: return 1 if n is a triangular number (it can be written as * m(m+1) / 2 ) */ int32_t is_triangular(int32_t n) { int32_t m = (int32_t) sqrt(n*2); return m*(m+1) / 2 == n; } /* read_word: read a word from a file that is like "A","ABILITY","ABLE"... */ int32_t read_word(FILE *fp, char *dest) { int32_t c; /* skip quotes and comma */ while ((c = fgetc(fp)) != EOF && !isupper(c)) ; *dest++ = c; /* read letters until it finds a comma or a quote */ while ((c = fgetc(fp)) != EOF && isupper(c)) *dest++ = c; *dest = '\0'; return c; } int32_t main(void) { FILE *fp; char word[MAXLEN]; int32_t answer = 0; fp = fopen("words-e42.txt", "r"); while (read_word(fp, word) != EOF) if (is_triangular(word_value(word))) ++answer; printf("Problem 42: %d\n", answer); return 0; }<file_sep>/* Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? Answer: 669171001 */ #include <inttypes.h> #include <stdio.h> #include <stdint.h> int32_t main() { uint64_t answer, n; answer = 1; for (n = 3; n < 1002; n += 2) answer += 4*n*n - 6*(n-1); printf("Result: %" PRIu64 "\n", answer); return 0; }<file_sep>/* The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. Author: https://github.com/ravikumark815 Answer: 748317 */ #include <stdio.h> #include <stdint.h> #define MAX 1000000 int8_t sieve[MAX]; int32_t is_truncatable_prime(int64_t n) { int64_t m; for (m = n; m > 0; m /= 10) if (!sieve[m]) return 0; for (m = 1; n / m > 10; m *= 10) ; for (n %= m; n > 0; m /= 10, n %= m) if (!sieve[n]) return 0; return 1; } void init_sieve(void) { int32_t i, j; for (i = 0; i < MAX; ++i) sieve[i] = 1; sieve[0] = sieve[1] = 0; for (i = 2; i < MAX; ++i) if (sieve[i]) for (j = 2*i; j < MAX; j += i) sieve[j] = 0; } int32_t main(void) { int32_t i, answer; init_sieve(); for (i = 8, answer = 0; i < MAX; ++i) if (is_truncatable_prime(i)) answer += i; printf("Result: %d\n", answer); return 0; }<file_sep>/* Problem 12 - Highly divisible triangular number The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? Answer: 76576500 Author: ravikumark815 */ #include <stdio.h> #include <stdlib.h> unsigned long long factors(unsigned long long n); void main(void) { unsigned long long i=0,c=0,j=1,tri=0; while(1) { tri = tri+i; if(factors(tri)<500){ i=i+1; } else{ break; } } printf("Result = %llu\n",tri); } unsigned long long factors(unsigned long long n) { unsigned long long i=0,c=0,res=1; for(i=2;i<=n;i++) { c=0; while(n%i==0){ c=c+1; n=n/i; } res*=(c+1); } return res; }<file_sep># Euler ![alt text](https://github.com/ravikumark815/euler-project/blob/master/Euler.jpg) Project Euler is a series of challenging problems that require mathematical and programming skills. Somebody who enjoys learning a new coding language, Euler Project is going to be a fun journey. This code is provided for reference only. You may republish any of this code verbatim with author and URL info intact. ## Solutions: Problem # | Result ---------- | -------- 1 | 233168 2 | 4613732 3 | 6857 4 | 906609 5 | 232792560 6 | 25164150 7 | 104743 8 | 23514624000 9 | 31875000 10 | 142913828922 11 | 70600674 12 | 76576500 13 | 5537376230 14 | 837799 15 | 137846528820 16 | 1366 17 | 21124 18 | 1074 19 | 171 20 | 648 21 | 31626 22 | 871198282 23 | 4179871 24 | 2783915460 25 | 4782 26 | 983 27 | -59231 28 | 669171001 29 | 9183 30 | 443839 31 | 73682 32 | 45228 33 | 100 34 | 40730 35 | 55 36 | 872187 37 | 748317 38 | 932718654 39 | 840 40 | 210 41 | 7652413 42 | 162 43 | 16695334890 44 | 5482660 45 | 1533776805 46 | 5777 47 | 134043 48 | 9110846700 49 | 296962999629 50 | 997651 51 | 121313 52 | 142857 53 | 4075 54 | 376 55 | 249 56 | 972 57 | 153 58 | 26241 59 | 129448<file_sep>/* You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? Author: https://github.com/ravikumark815 Answer: 171 */ #include <stdio.h> #include <stdint.h> int32_t main() { int32_t days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int32_t weekday = 2, c = 0, year, month; for (year = 1901; year < 2001; ++year) for (month = 0; month < 12; ++month) { if (year%4 == 0 && month == 1) weekday += 29; else weekday += days[month]; weekday %= 7; if (weekday == 0) ++c; } printf("Result: %d\n", c); return 0; }<file_sep>/* In the United Kingdom the currency is made up of pound (£) and pence (p). There are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? Author: https://github.com/ravikumark815 Answer: 443839 */ #include <stdio.h> #include <stdint.h> #define TOTAL 200 /* 2 pounds = 200p */ int32_t main(void) { int32_t coins[8] = {1, 2, 5, 10, 20, 50, 100, 200}; int64_t ways[TOTAL+1] = {0}; int32_t i, j; ways[0] = 1; for (i = 0; i < 8; ++i) for (j = coins[i]; j <= TOTAL; ++j) ways[j] += ways[j - coins[i]]; printf("Result: %ld\n", ways[TOTAL]); return 0; }<file_sep>/* It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. Author: https://github.com/ravikumark815 Answer: 142857 */ #include <stdio.h> #include <stdint.h> /* is_permutation: return 1 if b is a permutation of a, 0 otherwise */ int32_t is_permutation(int32_t a, int32_t b) { /* count the occurrence of each digit of a and b. They are permutation * if they have the same number of occurrence of each digit */ uint8_t i, digits_a[10] = {0}, digits_b[10] = {0}; while (a > 0) { ++digits_a[a%10]; a /= 10; } while (b > 0) { ++digits_b[b%10]; b /= 10; } for (i = 0; i < 10; ++i) if (digits_a[i] != digits_b[i]) return 0; return 1; } /* find the smallest integer n such that 2n, 3n, 4n, 5n and 6n are all * permutations of n */ int32_t main(void) { int32_t n; for (n = 1; ; ++n) if (is_permutation(n, 2*n) && is_permutation(n, 3*n) && is_permutation(n, 4*n) && is_permutation(n, 5*n) && is_permutation(n, 6*n)) { printf("Problem 52: %d\n", n); break; } return 0; }<file_sep>/* The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. Author: https://github.com/ravikumark815 Answer: 100 */ #include <stdio.h> #include <stdint.h> int32_t is_curious(int32_t num, int32_t den) { int32_t a, b, c, d; a = num/10; b = num%10; c = den/10; d = den%10; if (b == 0 && d == 0) return 0; if (a == c) return (float) b / d == (float) num / den; else if (a == d) return (float) b / c == (float) num / den; else if (b == c) return (float) a / d == (float) num / den; else if (b == d) return (float) a / c == (float) num / den; return 0; } void simplify(int64_t *num, int64_t *den) { int64_t i; for (i = *num; i > 1; --i) if (*num%i == 0 && *den%i == 0) { *num /= i; *den /= i; } } int32_t main(void) { int32_t a, b; int64_t num, den; num = den = 1; for (a = 10; a < 100; ++a) for (b = a+1; b < 100; ++b) if (is_curious(a, b)) { num *= a; den *= b; } simplify(&num, &den); printf("Result: %ld\n", den); return 0; }<file_sep>/* Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? Author: https://github.com/ravikumark815 Answer: 137846528820 */ #include <inttypes.h> #include <stdio.h> #include <stdint.h> /* return the binomial coefficient C(n,k) (n choose k) */ uint64_t binomial_coef(uint64_t n, uint64_t k) { uint64_t res = 1; if (k > n-k) k = n-k; for(uint64_t i = 0; i < k; ++i) { res *= (n-i); res /= (i+1); } return res; } int32_t main() { uint64_t answer = binomial_coef(40, 20); printf("Problem 15: %" PRIu64 "\n", answer); return 0; } <file_sep>/* Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. Author: https://github.com/ravikumark815 Answer: 31626 */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> /* Return the sum of all divisors of n (n is not included in the sum). */ int32_t sum_divisors(int32_t n) { int32_t s = 1; /* 1 is ALWAYS a divisor of n */ for (int32_t i = 2; i*i < n+1; ++i) { if (n%i == 0) { if (n/i == i) s += i; else s += i + n/i; } } return s; } int32_t main() { int32_t SIZE = 10000, sum_amicable = 0, i; int32_t* sum_div = (int32_t*) calloc(SIZE, sizeof(int32_t)); sum_div[0] = 0; /* special case, 1 has no proper divisors. */ /* Find sum of proper divisors for integers below 10000. */ for (i = 1; i < SIZE; ++i) sum_div[i] = sum_divisors(i+1); /* Find amicable numbers (same sum of divisors but different numbers). * There is -1 because d(i) is stored at the cell i-1. */ for (i = 1; i < SIZE+1; ++i) if (sum_div[sum_div[i-1]-1] == i && i != sum_div[i-1]) sum_amicable += i; printf("Result: %d\n", sum_amicable); free(sum_div); return 0; }<file_sep>/* We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. Author: https://github.com/ravikumark815 Answer: 45228 */ #include <stdio.h> #include <stdint.h> int32_t is_pandigital(int32_t mul1, int32_t mul2, int32_t product) { int32_t counter[10] = {0}; int32_t i; for (; mul1 > 0; mul1 /= 10) ++counter[mul1%10]; for (; mul2 > 0; mul2 /= 10) ++counter[mul2%10]; for (; product > 0; product /= 10) ++counter[product%10]; for (i = 1; i < 10; ++i) if (counter[i] != 1) return 0; return counter[0] == 0; } int32_t main(void) { int32_t a, b, c, answer = 0; int8_t done[10000] = {0}; for (a = 1; a < 10; ++a) for (b = 1000; b < 10000; ++b) if (is_pandigital(a, b, c=a*b) && !done[c]) { answer += c; done[c] = 1; } for (a = 10; a < 100; ++a) for (b = 100; b < 1000; ++b) if (is_pandigital(a, b, c=a*b) && !done[c]) { answer += c; done[c] = 1; } printf("Result: %d\n", answer); return 0; }<file_sep>/* A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. Author: https://github.com/ravikumark815 Answer: 4179871 */ #include <inttypes.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> int32_t sum_divisors(int32_t n) { int32_t s = 1; for (int32_t i = 2; i*i < n+1; ++i) if (n%i == 0) { if (n/i == i) s += i; else s += i + n/i; } return s; } int32_t main() { uint64_t total = 0; int32_t SIZE = 28124, i, j; int32_t* abundant = (int32_t*)calloc(SIZE, sizeof(int32_t)); for (i = 2; i < SIZE; ++i) abundant[i] = sum_divisors(i) > i ? 1 : 0; uint8_t is_sum_abundants; for (i = 1; i < SIZE; ++i) { is_sum_abundants = 0; for (j = 1; j < i/2+1; ++j) if (abundant[j] && abundant[i-j]) { is_sum_abundants = 1; break; } if (!is_sum_abundants) total += i; } printf("Result: %" PRIu64 "\n", total); free(abundant); return 0; }<file_sep>/* The first two consecutive numbers to have two distinct prime factors are: 14 = 2 × 7 15 = 3 × 5 The first three consecutive numbers to have three distinct prime factors are: 644 = 2² × 7 × 23 645 = 3 × 5 × 43 646 = 2 × 17 × 19. Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers? Author: https://github.com/ravikumark815 Answer: 134043 */ #include <stdio.h> #include <stdint.h> #define N 1000000 uint8_t number_prime_factor[N]; /* init_NPF: initialize the Number of Prime Factor (NPF) array. */ void init_NPF(void) { uint32_t i, j; /* similar to Eratosthene sieve. Initialize all numbers with 0 prime * factors counter. Goes from 2 to N. If the current number has 0 prime * factor, it means it's a prime, so increment the counter for all * multiples of this prime (e.g. 2 is prime so every even number has * at least 2 as a prime factor). */ for (i = 0; i < N; ++i) number_prime_factor[i] = 0; for (i = 2; i < N; ++i) if (number_prime_factor[i] == 0) for (j = 2*i; j < N; j += i) ++number_prime_factor[j]; } /* find the first 4 consecutive integers that have 4 different prime factors */ int32_t main(void) { int32_t i; init_NPF(); for (i = 0; i < N-4; ++i) { if (number_prime_factor[i] != 4) continue; if (number_prime_factor[i+1] != 4) continue; if (number_prime_factor[i+2] != 4) continue; if (number_prime_factor[i+3] != 4) continue; break; } printf("Problem 47: %d\n", i); return 0; }<file_sep>/* The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? Author: https://github.com/ravikumark815 Answer: 4782 */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> void copy(uint8_t* a, uint8_t* b, int32_t size) { for (int32_t i = 0; i < size; ++i) b[i] = a[i]; } void add(uint8_t* a, uint8_t* b, int32_t size) { int32_t carry = 0, d; for (int32_t i = 0; i < size; ++i) { d = a[i] + b[i] + carry; b[i] = d%10; carry = d/10; } } int32_t main() { int32_t SIZE = 1000, n; uint8_t *a, *b, *c; a = (uint8_t*)calloc(SIZE, sizeof(uint8_t)); b = (uint8_t*)calloc(SIZE, sizeof(uint8_t)); c = (uint8_t*)calloc(SIZE, sizeof(uint8_t)); a[0] = 1; b[0] = 1; n = 2; while (b[SIZE-1] == 0) { copy(b, c, SIZE); add(a, b, SIZE); copy(c, a, SIZE); ++n; } printf("Result: %d\n", n); free(a); free(b); free(c); return 0; } <file_sep>/* A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. Answer: 983 */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> int32_t main() { int32_t MAX = 1000, longest_cycle = 0, answer, remainder, pos, d, i; int32_t *already_seen = (int32_t*)calloc(MAX, sizeof(int32_t)); for (d = MAX; d > 1; --d) { if (longest_cycle > d-1) break; for (i = 0; i < MAX; ++i) already_seen[i] = 0; remainder = 1; pos = 0; while (already_seen[remainder] == 0 && remainder != 0) { already_seen[remainder] = pos; remainder = (remainder*10)%d; ++pos; } if (pos - already_seen[remainder] > longest_cycle) { longest_cycle = pos - already_seen[remainder]; answer = d; } } printf("Result: %d\n", answer); free(already_seen); return 0; }<file_sep>/* The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) Author: https://github.com/ravikumark815 Answer: 872187 */ #include <stdio.h> #include <stdint.h> #define MAX 1000000 int32_t is_palindrom(int32_t n, int32_t base) { int32_t m, p; m = n; for (p = 0; n > 0; n /= base) p = base * p + n%base; return p == m; } int32_t main(void) { int i, answer; for (i = 1, answer = 0; i < MAX; ++i) if (is_palindrom(i, 10) && is_palindrom(i, 2)) answer += i; printf("Result: %d\n", answer); return 0; }<file_sep>/* It was proposed by <NAME> that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? Author: https://github.com/ravikumark815 Answer: 5777 */ #include <stdio.h> #include <stdint.h> #define N 10000 uint8_t sieve[N]; /* init_sieve: initialize the array to test if a number is prime. */ void init_sieve(void) { uint32_t i, j; /* at first, every integer is considered to be prime, except 0 and 1 */ for (i = 0; i < N; ++i) sieve[i] = 1; sieve[0] = sieve[1] = 0; for (i = 2; i < N; ++i) if (sieve[i]) /* prime, mark all its multiples as non prime */ for (j = 2*i; j < N; j += i) sieve[j] = 0; } /* is_goldbach: return 1 if n respects the Goldbach conjecture (can be written * as the sum of a prime and twice a square), 0 otherwise. */ int32_t is_goldbach(int32_t n) { int32_t i; for (i = 1; i*i*2 < n; ++i) if (sieve[n - i*i*2]) return 1; return 0; } /* print the smallest odd non-prime number that does not respect Goldbach's * conjecture */ int32_t main(void) { int32_t i; init_sieve(); /* last given example is 33, so start at next odd number */ for (i = 35; i < N; i += 2) if (!sieve[i] && !is_goldbach(i)) { printf("Problem 46: %d\n", i); break; } return 0; }<file_sep>/* Problem 7 - 10001st Prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? Answer: 104743 Author: ravikumark815 */ #include<stdio.h> int isprime(int n); int main() { int i=2,j=0,c=1,res = 0; while(c<10002) { if (isprime(i)) { c+=1; res = i; } i+=1; } printf("Result = %d\n",res); return 0; } int isprime(int n) { if (n==1||n==2) return 1; else if (n%2==0)return 0; else { for(int i=3;i<n/2;i+=2) { if(n%i==0) return 0; } return 1; } }<file_sep>/* Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? Answer: 9183 */ #include <stdio.h> #include <stdint.h> #define MIN 2 #define MAX 100 int32_t main(void) { int32_t a, b, c, i, n, exponent, n_duplicate; uint8_t done[MAX-MIN+1] = {0}; n_duplicate = 0; for (a = MIN; a <= MAX; ++a) { n = a; for (b = MIN; b <= MAX; ++b) { n *= a; if (n > MAX || done[n-MIN]) break; done[n-MIN] = 1; if (b == 2) { n_duplicate += MAX/2 - 1; continue; } for (c = MIN; c <= MAX; ++c) { exponent = b * c; if (exponent <= MAX) { ++n_duplicate; continue; } for (i = MIN; i < b; ++i) if (!(exponent%i) && exponent/i <= MAX) { ++n_duplicate; break; } } } } n = (MAX-MIN+1) * (MAX-MIN+1); printf("Result: %d\n", n - n_duplicate); return 0; }
3d7b9865fe84ae14241c489682a81cbdfebb29aa
[ "Markdown", "C" ]
39
C
ravikumark815/euler-project
8a2666f159d67107a44f0d1cd92e9c461f070e42
46cbc36e1a6feafd7b9d7f7054209caba3ca348e
refs/heads/master
<file_sep>$(window).on("load", function() { var tbody = document.querySelector("#lec4Accordion"); var template = document.querySelector('#pseudocode-listing'); console.log(tbody, template) // Clone the new row and insert it into the table var clone = template.content.cloneNode(true); var body = clone.querySelector(".card-body"); var script = clone.querySelector(".script") tbody.appendChild(clone); var item = tbody.querySelector("") src = "https://emgithub.com/embed.js?target=https%3A%2F%2Fgithub.com%2FCMU-IDeeL%2Fpseudocode%2Fblob%2Fmaster%2Fbackprop%2Flec4_forward_pass.plaintext&style=github&showLineNumbers=on&showFileMeta=on" /* td[0].textContent = "1235646565"; td[1].textContent = "Stuff"; */ // Clone the new row and insert it into the table /*var clone2 = template.content.cloneNode(true); td = clone2.querySelectorAll("td"); td[0].textContent = "0384928528"; td[1].textContent = "Acme Kidney Beans 2"; tbody.appendChild(clone2);*/ }) <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>11-785 Deep Learning</title> <!-- display nicely on phones --> <meta name="viewport" content="width=device-width, initial-scale=1.0"</meta> <!-- bootstrap 3 --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY> crossorigin="anonymous"> <!-- fonts --> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,300italic' rel='stylesheet' type='text/css'> <link href="main.4.css" rel="stylesheet" type="text/css"> </head> <div class="container titlebar"> <div class="row"> <!--div class="titlebar-img title-col vcenter"> <img id="logo" src="./img/brain.png"> </div--> <div class="title-col vcenter" style="color:#A80000;font-weight:bold;text-align:center;width:100%"> <div id="title"><b>11-785</b> Introduction to Deep Learning</div> <div class="subtitle"><i>Fall 2020</i></div> </div> </div> </div> <body> <div class=" container"> <div class="row"> <h2> Project Video Instructions</h2> <p>As we inch closer to the project submission timeline, we wanted to release a set of instructions to create a good presentation video. Please be mindful that these instructions only serve to be a guideline of what you aim to achieve. We do not mandate following the order or time breakdown perfectly, as long as you address all the high-level components. We have also linked the set of Top 25 video presentations from S'20 on the course website which can be <a href="http://deeplearning.cs.cmu.edu/shared/gallery.html" target="_blank" rel="noopener noreferrer">found here.</a></p> <div></div> <div><h3>Instructions:</h3> Please try to adhere to the time limit, but also make sure you speak clearly and coherently so that your audience learns from your presentation. Total video length: 3 - 5 minutes (please try and not exceed the 5-minute limit, that said a few seconds here and there doesn't matter)</div> <ol> <li>The video can be slides with voice over but you can also get creative. There is no rule on who has to speak, it is left to your team's discretion.</li> <li>Use a screen - recording (screen-casting) tool. Most MacBooks and Windows laptops are equipped with an inbuilt one. </li> <li>The video must start with a slide of the title of the project, team-name, and names of group members.</li> <li>The video should be fluid enough so that you are able to convince an audience without any familiarity about your project topic, why your project topic is worth attempting, the goals you have accomplished, the methods deployed, the results achieved, and how were they similar/different to existing results, and why is it so!</li> </ol> <div><h3>Suggestive timeline of the video:</h3> <h3>1. Description of the problem(20 - 50 seconds):</h3></div> <ul> <li>Describe the problem at hand - What are you trying to solve, and why?</li> <li>Additionally, mention the significance of the problem - What do you think is the practical impact of your work?</li> <li>The novelty of the problem - Has the problem been solved before? If so, how are your results different from the current approach.</li> </ul> <h3>2. Task (&lt;= 30 seconds):</h3> <ul> <li>Mention whether your work is a re-implementation of a paper, application of an existing approach on a new dataset, or a novel approach.</li> <li>Talk about the dataset used, size of the datasets how some examples from the dataset in slides when possible in a tabulated fashion. A summary description of the dataset is very well appreciated. Also briefly mention any assumptions and any data transformations that were required.</li> </ul> <h3>3. Approach or Methods(1 minute - 2 minutes):</h3> <ul> <li>Briefly describe the overall approach.</li> <li>Possibly include a flow-chart or diagram of your pipeline and/or architecture. Describe in detail the novel and/or the most significant components of your methods. Use diagrams wherever possible to make the presentation more comprehensible.</li> </ul> <h3>4. Results and Discussion (&lt;= 1 minute):</h3> <ul> <li>Describe your evaluation metrics and talk about the performance achieved.</li> <li>Report the best, interesting and unexpected results i.e no need to show the results for all your experiments. But don’t forget to emphasize on your takeaways after assessing these results - Why did you get those results? Why did it work better/worse than other approaches? Possibly include diagrams comparing your work and others' work. It is always good to answer the WHY for your results achieved and not just HOW?</li> </ul> <h3>5. Conclusions (&lt;30 seconds): </h3> <ul> <li>Briefly describe your conclusions from the observed results. Does your conclusion have a real-world impact?</li> </ul> <strong>A general note: please resist the urge to describe everything in great detail to avoid going over the time limit</strong> <br /> <br /> </div> </div> <div class=" container"> <div class="row"> </div> </div> </body> </html> <file_sep><!DOCTYPE html> <html> <head> <title>MathJax TeX Test Page</title> <script type="text/x-mathjax-config"> MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}}); </script> <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"> </script> </head> <body> **Forward Pass** ~ Input: $D$ dimensional vector $\mathbf{x} = [x_j, j=1..D]$ $\\$ Set: $\\$ $\quad $ $D_0=0,$ is the width of the $0^\text{th}$ (input) layer $\\$ $\quad $ $y_j^{(0)}=x_j,$ $j=1..D$ $\\$ $\quad $ $y_0^{(k=1..N)}=x_0=1$ $\\$ For layer $k = 1..N$ $\\$ $\quad $ For $j=1..D_k$ $\\$ $\qquad$ $z_j^{(k)}=\sum_{i=0}^{N_k}w_{i,j}^{(k)}y_i^{(k-1)}$ $\\$ $\qquad$ $y_j^{(k)}=f_k(z_j^{(k)})$ $\\$ Output: $\\$ $\quad $ $Y=y_j^{(N)},$ $j=1..D_N$ $\\$ </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>11-785 Deep Learning</title> <!-- display nicely on phones --> <meta name="viewport" content="width=device-width, initial-scale=1.0"</meta> <!-- bootstrap 3 --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY> crossorigin="anonymous"> <!-- fonts --> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,300italic' rel='stylesheet' type='text/css'> <link href="main.3.css" rel="stylesheet" type="text/css"> </head> <div class="container titlebar"> <div class="row"> <!--div class="titlebar-img title-col vcenter"> <img id="logo" src="./img/brain.png"> </div--> <div class="title-col vcenter" style="color:#A80000;font-weight:bold;text-align:center;width:100%"> <div id="title"><b>11-785</b> Introduction to Deep Learning</div> <div class="subtitle"><i>Fall 2020</i></div> </div> </div> </div> <body> <div class=" container"> <div class="row"> <h2> Project Video Instructions</h2> <ol> <li>Total video length: 3 - 5 minutes</li> <li>The video must be slides with voice over.</li> <li>Free softwares available for screen casting. </li> <ol> <li>Screen-o-matic: https://screencast-o-matic.com/screen-recorder</li> <li>Camtasia(free trial): https://www.techsmith.com/video-editor.html</li> <li>Others are also available</li> </ol> <li>Video must start with a slide of the title of the project, group name and names of the group members. </li> <li>Videos must contain enough information to be understood by someone not familiar with your work.</li> </ol> <h3>Contents:</h3> <h3>1. Description of the problem (20 - 50 seconds)</h3> <ol> <li>Description of the problem</li> <li>Significance of the problem</li> <li>Has the problem been solved before?If so, how good was the solution.</li> </ol> <h3>2. Task (&lt;= 30 seconds)</h3> <ol> <li>Mention whether your work is re-implementation of a paper, application of an existing approach on a new dataset or a novel approach</li> <li>Dataset used, size of the dataset;show some examples from dataset in slides when possible</li> </ol> <h3>3. Approach (1 minute - 2 minutes)</h3> <ol> <li>Start with a brief description of the overall approach; Possibly include a diagram of your pipeline and/or architecture</li> <li>Describe the novel or most significant parts of your approach in greater detail; Use diagrams whenever possible: e.g. how your data is transformed, gradient flow in your model,... </li> </ol> <h3>4. Results and Discussion (&lt;= 1 minute)</h3> <ol> <li>Describe how performance was evaluated</li> <li>Report the best, interesting and unexpected results i.e no need to show the results for all your experiments</li> <li>Why did you get those results? Why did it work better/worse than other approaches?Possibly include diagrams comparing your work and others work. </li> </ol> <h3>5. Conclusions (&lt;30 seconds)</h3> <p>General note:Resist the urge to describe everything in great detail to avoid going over the time limit</p> </div> </div> <div class=" container"> <div class="row"> </div> </div> </body> </html> <file_sep>import torch import torch.nn as nn import math class InvertedResidualBlock(nn.Module): """ Intuitively, layers in MobileNet can be split into "feature mixing" and "spatial mixing" layers. You can think of feature mixing as each pixel "thinking on its own" about its own featuers, and you can think of spatial mixing as pixels "talking with each other". Alternating these two builds up a CNN. In a bit more detail: - The purpose of the "feature mixing" layers is what you've already seen in hw1p2. Remember, in hw1p2, we went from some low-level audio input to semantically rich representations of phonemes. Featuring mixing is simply a linear layer (a weight matrix) that transforms simpler features into something more advanced. - The purpose of the "spatial mixing" layers is to mix features from different spatial locations. You can't figure out a face by looking at each pixel on its own, right? So we need 3x3 convolutions to mix features from neighboring pixels to build up spatially larger features. """ def __init__(self, in_channels, out_channels, stride, expand_ratio): super().__init__() # Just have to do this for all nn.Module classes # Can only do identity residual connection if input & output are the # same channel & spatial shape. if stride == 1 and in_channels == out_channels: self.do_identity = True else: self.do_identity = False # Expand Ratio is like 6, so hidden_dim >> in_channels hidden_dim = in_channels * expand_ratio """ What is this doing? It's a 1x1 convolutional layer that drastically increases the # of channels (feature dimension). 1x1 means each pixel is thinking on its own, and increasing # of channels means the network is seeing if it can "see" more clearly in a higher dimensional space. Some patterns are just more obvious/separable in higher dimensions. Also, note that bias = False since BatchNorm2d has a bias term built-in. As you go, note the relationship between kernel_size and padding. As you covered in class, padding = kernel_size // 2 (kernel_size being odd) to make sure input & output spatial resolution is the same. """ self.feature_mixing = nn.Sequential( # TODO: Fill this in! ) """ What is this doing? Let's break it down. - kernel_size = 3 means neighboring pixels are talking with each other. This is different from feature mixing, where kernel_size = 1. - stride. Remember that we sometimes want to downsample spatially. Downsampling is done to reduce # of pixels (less computation to do), and also to increase receptive field (if a face was 32x32, and now it's 16x16, a 3x3 convolution covers more of the face, right?). It makes sense to put the downsampling in the spatial mixing portion since this layer is "in charge" of messing around spatially anyway. Note that most of the time, stride is 1. It's just the first block of every "stage" (layer \subsetof block \subsetof stage) that we have stride = 2. - groups = hidden_dim. Remember depthwise separable convolutions in class? If not, it's fine. Usually, when we go from hidden_dim channels to hidden_dim channels, they're densely connected (like a linear layer). So you can think of every pixel/grid in an input 3 x 3 x hidden_dim block being connected to every single pixel/grid in the output 3 x 3 x hidden_dim block. What groups = hidden_dim does is remove a lot of these connections. Now, each input 3 x 3 block/region is densely connected to the corresponding output 3 x 3 block/region. This happens for each of the hidden_dim input/output channel pairs independently. So we're not even mixing different channels together - we're only mixing spatial neighborhoods. Try to draw this out, or come to my (Jinhyung Park)'s OH if you want a more in-depth explanation. https://towardsdatascience.com/a-basic-introduction-to-separable-convolutions-b99ec3102728 """ self.spatial_mixing = nn.Sequential( # TODO: Fill this in! ) """ What's this? Remember that hidden_dim is quite large - six times the in_channels. So it was nice to do the above operations in this high-dim space, where some patterns might be more clear. But we still want to bring it back down-to-earth. Intuitively, you can takeaway two reasons for doing this: - Reduces computational cost by a lot. 6x in & out channels means 36x larger weights, which is crazy. We're okay with just one of input or output of a convolutional layer being large when mixing channels, but not both. - We also want a residual connection from the input to the output. To do that without introducing another convolutional layer, we want to condense the # of channels back to be the same as the in_channels. (out_channels and in_channels are usually the same). """ self.bottleneck_channels = nn.Sequential( # TODO: Fill this in! ) def forward(self, x): out = self.feature_mixing(x) out = self.spatial_mixing(out) out = self.bottleneck_channels(out) if self.do_identity: return x + out else: return out class MobileNetV2(nn.Module): """ The heavy lifting is already done in InvertedBottleneck. Why MobileNetV2 and not V3? V2 is the foundation for V3, which uses "neural architecture search" to find better configurations of V2. If you understand V2 well, you can totally implement V3! """ def __init__(self, num_classes= 7000): super().__init__() self.num_classes = num_classes """ First couple of layers are special, just do them here. This is called the "stem". Usually, methods use it to downsample or twice. """ self.stem = nn.Sequential( # TODO: Fill this in! ) """ Since we're just repeating InvertedResidualBlocks again and again, we want to specify their parameters like this. The four numbers in each row (a stage) are shown below. - Expand ratio: We talked about this in InvertedResidualBlock - Channels: This specifies the channel size before expansion - # blocks: Each stage has many blocks, how many? - Stride of first block: For some stages, we want to downsample. In a downsampling stage, we set the first block in that stage to have stride = 2, and the rest just have stride = 1. Again, note that almost every stage here is downsampling! By the time we get to the last stage, what is the image resolution? Can it still be called an image for our dataset? Think about this, and make changes as you want. """ self.stage_cfgs = [ # expand_ratio, channels, # blocks, stride of first block [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1], ] # Remember that our stem left us off at 16 channels. We're going to # keep updating this in_channels variable as we go in_channels = 16 # Let's make the layers layers = [] for curr_stage in self.stage_cfgs: expand_ratio, num_channels, num_blocks, stride = curr_stage for block_idx in range(num_blocks): out_channels = num_channels layers.append(InvertedResidualBlock( in_channels=in_channels, out_channels=out_channels, # only have non-trivial stride if first block stride=stride if block_idx == 0 else 1, expand_ratio=expand_ratio )) # In channels of the next block is the out_channels of the current one in_channels = out_channels self.layers = nn.Sequential(*layers) # Done, save them to the class # Some final feature mixing self.final_block = nn.Sequential( nn.Conv2d(in_channels, 1280, kernel_size=1, padding=0, stride=1, bias=False), nn.BatchNorm2d(1280), nn.ReLU6() ) # Now, we need to build the final classification layer. self.cls_layer = nn.Sequential( # TODO: Fill this in! # Pool over & collapse the spatial dimensions to (1, 1) # Collapse the trivial (1, 1) dimensions # Project to our # of classes ) self._initialize_weights() def _initialize_weights(self): """ Usually, I like to use default pytorch initialization for stuff, but MobileNetV2 made a point of putting in some custom ones, so let's just use them. """ for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) m.bias.data.zero_() def forward(self, x): out = self.stem(x) out = self.layers(out) out = self.final_block(out) out = self.cls_layer(out) return out<file_sep># Info to know A brain dump about the website... feel free to disregard if you choose a different direction... ## Transitioning between semesters 1. Copy the last semester's folder, e.g. copy F70 to S71 2. Change the index.html's URL for the new semester, e.g. url=./S71/index.html (to update main page) 3. On the mobile menus and desktop headers for the past and current websites, add a link to the new semester 4. Yeet out the content from the new website! ## Organization - F20: F20 website - S20: S20 website - index.html: just links to index.html of current semester - exp: you can push experimental changes here, and then link other course staff to https://deeplearning.cs.cmu.edu/exp/ - shared: pages that don't belong to a particular semester - favicon.ico: website icon, maybe should be the LTI icon - project.css, project.html, projects.js, load_suggestions.js: F20 specific project information, maybe should be in F20 - S20TAs.png, TAs.css, TAs.html: stuff for the acknowledgements page - pics, load_squares, projects.js, gallery.html: stuff for project gallery. If it looks good, would be cool to link from a more central place! ## Pseudocode Page http://deeplearning.cs.cmu.edu/F20/pseudocode.html We got a decent amount done, but didn't finish or verify... see the pseudocode repository for more. Once this gets finished, it would be a good idea for the slides to have code listing numbers, so that this is maintanable. Also, note that this stuff is from S20 lectures. We have a spreadsheet with info about which slides the codes came from. ## Technologies - The main page is built with bootstrap 3, it would be cool to create a new branch, update to latest bootstrap, and then merge. But perhaps time consuming / not necessary - Most other pages are with bootstrap 4, font sizes are bigger by default, there's more features... - Acknowledgements page should probably be ported to bootstrap, right now it's just html/css... - If you continue with the table calendar, it takes a while to make if you do it from scratch; you can make an outline of the table with www.tablesgenerator.com (or just edit the current one) ## Misc - We probably don't need to link quizzes in lectures table, just in the calendar table / bulletin. Not sure it's worth the effort. - The grand vision for the bulletin is that if there's something due soon, you can go to the bulletin and it links to everything relevant about that assignment... piazza posts, kaggles, autolab, canvas assignment, etc. - The assignments table should mirror all of these links ^ - If you continue with the chatbot, Akshat has information about it Or do your own thing :)
4daa4303d826215e9b84514159e73562ad199cea
[ "JavaScript", "Python", "HTML", "Markdown" ]
6
JavaScript
CMU-IDeeL/CMU-IDeeL.github.io
ae58d6505c75dafd525beda8f03df59e6b7f7457
b6094b94b39438e16933b87f0eba48869f95d5d4
refs/heads/master
<repo_name>bacitracin/Bitly-URL-Unwrapper<file_sep>/README.md # Bitly-URL-Unwrapper Takes CSVs with shortened Twitter links in "T.co" form (common for Radian6 & Sysomos outputs), and then returns a CSV with the original/decoded URL added in a second column. <file_sep>/Bitly_URL_unwrapper5.12.py # -*- coding: utf-8 -*- """ Edited on Mon May 11 13:00:14 2015 Shortened Twitter Link Unwrapper (Doesn't work on all vanity urls, best to use http://t.co link from the Radian6 / Sysomos CSV Download to avoid issues.) @author: Tracy """ #pip install these packages if you don't already have them import urllib2 import csv short_urls = [] unwrapped_urls = [] #Update name of row with shortened links here f = open('shortlinks20.csv') csv_f = csv.reader(f) for row in csv_f: short_urls.append(row) try: response = urllib2.urlopen(row[0], timeout = 60) url_destination = response.geturl() unwrapped_urls.append(url_destination) except urllib2.HTTPError, e: url_destination = "Error HTTP Error" unwrapped_urls.append(url_destination) except urllib2.URLError, e: url_destination = "Error URL Error" unwrapped_urls.append(url_destination) except urllib2.HttpException, e: url_destination = "Error HTTP Exception" unwrapped_urls.append(url_destination) except Exception: url_destination = "Exception" unwrapped_urls.append(url_destination) else: continue zipped = zip(short_urls, unwrapped_urls) f.close() #Update the name of the resulting file with open('shortlinks20UNWRAP.csv', 'wb') as newfile: writer = csv.writer(newfile) writer.writerows(zipped) newfile.close() print("All Done! Check it out!")
0f03c2a64384d41b3d277a87f944d913be79a297
[ "Markdown", "Python" ]
2
Markdown
bacitracin/Bitly-URL-Unwrapper
db2a3cf9acd4abd4e3609450c0f6cfecf3ec07fe
54fda091de31868fc9b1d6ae4dad64da4d6d802e
refs/heads/master
<file_sep>//: [Previous](@previous) import Foundation var str = "Hello, playground" var number = 10 func add(_ num: inout Int) { num += 20 } add(&number) print("值为",separator:"",terminator: "") print(number ) //: [Next](@next) <file_sep>//: [Previous](@previous) import Foundation var str = "Hello, playground" var arr = [1,2,3,4] var arr2 = arr.map{$0 * 2} print("\(arr2)") var arr3 = arr.filter { $0 % 2 == 0 } print("\(arr3)") var num1: Int? = 10 var num2 = (num1 != nil) ? (num1! + 10) : nil var num3 = num1.map { $0 + 10 } print("\(num2!)-\(num3!)") //: [Next](@next) <file_sep>//: [Previous](@previous) import Foundation var str = "Hello, playground" let doubleHexAdecimal = 0xfp2 print("\(doubleHexAdecimal)") let int1: UInt16 = 2_000 let int2: UInt8 = 1 let int3 = int1 + UInt16(int2) // tuple let http404 = (404,"error") http404.0 http404.1 let (h1,h2) = http404 h1 h2 //: [Next](@next) <file_sep>//: [Previous](@previous) import Foundation var str = "Hello, playground" MemoryLayout<Int>.size // 分配占用空间大小 MemoryLayout<Int>.stride // 实际用到的大小 MemoryLayout<Int>.alignment // 内存对齐 MemoryLayout.size(ofValue: str) enum Password { case number(Int,Int,Int,Int) case other } var pwd = Password.number(1, 2, 3, 4) pwd = .other MemoryLayout.size(ofValue: pwd) enum Season:String { case spring = "1" case summer = "2" case autumn = "3" case winter = "4" } var s = Season.spring s.rawValue MemoryLayout<Season>.size let age = 21 if case 0...9 = age { print("[0...9]") } //: [Next](@next) <file_sep>//: [Previous](@previous) import Foundation // 基本For循环 for i in 0..<3 { print("\(i)") } // 访问数组 let names = ["name1","name2","name3","name4"] for name in names[0...3] { print("\(name)") } // 字符范围 let str = "a" let a: Character = "a" let z: Character = "z" let range = a...z // 判断字符是否在ascii中 let ascii: ClosedRange<Character> = "\0"..."~" ascii.contains("@") // 带区间间隔的遍历 let hours = 11 let hourInterval = 2 for tickMark in stride(from: 2, to: hours, by: hourInterval) { print("\(tickMark)") } let number = 1 switch number { case 1: print("\(number)") // fallthrough case 2: print("\(number)111") default: break } let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." print(vegetableComment) case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." print(vegetableComment) case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" print(vegetableComment) default: let vegetableComment = "Everything tastes good in soup." print(vegetableComment) } //: [Next](@next) <file_sep>//: [Previous](@previous) import Foundation var str = "Hello, playground" class Person { var fn:(() -> ())? func run() { print("run") } deinit { print("Person.deinit") } } func test() { let p = Person() p.fn = { [weak p] in p?.run() } } test() print(1) // 1、弱引用必须是var // 2、自动给弱引用设置nil时,不会触发属性观察器 //weak var p: Person? = Person() print(2) //: [Next](@next) <file_sep>//: [Previous](@previous) var name:String? = "jack" name = nil var array = [1,15,40,29] func get(_ index: Int) -> Int? { if index < 0 || index >= array.count { return nil } return array[index] } print(get(1)) print(get(-1)) print(get(4)) let a: Int? = 1 let b: Int = 2 let c = a ?? b print(c) //: [Next](@next) <file_sep>//: [Previous](@previous) import Foundation var str = "Hello, playground" func addOne(num: Int) -> Int { return num + 1 } func addTo(_ adder: Int) -> (Int) -> Int { return { num in return num + adder } } let addTwo = addTo(2) let result = addTo(2)(6) //: [Next](@next) <file_sep>import UIKit import PlaygroundSupport var str = "Hello, playground" let view = UIView() view.frame = CGRect(x: 0, y: 0, width: 100, height: 100) view.backgroundColor = UIColor.red PlaygroundPage.current.liveView = view let imageView = UIImageView(image: UIImage(named: "mst_01")) PlaygroundPage.current.liveView = imageView let vc = UITableViewController() vc.view.backgroundColor = UIColor.gray PlaygroundPage.current.liveView = vc
2cb499bc846b9df46e683f40e75a0c857663203f
[ "Swift" ]
9
Swift
ilfocus/SwiftPlayground
42524d4e35e1df58c467970865cf28ccddbc3aae
a49b1488d8fb03d642cecd2edc3ac784f7050cd5
refs/heads/main
<repo_name>parmarjh/bank_note_authentication_heroku<file_sep>/app.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 22 00:06:11 2021 @author: ashishsapra """ import pandas as pd import numpy as np import pickle import streamlit as st #import flasgger #from flasgger import Swagger #app = Flask(__name__) #Swagger(app) pickle_in = open('classifier.pkl','rb') classifier = pickle.load(pickle_in) <EMAIL>('/') def welcome(): return "Welcome All" def predict_note_authentication(variance, skewness, curtosis, entropy): """Let's Authenticate the Banks Note This is using docstrings for specifications. --- parameters: - name: variance in: query type: number required: true - name: skewness in: query type: number required: true - name: curtosis in: query type: number required: true - name: entropy in: query type: number required: true responses: 200: description: The output values """ prediction = classifier.predict([[variance, skewness, curtosis, entropy]]) return prediction def main(): st.title("Bank Authentication") html_temp = """ <div style="background-color:green:padding:10px" <h2 style="color:white;text-align:center;">Bank Authenticator ML app<h2> </div> """ st.markdown(html_temp,unsafe_allow_html=True) variance = st.text_input("Variance","Type here") skewness = st.text_input("Skewness","Type here") curtosis = st.text_input("Curtosis","Type here") entropy = st.text_input("Entropy","Type here") result = "" if st.button("Predict"): result = predict_note_authentication(variance, skewness, curtosis, entropy) st.success('The Output is {}'.format(result)) if st.button("About"): st.text("App build by <NAME>") st.text("Contact on : <EMAIL>") if __name__ == '__main__': main()<file_sep>/README.md # Bank Note Authentication This is an ML app for authenticating banknotes ![img_0](https://user-images.githubusercontent.com/41446634/127739328-af558629-7465-4a02-abb1-84d8e50dca37.png) * All files for creating this app is in the 👉 testing branch, you can check it out like `BankNote_Authentication.csv` * `main` branch is deployed on Heroku. This is the link : [Heroku](https://money-app-ashish.herokuapp.com/) * This is a classification project, since the variable to be predicted is binary (fraudulent or legal). * The goal here is to model the probability that a banknote is fraudulent, as a function of its features. ## About Data Data were extracted from images that were taken from genuine and forged banknote-like specimens. For digitization, an industrial camera usually used for print inspection was used. The final images have 400x 400 pixels. Due to the object lens and distance to the investigated object gray-scale pictures with a resolution of about 660 dpi were gained. Wavelet Transform tools were used to extract features from images. The data file `banknote_authentication.csv` is the source of information for the classification problem. The number of instances (rows) in the data set is 1372, and the number of variables (columns) is 5. In that way, this problem has the following variables of wavelet transformed: - `variance`, used as input. - `skewness`, used as input. - `curtosis`, used as input. - `entropy`, used as input. - counterfeit, used as the target. It can only have two values: `0` (non-counterfeit) or `1` (counterfeit). # Making the app * I have already created the model you can check in `model_training.ipynb` file in `testing` branch * From model training we get the pickle file which is used in predicting the output which is 0 or 1 * For creating this Heroku app we need `classifier.pkl` which is trained file, `app.py` which runs and gives output, `requirements.txt` which has all the libraries which are required to run the `app.py`, `setup.sh` which has script we will be using this script on the **Heroku**, help to run `app.py`. * Clone this repo to your local system. * First you need to have Heroku account. You can sign-up if you don't have one. * You should have **Heroku CLI**, if you don't have you can downlod from [here](https://devcenter.heroku.com/articles/heroku-cli#download-and-install). * Now we are Ready to deploy. * Run this command `$ heroku create money-app` it will ask you login credentials. You get login through browser. * Now your app is created on Heroku, you have to put your code in Heroku. * You have to run the following command in order to make it deoployable * `$ git add .` * `$ git commit -m "make it better"` * `$ git push heroku master` * Just simply `$ git push heroku master`. Before this command make sure you commit all your code. ### Your Heroku app is ready you can checkout Heroku link # Contribute * You can contribute by folking this repo * Make changes, if you want to. * Push changes to this repo. ## 🤩Happy Contributing🤩<file_sep>/requirements.txt Flask numpy scipy scikit-learn matplotlib pandas streamlit
a1d64f86563550d1762ea79264beabc6435956ac
[ "Markdown", "Python", "Text" ]
3
Python
parmarjh/bank_note_authentication_heroku
ba6e7229ce16c9b188b108a7ccce1ba17380f546
bbeb805bb67180b6eb6928218cffeb5554a70e8b
refs/heads/main
<file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: dataloader.py # @Version: version 1.0 import sys import os sys.path.append(os.path.dirname(__file__) + os.sep + '../') import torch from torch.utils.data import DataLoader from dataloaders.dataloader_msrvtt_frame import MSRVTT_single_sentence_dataLoader from dataloaders.dataloader_msrvtt_frame import MSRVTT_multi_sentence_dataLoader from dataloaders.dataloader_msvd_frame import MSVD_multi_sentence_dataLoader from dataloaders.dataloader_vatexEnglish_frame import VATEXENGLISH_multi_sentence_dataLoader from dataloaders.dataloader_msrvttfull_frame import MSRVTTFULL_multi_sentence_dataLoader def dataloader_vatexEnglish_train(args, tokenizer): """return dataloader for training VATEX with English annotations Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(vatexEnglish_dataset): length train_sampler: sampler for distributed training """ vatexEnglish_dataset = VATEXENGLISH_multi_sentence_dataLoader( subset="train", data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) train_sampler = torch.utils.data.distributed.DistributedSampler(vatexEnglish_dataset) dataloader = DataLoader( vatexEnglish_dataset, batch_size=args.batch_size // args.n_gpu, num_workers=args.num_thread_reader, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True, ) return dataloader, len(vatexEnglish_dataset), train_sampler def dataloader_vatexEnglish_test(args, tokenizer, subset="test"): """return dataloader for testing VATEX with English annotations in multi-sentence captions Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(vatexEnglish_dataset): length """ vatexEnglish_dataset = VATEXENGLISH_multi_sentence_dataLoader( subset=subset, data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) dataloader = DataLoader( vatexEnglish_dataset, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False, ) return dataloader, len(vatexEnglish_dataset) def dataloader_msrvtt_train(args, tokenizer): """return dataloader for training msrvtt-9k Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(msrvtt_train_set): length train_sampler: sampler for distributed training """ msrvtt_train_set = MSRVTT_multi_sentence_dataLoader( csv_path=args.train_csv, json_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) train_sampler = torch.utils.data.distributed.DistributedSampler(msrvtt_train_set) dataloader = DataLoader( msrvtt_train_set, batch_size=args.batch_size // args.n_gpu, num_workers=args.num_thread_reader, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True, ) return dataloader, len(msrvtt_train_set), train_sampler def dataloader_msrvtt_test(args, tokenizer): """return dataloader for testing 1k-A protocol Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(msrvtt_test_set): length """ msrvtt_test_set = MSRVTT_single_sentence_dataLoader( csv_path=args.val_csv, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) dataloader = DataLoader( msrvtt_test_set, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False, ) return dataloader, len(msrvtt_test_set) def dataloader_msrvttfull_test(args, tokenizer): """return dataloader for testing full protocol Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(msrvtt_test_set): length """ msrvtt_test_set = MSRVTTFULL_multi_sentence_dataLoader( subset='test', csv_path=args.val_csv, json_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) dataloader = DataLoader( msrvtt_test_set, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False, ) return dataloader, len(msrvtt_test_set) def dataloader_msvd_train(args, tokenizer): """return dataloader for training msvd Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(msvd_dataset): length train_sampler: sampler for distributed training """ msvd_dataset = MSVD_multi_sentence_dataLoader( subset="train", data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) train_sampler = torch.utils.data.distributed.DistributedSampler(msvd_dataset) dataloader = DataLoader( msvd_dataset, batch_size=args.batch_size // args.n_gpu, num_workers=args.num_thread_reader, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True, ) return dataloader, len(msvd_dataset), train_sampler def dataloader_msvd_test(args, tokenizer, subset="test"): """return dataloader for testing msvd in multi-sentence captions Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(msvd_dataset): length """ msvd_test_set = MSVD_multi_sentence_dataLoader( subset=subset, data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, ) dataloader = DataLoader( msvd_test_set, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False, ) return dataloader, len(msvd_test_set) <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: modeling.py # @Version: version 1.0 from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import torch from torch import nn import torch.nn.functional as F from modules.until_module import PreTrainedModel from modules.until_module import CrossEn from modules.module_cross import CrossConfig from modules.module_cross import Transformer as TransformerClip from modules.module_clip import CLIP from modules.module_clip import convert_weights # logging the parameters logger = logging.getLogger(__name__) class CLIP2VideoPreTrainedModel(PreTrainedModel, nn.Module): """ An abstract class to handle weights initialization and a simple interface for loading pretrained models. """ def __init__(self, cross_config, *inputs, **kwargs): super(CLIP2VideoPreTrainedModel, self).__init__(cross_config) self.cross_config = cross_config self.clip = None self.cross = None @classmethod def from_pretrained(cls, cross_model_name, state_dict=None, cache_dir=None, type_vocab_size=2, *inputs, **kwargs): task_config = None if "task_config" in kwargs.keys(): task_config = kwargs["task_config"] if not hasattr(task_config, "local_rank"): task_config.__dict__["local_rank"] = 0 elif task_config.local_rank == -1: task_config.local_rank = 0 # obtain the basic parameter in CLIP model if state_dict is None: state_dict = {} # obtain the basic cross config clip_state_dict = CLIP.get_config(clip_path=task_config.clip_path) cross_config, _ = CrossConfig.get_config(cross_model_name, cache_dir, type_vocab_size, state_dict=None, task_config=task_config) #obtain the basic model and initialization model = cls(cross_config, clip_state_dict, *inputs, **kwargs) # initialize the parameters of clip for key, val in clip_state_dict.items(): new_key = "clip." + key if new_key not in state_dict: state_dict[new_key] = val.clone() # initialize the model with other modules if model.sim_type == "seqTransf": contain_frame_position = False for key in state_dict.keys(): if key.find("frame_position_embeddings") > -1: contain_frame_position = True break if contain_frame_position is False: for key, val in clip_state_dict.items(): # initialize for the mlp transformation if key == 'visual.proj': if task_config.temporal_proj == 'sigmoid_mlp': state_dict['frame2t_projection'] = val[0:512].clone() # initialize for the frame and type postion embedding if key == "positional_embedding": state_dict["frame_position_embeddings.weight"] = val.clone() if task_config.temporal_type == 'TDB': state_dict["type_position_embeddings.weight"] = val[0:2].clone() # using weight of first 4 layers for initialization if key.find("transformer.resblocks") == 0: num_layer = int(key.split(".")[2]) # initialize TDB's difference-level attention if task_config.temporal_proj == 'sigmoid_selfA' and num_layer < 1: state_dict[key.replace("transformer.", "frame2t_attention.")] = val.clone() # initialize the one-layer transformer for the input of TAB if (task_config.center_proj == 'TAB' or task_config.center_proj == 'TAB_TDB') and num_layer < 1: state_dict[key.replace("transformer.", "actionClip.")] = val.clone() # initialize the 4-layer temporal transformer if num_layer < task_config.cross_num_hidden_layers: state_dict[key.replace("transformer.", "transformerClip.")] = val.clone() continue # init model with loaded parameters if state_dict is not None: model = cls.init_preweight(model, state_dict, task_config=task_config) return model def show_log(task_config, info): if task_config is None or task_config.local_rank == 0: logger.warning(info) class CLIP2Video(CLIP2VideoPreTrainedModel): """main code for CLIP2Video Attributes: task_config: hyper-parameter from args center_type: indicate to whether use TAB or TDB temporal_type: default to use the standard type, while TDB to use the TDB block temporal_proj: different type to encode difference centerK: the center number of TAB block center_weight: the weight of TAB loss center_proj: TAB_TDB, TAB """ def __init__(self, cross_config, clip_state_dict, task_config): super(CLIP2Video, self).__init__(cross_config) self.task_config = task_config # for TDB block self.temporal_type = task_config.temporal_type self.temporal_proj = task_config.temporal_proj # for TAB block self.center_type = task_config.center_type self.centerK = task_config.centerK self.center_weight = task_config.center_weight self.center_proj = task_config.center_proj # set the parameters of CLIP # CLIP Encoders: From OpenAI: CLIP [https://github.com/openai/CLIP] vision_width = clip_state_dict["visual.conv1.weight"].shape[0] vision_layers = len( [k for k in clip_state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) vision_patch_size = clip_state_dict["visual.conv1.weight"].shape[-1] grid_size = round((clip_state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) image_resolution = vision_patch_size * grid_size embed_dim = clip_state_dict["text_projection"].shape[1] context_length = clip_state_dict["positional_embedding"].shape[0] vocab_size = task_config.vocab_size #["token_embedding.weight"].shape[0] transformer_width = clip_state_dict["ln_final.weight"].shape[0] transformer_heads = transformer_width // 64 transformer_layers = len(set(k.split(".")[2] for k in clip_state_dict if k.startswith(f"transformer.resblocks"))) show_log(task_config, "\t embed_dim: {}".format(embed_dim)) show_log(task_config, "\t image_resolution: {}".format(image_resolution)) show_log(task_config, "\t vision_layers: {}".format(vision_layers)) show_log(task_config, "\t vision_width: {}".format(vision_width)) show_log(task_config, "\t vision_patch_size: {}".format(vision_patch_size)) show_log(task_config, "\t context_length: {}".format(context_length)) show_log(task_config, "\t vocab_size: {}".format(vocab_size)) show_log(task_config, "\t transformer_width: {}".format(transformer_width)) show_log(task_config, "\t transformer_heads: {}".format(transformer_heads)) show_log(task_config, "\t transformer_layers: {}".format(transformer_layers)) cut_top_layer = 0 show_log(task_config, "\t cut_top_layer: {}".format(cut_top_layer)) if vocab_size == 49408: key_name = ["input_resolution", "context_length", "vocab_size"] else: key_name = ["input_resolution", "context_length", "vocab_size", "token_embedding.weight"] for key in key_name: if key in clip_state_dict: del clip_state_dict[key] # use .float() to avoid overflow/underflow from fp16 weight. https://github.com/openai/CLIP/issues/40 self.clip = CLIP( embed_dim, image_resolution, vision_layers-cut_top_layer, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers-cut_top_layer, ).float() convert_weights(self.clip) # set the type of similarity calculator self.sim_type = 'meanP' if hasattr(task_config, "sim_type"): self.sim_type = task_config.sim_type show_log(task_config, "\t sim_type: {}".format(self.sim_type)) # load the max length of positional embedding cross_config.max_position_embeddings = context_length if self.sim_type == "seqTransf": # positional embedding for temporal transformer self.frame_position_embeddings = nn.Embedding(cross_config.max_position_embeddings, cross_config.hidden_size) # 4-layer temporal transformer self.transformerClip = TransformerClip(width=transformer_width, layers=self.task_config.cross_num_hidden_layers, heads=transformer_heads, ) if self.temporal_proj == 'sigmoid_mlp': # initialize for mlp self.frame2t_projection = nn.Parameter(torch.empty(512, 512)) nn.init.normal_(self.frame2t_projection, std=64 ** -0.5) elif self.temporal_proj == 'sigmoid_selfA': # initialize for difference-level attention self.frame2t_attention = TransformerClip(width=transformer_width, layers=1, heads=transformer_heads, ) # initialize difference pipeline for 'TDB', use default to use the standard structure if self.temporal_type == 'TDB': self.type_position_embeddings = nn.Embedding(2, cross_config.hidden_size) self.sigmoid = torch.nn.Sigmoid() self.trans_layernorm = torch.nn.LayerNorm(512) if self.center_type == 'TAB': # initialize the weight center self.weight_center = nn.Parameter(torch.empty(self.centerK, 512)) nn.init.normal_(self.weight_center, std=64 ** -0.5) # initialize the embedding center self.emb_center = nn.Parameter(torch.empty(self.centerK, 512)) nn.init.normal_(self.emb_center, std=64 ** -0.5) # initialize the 1-layer transformer used in TAB if self.center_proj == 'TAB' or self.center_proj == 'TAB_TDB': self.actionClip = TransformerClip(width=transformer_width, layers=1, heads=transformer_heads, ) # initial loss (Cross entropy loss) self.loss_fct = CrossEn() self.apply(self.init_weights) def calc_loss(self, sequence_output, visual_output, attention_mask, video_mask): """ calculate loss Args: sequence_hidden_output: token embedding visual_output: frame embedding attention_mask: caption mask video_mask: video mask Returns: sim_loss: loss for optimization """ sim_matrix = self.get_similarity_logits(sequence_output, visual_output, attention_mask, video_mask, shaped=True) # text-to-video loss sim_loss1 = self.loss_fct(sim_matrix) # video-to-text loss sim_loss2 = self.loss_fct(sim_matrix.T) sim_loss = (sim_loss1 + sim_loss2) / 2 return sim_loss def get_extra_TAB_embedding(self, embedding_out, attention_mask): """ obtain frame embedding concentrated with temporal embedding Args: embedding_out: token embedding attention_mask: frame embedding Returns: embedding_out: token embedding with temporal enhancing attention_mask: frame embedding with temporal enhancing """ large_position_d = torch.arange(start=0, end=embedding_out.size()[1], step=2, dtype=torch.long, device=embedding_out.device) large_embedding_out = embedding_out[:, large_position_d, :] # bs * 6 * 512 large_attention_mask = attention_mask[:, large_position_d] # embedding_out: bs * seq * 512 | local_out: bs * seq * (k + 1) if self.center_proj == 'TAB' or self.center_proj == 'TAB_TDB': # sample in the large frame rate # obtain the attention mask of large frame rate large_attention_mask_span = large_attention_mask.squeeze(-1) large_attention_mask_span = large_attention_mask_span.squeeze(-1) # prepare the position embedding and store the input embedding seq_length = large_embedding_out.size(1) position_ids = torch.arange(seq_length, dtype=torch.long, device=large_embedding_out.device) position_ids = position_ids.unsqueeze(0).expand(large_embedding_out.size(0), -1) TAB_position_embedding = self.frame_position_embeddings(position_ids) large_embedding_out_original = large_embedding_out if self.center_proj == 'TAB_TDB': # shared TDB is adopted to insert difference-enhanced token large_embedding_out, TAB_position_embedding, TAB_type_embedding, large_attention_mask_span = self.temporal_difference_block( large_embedding_out, large_attention_mask_span) large_embedding_out = large_embedding_out + TAB_position_embedding + TAB_type_embedding else: large_embedding_out = large_embedding_out + TAB_position_embedding # batch_size * 12 * 512 extended_video_mask = (1.0 - large_attention_mask_span.unsqueeze(1)) * -1000000.0 # batch_size * 1* 12 extended_video_mask = extended_video_mask.expand(-1, large_attention_mask_span.size(1), -1) # batch_size * 12 * 12 # adopt 1-layer temporal transformer to encode representation large_embedding_out = large_embedding_out.permute(1, 0, 2) # NLD -> LND # 12 * batch_size * 512 large_embedding_out = self.actionClip(large_embedding_out, extended_video_mask) # 12 * batch_size * 512 large_embedding_out = large_embedding_out.permute(1, 0, 2) # LND -> NLD # batch_size * 12 * 512 # adopt the output of frame token if use TAB_TDB if self.center_proj == 'TAB_TDB': frame_position_id = torch.arange(start=0, end=large_embedding_out.size()[1], step=2, dtype=torch.long, device=large_embedding_out.device) large_embedding_out = large_embedding_out[:, frame_position_id, :] # concat the original embedding and encoded embedding with temporal correlations large_embedding_out = large_embedding_out + large_embedding_out_original embedding_out = torch.cat((embedding_out, large_embedding_out), 1) attention_mask = torch.cat((attention_mask, large_attention_mask), 1) return embedding_out, attention_mask def get_TAB_embedding(self, embedding_out, attention_mask, type='default'): """ obtain aligned embedding for video and text Args: embedding_out: token embedding attention_mask: frame embedding Returns: cluster_embedding: aligned embedding """ if type == 'visual': embedding_out, attention_mask = self.get_extra_TAB_embedding(embedding_out, attention_mask) soft_weight = F.softmax(embedding_out @ self.weight_center[0:self.centerK].t(), 2) cluster_embedding = soft_weight.unsqueeze(3) * (embedding_out.unsqueeze(2) - self.emb_center[0:self.centerK]) cluster_embedding = torch.sum(cluster_embedding * attention_mask, 1) cluster_embedding = cluster_embedding / cluster_embedding.norm(dim=-1, keepdim=True) cluster_embedding = torch.mean(cluster_embedding, dim=1) cluster_embedding = cluster_embedding / cluster_embedding.norm(dim=-1, keepdim=True) return cluster_embedding def calc_TAB_loss(self, sequence_hidden_output, visual_output, attention_mask, video_mask): """ calculate TAB loss Args: sequence_hidden_output: token embedding visual_output: frame embedding attention_mask: caption mask video_mask: video mask Returns: sim_loss: loss for optimization """ # obtain the aligned video representation video_mask_un = video_mask.to(dtype=torch.float).unsqueeze(-1) video_mask_un = video_mask_un.unsqueeze(-1) cluster_visual_output = self.get_TAB_embedding(visual_output, video_mask_un, type='visual') # obtain the aligned text representation attention_mask_un = attention_mask.to(dtype=torch.float).unsqueeze(-1) attention_mask_un[:, 0, :] = 0. attention_mask_un = attention_mask_un.unsqueeze(-1) cluster_sequence_output = self.get_TAB_embedding(sequence_hidden_output, attention_mask_un, type='sequence') # calculate the similarity logit_scale = self.clip.logit_scale.exp() sim_matrix = logit_scale * torch.matmul(cluster_sequence_output, cluster_visual_output.t()) # text-to-video loss sim_loss1 = self.loss_fct(sim_matrix) # video-to-text loss sim_loss2 = self.loss_fct(sim_matrix.T) sim_loss = (sim_loss1 + sim_loss2) / 2 return sim_loss def forward(self, input_ids, token_type_ids, attention_mask, video, video_mask=None): """ forward method during training Args: input_ids: caption id token_type_ids: type id attention_mask: caption mask video_mask: video mask shaped: False to reshape Returns: loss: total loss TAB_losses: TAB loss """ # reshape the input text input_ids = input_ids.view(-1, input_ids.shape[-1]) token_type_ids = token_type_ids.view(-1, token_type_ids.shape[-1]) attention_mask = attention_mask.view(-1, attention_mask.shape[-1]) # reshape the input video video_mask = video_mask.view(-1, video_mask.shape[-1]) video = torch.as_tensor(video).float() b, pair, bs, ts, channel, h, w = video.shape video = video.view(b * pair * bs * ts, channel, h, w) video_frame = bs * ts # obtain the frame and text representation sequence_output, visual_output = self.get_sequence_visual_output(input_ids, token_type_ids, attention_mask, video, video_mask, shaped=True, video_frame=video_frame) if self.training: loss = 0. TAB_losses = 0. if self.center_type == 'TAB': # tuple, which contain the output of cls and other tokens sequence_output, sequence_hidden_output = sequence_output # calculate the total loss sim_loss = self.calc_loss(sequence_output, visual_output, attention_mask, video_mask) loss += sim_loss * self.center_weight # calculate TAB loss TAB_loss = self.calc_TAB_loss(sequence_hidden_output, visual_output, attention_mask, video_mask) # combine two losses, where loss is for optimization and TAB_losses if for logging loss += TAB_loss * (1 - self.center_weight) TAB_losses += TAB_loss else: # calculate the total loss sim_loss, _ = self.calc_loss(sequence_output, visual_output, attention_mask, video_mask) loss += sim_loss return loss, TAB_losses else: return None def get_sequence_output(self, input_ids, token_type_ids, attention_mask, shaped=False): """Encode text representation Args: input_ids: caption id token_type_ids: type id attention_mask: caption mask shaped: False to reshape Returns: sequence_output: output embedding [1,512] visual_output: output embedding [1,512] """ if shaped is False: input_ids = input_ids.view(-1, input_ids.shape[-1]) token_type_ids = token_type_ids.view(-1, token_type_ids.shape[-1]) attention_mask = attention_mask.view(-1, attention_mask.shape[-1]) bs_pair = input_ids.size(0) if self.center_type == 'TAB': sequence_hidden, return_hidden = self.clip.encode_text(input_ids, return_hidden=True) sequence_hidden = sequence_hidden.float() return_hidden = return_hidden.float() return_hidden = return_hidden.view(bs_pair, -1, return_hidden.size(-1)) return sequence_hidden, return_hidden else: sequence_hidden = self.clip.encode_text(input_ids).float() sequence_hidden = sequence_hidden.view(bs_pair, -1, sequence_hidden.size(-1)) return sequence_hidden def get_visual_output(self, video, video_mask, shaped=False, video_frame=-1): """Encode video representation Args: video: video frames video_mask: video mask video_frame: frame length of video shaped: False to reshape Returns: visual_hidden: output embedding [1,512] """ if shaped is False: video_mask = video_mask.view(-1, video_mask.shape[-1]) video = torch.as_tensor(video).float() b, pair, bs, ts, channel, h, w = video.shape video = video.view(b * pair * bs * ts, channel, h, w) video_frame = bs * ts bs_pair = video_mask.size(0) visual_hidden = self.clip.encode_image(video, video_frame=video_frame).float() visual_hidden = visual_hidden.view(bs_pair, -1, visual_hidden.size(-1)) return visual_hidden def get_sequence_visual_output(self, input_ids, token_type_ids, attention_mask, video, video_mask, shaped=False, video_frame=-1): """Encode text and video representation Args: input_ids: caption id token_type_ids: type id attention_mask: caption mask video: video frames video_mask: video mask video_frame: frame length of video Returns: sequence_output: output embedding [1,512] visual_output: output embedding [1,512] """ if shaped is False: input_ids = input_ids.view(-1, input_ids.shape[-1]) token_type_ids = token_type_ids.view(-1, token_type_ids.shape[-1]) attention_mask = attention_mask.view(-1, attention_mask.shape[-1]) video_mask = video_mask.view(-1, video_mask.shape[-1]) video = torch.as_tensor(video).float() b, pair, bs, ts, channel, h, w = video.shape video = video.view(b * pair * bs * ts, channel, h, w) video_frame = bs * ts # encode text representation sequence_output = self.get_sequence_output(input_ids, token_type_ids, attention_mask, shaped=True) # encode video representation visual_output = self.get_visual_output(video, video_mask, shaped=True, video_frame=video_frame) return sequence_output, visual_output def _mean_pooling_for_similarity_sequence(self, sequence_output, attention_mask): """average pooling for the overall text representation Args: sequence_output: embedding attention_mask: caption mask Returns: text_out: output embedding [1,512] """ attention_mask_un = attention_mask.to(dtype=torch.float).unsqueeze(-1) attention_mask_un[:, 0, :] = 0. sequence_output = sequence_output * attention_mask_un text_out = torch.sum(sequence_output, dim=1) / torch.sum(attention_mask_un, dim=1, dtype=torch.float) return text_out def _mean_pooling_for_similarity_visual(self, visual_output, video_mask,): """average pooling for the overall video representation Args: visual_output: embedding video_mask: video embedding Returns: video_out: output embedding [1,512] """ video_mask_un = video_mask.to(dtype=torch.float).unsqueeze(-1) visual_output = visual_output * video_mask_un video_mask_un_sum = torch.sum(video_mask_un, dim=1, dtype=torch.float) video_mask_un_sum[video_mask_un_sum == 0.] = 1. video_out = torch.sum(visual_output, dim=1) / video_mask_un_sum return video_out def _mean_pooling_for_similarity(self, sequence_output, visual_output, attention_mask, video_mask,): """average pooling for the overall video representation Args: sequence_output: embedding visual_output: embedding attention_mask: caption mask video_mask: video mask Returns: text_out:output embedding [1,512] video_out: output embedding [1,512] """ text_out = self._mean_pooling_for_similarity_sequence(sequence_output, attention_mask) video_out = self._mean_pooling_for_similarity_visual(visual_output, video_mask) return text_out, video_out def _similarity(self, sequence_output, visual_output, attention_mask, video_mask, sim_type="meanP"): """Calculate the similarity between visual and text representation Args: sequence_output: embedding visual_output: embedding attention_mask: caption mask video_mask: video mask sim_type: header for aggregate the video representation Returns: retrieve_logits: similarity """ sequence_output, visual_output = sequence_output.contiguous(), visual_output.contiguous() if sim_type == "meanP": # Default: Parameter-free type pass elif sim_type == "seqTransf": # Sequential type: Transformer Encoder visual_output_original = visual_output # batch_size * 12 * 512 seq_length = visual_output.size(1) # 12 # obtain positional embedding position_ids = torch.arange(seq_length, dtype=torch.long, device=visual_output.device) # 12 position_ids = position_ids.unsqueeze(0).expand(visual_output.size(0), -1) # batch_size * 12 frame_position_embeddings = self.frame_position_embeddings(position_ids) # batch_size * 12 * 512 # add positional embedding into visual_output visual_output = visual_output + frame_position_embeddings # batch_size * 12 * 512 # obtain the output of temporal transformer extended_video_mask = (1.0 - video_mask.unsqueeze(1)) * -1000000.0 # batch_size * 1* 12 extended_video_mask = extended_video_mask.expand(-1, video_mask.size(1), -1) # batch_size * 12 * 12 visual_output = visual_output.permute(1, 0, 2) # NLD -> LND # 12 * batch_size * 512 visual_output = self.transformerClip(visual_output, extended_video_mask) #12 * batch_size * 512 visual_output = visual_output.permute(1, 0, 2) # LND -> NLD # batch_size * 12 * 512 visual_output = visual_output + visual_output_original # normalize the video representation visual_output = visual_output / visual_output.norm(dim=-1, keepdim=True) visual_output = self._mean_pooling_for_similarity_visual(visual_output, video_mask) visual_output = visual_output / visual_output.norm(dim=-1, keepdim=True) # normalize the text representation sequence_output = sequence_output.squeeze(1) sequence_output = sequence_output / sequence_output.norm(dim=-1, keepdim=True) # calculate the similarity logit_scale = self.clip.logit_scale.exp() retrieve_logits = logit_scale * torch.matmul(sequence_output, visual_output.t()) return retrieve_logits def temporal_difference_block(self, visual_output, video_mask): """Calculate difference-enhanced token and inset into frame token Args: visual_output: embedding video_mask: video mask Returns: visual_output: frame representation frame_position_embeddings: position embedding type_embedding: type embedding temporal_video_mask: attention mask """ seq_length = visual_output.size(1) # 12 # obtain the positional embedding position_ids = torch.arange(seq_length, dtype=torch.long, device=visual_output.device) # 12 position_ids = position_ids.unsqueeze(0).expand(visual_output.size(0), -1) # batch_size * 12 frame_position_embeddings = self.frame_position_embeddings(position_ids) # batch_size * 12 * 512 # obtain the type embedding to indicate the frame token and difference-enhanced token video_ids = torch.ones_like(position_ids) videoDif_ids = torch.zeros_like(position_ids) video_type_embedding = self.type_position_embeddings(video_ids) videoDif_type_embedding = self.type_position_embeddings(videoDif_ids) # adopt temporal_proj == sigmoid_mlp for mlp transformation # adopt temporal_proj == sigmoid_selfA for difference-level attention # adopt temporal_proj == default to use subtraction directly # batch size * 11 * 512 dif_visual_output = visual_output[:, 1: seq_length, :] - visual_output[:, 0: seq_length - 1, :] if self.temporal_proj == 'sigmoid_mlp': # adopt sigmoid to transform into [-1, 1] dif_visual_output = 2 * self.sigmoid(self.trans_layernorm(dif_visual_output @ self.frame2t_projection)) - 1 elif self.temporal_proj == 'sigmoid_selfA': # batch_size * 11 * 512 dif_visual_output = dif_visual_output + frame_position_embeddings[:, 1:seq_length, :] trans_video_mask = video_mask[:,1:seq_length] # batch_size * 1* 11 extend_trans_video_mask = (1.0 - trans_video_mask.unsqueeze(1)) * -1000000.0 # batch_size * 11 * 11 extend_trans_video_mask = extend_trans_video_mask.expand(-1, trans_video_mask.size(1), -1) dif_visual_output = dif_visual_output.permute(1, 0, 2) # NLD -> LND # 11 * batch_size * 512 dif_visual_output = self.frame2t_attention(dif_visual_output, extend_trans_video_mask) dif_visual_output = dif_visual_output.permute(1, 0, 2) # LND -> NLD # batch_size * 11 * 512 dif_visual_output = 2 * self.sigmoid(self.trans_layernorm(dif_visual_output)) - 1 # batch size * (12+11) * 512 visual_middle = torch.cat((visual_output, dif_visual_output), 1) # batch size * (12+12) * 512 frame_position_embeddings_middle = torch.cat((frame_position_embeddings, frame_position_embeddings), 1) temporal_video_mask_middle = torch.cat((video_mask, video_mask), 1) type_embedding_middle = torch.cat((video_type_embedding, videoDif_type_embedding), 1) # obtain the correct index to insert difference-enhanced token seq1_indices = torch.arange(start=0, end=seq_length, step=1, dtype=torch.long) seq2_indices = torch.arange(start=seq_length, end=2 * seq_length - 1, step=1, dtype=torch.long) seq_indices = torch.stack((seq1_indices[0], seq2_indices[0])) for i in range(1, seq_length - 1): seq_indices = torch.cat((seq_indices, seq1_indices[i].view(1), seq2_indices[i].view(1))) seq_indices = torch.cat((seq_indices, seq1_indices[seq_length - 1].view(1))).cuda() # insert difference-enhanced token between every adjacent frame token visual_output = visual_middle.index_select(1, seq_indices) frame_position_embeddings = frame_position_embeddings_middle.index_select(1, seq_indices) temporal_video_mask = temporal_video_mask_middle.index_select(1, seq_indices) type_embedding = type_embedding_middle.index_select(1, seq_indices) return visual_output, frame_position_embeddings, type_embedding, temporal_video_mask def _similarity_TDB(self, sequence_output, visual_output, attention_mask, video_mask): """Calculate the similarity between visual and text representation by adding TDB Args: sequence_output: embedding visual_output: embedding attention_mask: caption mask video_mask: video mask Returns: retrieve_logits: similarity """ sequence_output, visual_output = sequence_output.contiguous(), visual_output.contiguous() # obtain the basic embedding visual_output_original = visual_output # batch_size * 12 * 512 # difference-enhanced token obtained by TDB visual_output, frame_position_embeddings, type_embedding, temporal_video_mask = self.temporal_difference_block( visual_output, video_mask) # obtain the output of transformer visual_output = visual_output + frame_position_embeddings + type_embedding # batch_size * 12 * 512 extended_video_mask = (1.0 - temporal_video_mask.unsqueeze(1)) * -1000000.0 # batch_size * 1* 12 extended_video_mask = extended_video_mask.expand(-1, temporal_video_mask.size(1), -1) # batch_size * 12 * 12 visual_output = visual_output.permute(1, 0, 2) # NLD -> LND # 12 * batch_size * 512 visual_output = self.transformerClip(visual_output, extended_video_mask) #12 * batch_size * 512 visual_output = visual_output.permute(1, 0, 2) # LND -> NLD # batch_size * 12 * 512 # select the output of frame token for final video representation frame_position_id = torch.arange(start=0, end=visual_output.size()[1], step=2, dtype=torch.long, device=visual_output.device) visual_output = visual_output[:, frame_position_id, :] visual_output = visual_output + visual_output_original visual_output = visual_output / visual_output.norm(dim=-1, keepdim=True) # mean pooling for video representation video_mask_un = video_mask.to(dtype=torch.float).unsqueeze(-1) # batch_size * 12 * 1 visual_output = visual_output * video_mask_un video_mask_un_sum = torch.sum(video_mask_un, dim=1, dtype=torch.float) video_mask_un_sum[video_mask_un_sum == 0.] = 1. visual_output = torch.sum(visual_output, dim=1) / video_mask_un_sum # obtain the normalized video embedding visual_output = visual_output / visual_output.norm(dim=-1, keepdim=True) # obtain the normalized sequence embedding sequence_output = sequence_output.squeeze(1) sequence_output = sequence_output / sequence_output.norm(dim=-1, keepdim=True) # calculate the similarity logit_scale = self.clip.logit_scale.exp() retrieve_logits = logit_scale * torch.matmul(sequence_output, visual_output.t()) return retrieve_logits def get_similarity_logits(self, sequence_output, visual_output, attention_mask, video_mask, shaped=False): """get the similarity for global representation during training Args: sequence_output: embedding visual_output: embedding attention_mask: caption mask video_mask: video mask shaped: whether to shape the dimension Returns: retrieve_logits: output similarity """ if shaped is False: attention_mask = attention_mask.view(-1, attention_mask.shape[-1]) video_mask = video_mask.view(-1, video_mask.shape[-1]) if self.sim_type == 'seqTransf' and self.temporal_type == 'TDB': # adopting temporal transformer with TDB block retrieve_logits = self._similarity_TDB(sequence_output, visual_output, attention_mask, video_mask) else: # adopting mean pooling or use temporal transformer to aggregate the video representation assert self.sim_type in ["meanP", "seqTransf"] retrieve_logits = self._similarity(sequence_output, visual_output, attention_mask, video_mask, sim_type=self.sim_type) return retrieve_logits def get_inference_logits(self, sequence_output, visual_output, attention_mask, video_mask, shaped=False): """get the similarity for global and local representation during inference Args: sequence_output: embedding visual_output: embedding attention_mask: caption mask video_mask: video mask shaped: whether to shape the dimension Returns: text_out:output embedding [1,512] video_out: output embedding [1,512] """ if shaped is False: attention_mask = attention_mask.view(-1, attention_mask.shape[-1]) video_mask = video_mask.view(-1, video_mask.shape[-1]) contrastive_direction = () if self.center_type == 'TAB': sequence_output, sequence_hidden_output = sequence_output if self.sim_type == 'seqTransf' and self.temporal_type == 'TDB': # adopting temporal transformer with TDB block retrieve_logits = self._similarity_TDB(sequence_output, visual_output, attention_mask, video_mask) else: # adopting mean pooling or use temporal transformer to aggregate the video representation assert self.sim_type in ["meanP", "seqTransf"] retrieve_logits = self._similarity(sequence_output, visual_output, attention_mask, video_mask, sim_type=self.sim_type) # calculate the similarity aggregated in TAB block if self.center_type == 'TAB': # calculate the aligned video representation video_mask_un = video_mask.to(dtype=torch.float).unsqueeze(-1) video_mask_un = video_mask_un.unsqueeze(-1) cluster_visual_output = self.get_TAB_embedding(visual_output, video_mask_un, type='visual') # calculate the aligned text representation attention_mask_un = attention_mask.to(dtype=torch.float).unsqueeze(-1) attention_mask_un[:, 0, :] = 0. attention_mask_un = attention_mask_un.unsqueeze(-1) cluster_sequence_output = self.get_TAB_embedding(sequence_hidden_output, attention_mask_un, type='sequence') logit_scale = self.clip.logit_scale.exp() sim_matrix = logit_scale * torch.matmul(cluster_sequence_output, cluster_visual_output.t()) retrieve_logits = retrieve_logits * self.center_weight + sim_matrix * ( 1 - self.center_weight) return retrieve_logits, contrastive_direction <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: infer_retrieval.py # @Version: version 1.0 import torch import numpy as np import os import random from modules.tokenization_clip import SimpleTokenizer as ClipTokenizer from modules.modeling import CLIP2Video from evaluation.eval import eval_epoch from utils.config import get_args from utils.utils import get_logger from utils.dataloader import dataloader_msrvtt_train from utils.dataloader import dataloader_msrvtt_test from utils.dataloader import dataloader_msrvttfull_test from utils.dataloader import dataloader_msvd_train from utils.dataloader import dataloader_msvd_test from utils.dataloader import dataloader_vatexEnglish_train from utils.dataloader import dataloader_vatexEnglish_test # define the dataloader # new dataset can be added from import and inserted according to the following code DATALOADER_DICT = {} DATALOADER_DICT["msrvtt"] = {"train":dataloader_msrvtt_train, "test":dataloader_msrvtt_test} DATALOADER_DICT["msrvttfull"] = {"train":dataloader_msrvtt_train, "val":dataloader_msrvttfull_test, "test":dataloader_msrvttfull_test} DATALOADER_DICT["msvd"] = {"train":dataloader_msvd_train, "val":dataloader_msvd_test, "test":dataloader_msvd_test} DATALOADER_DICT["vatexEnglish"] = {"train":dataloader_vatexEnglish_train, "test":dataloader_vatexEnglish_test} def set_seed_logger(args): """Initialize the seed and environment variable Args: args: the hyper-parameters. Returns: args: the hyper-parameters modified by the random seed. """ global logger # predefining random initial seeds random.seed(args.seed) os.environ['PYTHONHASHSEED'] = str(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) # if you are using multi-GPU. torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True # get logger logger = get_logger(os.path.join(args.output_dir)) return args def init_device(args, local_rank): """Initialize device to determine CPU or GPU Args: args: the hyper-parameters local_rank: GPU id Returns: devices: cuda n_gpu: number of gpu """ global logger device = torch.device("cuda" if torch.cuda.is_available() else "cpu", local_rank) n_gpu = torch.cuda.device_count() logger.info("device: {} n_gpu: {}".format(device, n_gpu)) args.n_gpu = n_gpu if args.batch_size_val % args.n_gpu != 0: raise ValueError("Invalid batch_size/batch_size_val and n_gpu parameter: {}%{} and {}%{}, should be == 0".format( args.batch_size, args.n_gpu, args.batch_size_val, args.n_gpu)) return device, n_gpu def init_model(args, device): """Initialize model. if location of args.init_model exists, model will be initialized from the pretrained model. if no model exists, the training will be initialized from CLIP's parameters. Args: args: the hyper-parameters devices: cuda Returns: model: the initialized model """ # resume model if pre-trained model exist. model_file = os.path.join(args.checkpoint, "pytorch_model.bin.{}".format(args.model_num)) if os.path.exists(model_file): model_state_dict = torch.load(model_file, map_location='cpu') if args.local_rank == 0: logger.info("Model loaded from %s", model_file) else: model_state_dict = None if args.local_rank == 0: logger.info("Model loaded fail %s", model_file) # Prepare model model = CLIP2Video.from_pretrained(args.cross_model, cache_dir=None, state_dict=model_state_dict, task_config=args) model.to(device) return model def main(): global logger # obtain the hyper-parameter args = get_args() # set the seed args = set_seed_logger(args) # setting the testing device device, n_gpu = init_device(args, args.local_rank) # setting tokenizer tokenizer = ClipTokenizer() # init model model = init_model(args, device) # init test dataloader assert args.datatype in DATALOADER_DICT test_dataloader, test_length = DATALOADER_DICT[args.datatype]["test"](args, tokenizer) # print information for debugging if args.local_rank == 0: logger.info("***** Running test *****") logger.info(" Num examples = %d", test_length) logger.info(" Batch size = %d", args.batch_size_val) logger.info(" Num steps = %d", len(test_dataloader)) # evaluation for text-to-video and video-to-text retrieval if args.local_rank == 0: eval_epoch(model, test_dataloader, device, n_gpu, logger) if __name__ == "__main__": main() <file_sep>import os from concurrent import futures import argparse def extract_frames(video_name, out_folder, fps=5): if os.path.exists(out_folder): os.system('rm -rf ' + out_folder + '/*') os.system('rm -rf ' + out_folder) os.makedirs(out_folder) cmd = 'ffmpeg -v 0 -i %s -r %d -q 0 %s/%s.jpg' % (video_name, fps, out_folder, '%08d') os.system(cmd) def process(line): print(line) mp4_name, folder_frame = line extract_frames(mp4_name, folder_frame) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Get frames from video') parser.add_argument('--input_path', type=str, default='input', help='input directory of videos') parser.add_argument('--output_path', type=str, default='output', help='output directory of sampled frames') args = parser.parse_args() if not os.path.exists(args.output_path): os.mkdir(args.output_path) mp4_file = os.listdir(args.input_path) lines = [(os.path.join(args.input_path, mp4), os.path.join(args.output_path, mp4.split(".")[0])) for mp4 in mp4_file] # multi thread with futures.ProcessPoolExecutor(max_workers=10) as executer: fs = [executer.submit(process, line) for line in lines] print("done") <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: dataloader_msrvtt_frame.py # @Version: version 1.0 import os from torch.utils.data import Dataset import numpy as np import pandas as pd import json from dataloaders.rawframe_util import RawFrameExtractor class MSRVTT_single_sentence_dataLoader(Dataset): """MSRVTT dataset loader for single sentence Attributes: csv_path: video id of sub set features_path: frame directory tokenizer: tokenize the word max_words: the max number of word feature_framerate: frame rate for sampling video max_frames: the max number of frame image_resolution: resolution of images """ def __init__( self, csv_path, features_path, tokenizer, max_words=30, feature_framerate=1.0, max_frames=100, image_resolution=224, ): self.data = pd.read_csv(csv_path) self.features_path = features_path self.feature_framerate = feature_framerate self.max_words = max_words self.max_frames = max_frames self.tokenizer = tokenizer # frame extractor to sample frames from video self.frameExtractor = RawFrameExtractor(framerate=feature_framerate, size=image_resolution) # start and end token self.SPECIAL_TOKEN = {"CLS_TOKEN": "<|startoftext|>", "SEP_TOKEN": "<|endoftext|>", "MASK_TOKEN": "[MASK]", "UNK_TOKEN": "[UNK]", "PAD_TOKEN": "[PAD]"} def __len__(self): """length of data loader Returns: length: length of data loader """ length = len(self.data) return length def _get_text(self, caption): """get tokenized word feature Args: caption: caption Returns: pairs_text: tokenized text pairs_mask: mask of tokenized text pairs_segment: type of tokenized text """ # tokenize word words = self.tokenizer.tokenize(caption) # add cls token words = [self.SPECIAL_TOKEN["CLS_TOKEN"]] + words total_length_with_CLS = self.max_words - 1 if len(words) > total_length_with_CLS: words = words[:total_length_with_CLS] # add end token words = words + [self.SPECIAL_TOKEN["SEP_TOKEN"]] # convert token to id according to the vocab input_ids = self.tokenizer.convert_tokens_to_ids(words) # add zeros for feature of the same length input_mask = [1] * len(input_ids) segment_ids = [0] * len(input_ids) while len(input_ids) < self.max_words: input_ids.append(0) input_mask.append(0) segment_ids.append(0) # ensure the length of feature to be equal with max words assert len(input_ids) == self.max_words assert len(input_mask) == self.max_words assert len(segment_ids) == self.max_words pairs_text = np.array(input_ids) pairs_mask = np.array(input_mask) pairs_segment = np.array(segment_ids) return pairs_text, pairs_mask, pairs_segment def _get_rawvideo(self, video_id): """get sampled frames Args: video_id: id of video Returns: video: sampled frame video_mask: mask of video """ video_mask = np.zeros((1, self.max_frames), dtype=np.long) # 1 x L x 1 x 3 x H x W video = np.zeros((1, self.max_frames, 1, 3, self.frameExtractor.size, self.frameExtractor.size), dtype=np.float) # video_path video_path = os.path.join(self.features_path, video_id) # get sampling frames raw_video_data = self.frameExtractor.get_video_data(video_path, self.max_frames) raw_video_data = raw_video_data['video'] # L x 1 x 3 x H x W if len(raw_video_data.shape) > 3: raw_video_data_clip = raw_video_data # L x T x 3 x H x W raw_video_slice = self.frameExtractor.process_raw_data(raw_video_data_clip) # max_frames x 1 x 3 x H x W if self.max_frames < raw_video_slice.shape[0]: sample_indx = np.linspace(0, raw_video_slice.shape[0] - 1, num=self.max_frames, dtype=int) video_slice = raw_video_slice[sample_indx, ...] else: video_slice = raw_video_slice # set max length, and save video mask and frames slice_len = video_slice.shape[0] video_mask[0][:slice_len] = [1] * slice_len video[0][:slice_len, ...] = video_slice else: print("get raw video error, skip it.") return video, video_mask def __getitem__(self, idx): """forward method Args: idx: id Returns: pairs_text: tokenized text pairs_mask: mask of tokenized text pairs_segment: type of tokenized text video: sampled frames video_mask: mask of sampled frames """ video_id = self.data['video_id'].values[idx] sentence = self.data['sentence'].values[idx] # obtain text data pairs_text, pairs_mask, pairs_segment = self._get_text(sentence) #obtain video data video, video_mask = self._get_rawvideo(video_id) return pairs_text, pairs_mask, pairs_segment, video, video_mask class MSRVTT_multi_sentence_dataLoader(Dataset): """MSRVTT dataset loader for multi-sentence Attributes: csv_path: video id of sub set json_path: total information of video features_path: frame directory tokenizer: tokenize the word max_words: the max number of word feature_framerate: frame rate for sampling video max_frames: the max number of frame image_resolution: resolution of images """ def __init__( self, csv_path, json_path, features_path, tokenizer, max_words=30, feature_framerate=1.0, max_frames=100, image_resolution=224, ): self.csv = pd.read_csv(csv_path) self.data = json.load(open(json_path, 'r')) self.features_path = features_path self.feature_framerate = feature_framerate self.max_words = max_words self.max_frames = max_frames self.tokenizer = tokenizer self.sample_len = 0 # store the pairs for video and text train_video_ids = list(self.csv['video_id'].values) self.sentences_dict = {} for itm in self.data['sentences']: if itm['video_id'] in train_video_ids: self.sentences_dict[len(self.sentences_dict)] = (itm['video_id'], itm['caption']) # set the length of paris for one epoch self.sample_len = len(self.sentences_dict) # frame extractor to sample frames from video self.frameExtractor = RawFrameExtractor(framerate=feature_framerate, size=image_resolution, train="train") # start and end token self.SPECIAL_TOKEN = {"CLS_TOKEN": "<|startoftext|>", "SEP_TOKEN": "<|endoftext|>", "MASK_TOKEN": "[MASK]", "UNK_TOKEN": "[UNK]", "PAD_TOKEN": "[PAD]"} def __len__(self): """length of data loader Returns: length: length of data loader """ length = self.sample_len return length def _get_text(self, caption): """get tokenized word feature Args: caption: caption Returns: pairs_text: tokenized text pairs_mask: mask of tokenized text pairs_segment: type of tokenized text """ # tokenize word words = self.tokenizer.tokenize(caption) # add cls token words = [self.SPECIAL_TOKEN["CLS_TOKEN"]] + words total_length_with_CLS = self.max_words - 1 if len(words) > total_length_with_CLS: words = words[:total_length_with_CLS] # add end token words = words + [self.SPECIAL_TOKEN["SEP_TOKEN"]] # convert token to id according to the vocab input_ids = self.tokenizer.convert_tokens_to_ids(words) # add zeros for feature of the same length input_mask = [1] * len(input_ids) segment_ids = [0] * len(input_ids) while len(input_ids) < self.max_words: input_ids.append(0) input_mask.append(0) segment_ids.append(0) # ensure the length of feature to be equal with max words assert len(input_ids) == self.max_words assert len(input_mask) == self.max_words assert len(segment_ids) == self.max_words pairs_text = np.array(input_ids) pairs_mask = np.array(input_mask) pairs_segment = np.array(segment_ids) return pairs_text, pairs_mask, pairs_segment def _get_rawvideo(self, video_id): """get sampled frame Args: video_id: id of video Returns: video: sampled frame video_mask: mask of video """ video_mask = np.zeros((1, self.max_frames), dtype=np.long) # 1 x L x 1 x 3 x H x W video = np.zeros((1, self.max_frames, 1, 3, self.frameExtractor.size, self.frameExtractor.size), dtype=np.float) # video_path video_path = os.path.join(self.features_path, video_id) # get sampling frames raw_video_data = self.frameExtractor.get_video_data(video_path, self.max_frames) raw_video_data = raw_video_data['video'] # L x 1 x 3 x H x W if len(raw_video_data.shape) > 3: raw_video_data_clip = raw_video_data # L x T x 3 x H x W raw_video_slice = self.frameExtractor.process_raw_data(raw_video_data_clip) # max_frames x 1 x 3 x H x W if self.max_frames < raw_video_slice.shape[0]: sample_indx = np.linspace(0, raw_video_slice.shape[0] - 1, num=self.max_frames, dtype=int) video_slice = raw_video_slice[sample_indx, ...] else: video_slice = raw_video_slice # set max length, and save video mask and frames slice_len = video_slice.shape[0] video_mask[0][:slice_len] = [1] * slice_len video[0][:slice_len, ...] = video_slice else: print("get raw video error, skip it.") return video, video_mask def __getitem__(self, idx): """forward method Args: idx: id Returns: pairs_text: tokenized text pairs_mask: mask of tokenized text pairs_segment: type of tokenized text video: sampled frames video_mask: mask of sampled frames """ video_id, caption = self.sentences_dict[idx] # obtain text data pairs_text, pairs_mask, pairs_segment = self._get_text(caption) #obtain video data video, video_mask = self._get_rawvideo(video_id) return pairs_text, pairs_mask, pairs_segment, video, video_mask <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: __init__.py # @Version: version 1.0 <file_sep>ftfy regex opencv-python pandas torchvision==0.8.2 torch==1.7.1 <file_sep># Adapted from https://github.com/ArrowLuo/CLIP4Clip/blob/668334707c493a4eaee7b4a03b2dae04915ce170/main_task_retrieval.py#L457 import os import sys sys.path.append(os.path.dirname(__file__) + os.sep + '../') import numpy as np from evaluation.metrics import compute_metrics from evaluation.metrics import tensor_text_to_video_metrics from evaluation.metrics import tensor_video_to_text_sim from utils.utils import parallel_apply import torch def _run_on_single_gpu(model, batch_list_t, batch_list_v, batch_sequence_output_list, batch_visual_output_list): """run similarity in one single gpu Args: model: CLIP2Video batch_list_t: id of text embedding batch_list_v: id of visual embedding batch_sequence_output_list: batch text embedding batch_visual_output_list: batch visual embedding Returns: sim_matrix: similarity """ sim_matrix = [] for idx1, b1 in enumerate(batch_list_t): input_mask, segment_ids, *_tmp = b1 sequence_output = batch_sequence_output_list[idx1] each_row = [] for idx2, b2 in enumerate(batch_list_v): video_mask, *_tmp = b2 visual_output = batch_visual_output_list[idx2] # calculate the similarity b1b2_logits, *_tmp = model.get_inference_logits(sequence_output, visual_output, input_mask, video_mask) b1b2_logits = b1b2_logits.cpu().detach().numpy() each_row.append(b1b2_logits) each_row = np.concatenate(tuple(each_row), axis=-1) sim_matrix.append(each_row) return sim_matrix def eval_epoch(model, test_dataloader, device, n_gpu, logger): """run similarity in one single gpu Args: model: CLIP2Video test_dataloader: data loader for test device: device to run model n_gpu: GPU number batch_sequence_output_list: batch text embedding batch_visual_output_list: batch visual embedding Returns: R1: rank 1 of text-to-video retrieval """ if hasattr(model, 'module'): model = model.module.to(device) else: model = model.to(device) # if multi_sentence_ == True: compute the similarity with multi-sentences retrieval multi_sentence_ = False cut_off_points_, sentence_num_, video_num_ = [], -1, -1 if hasattr(test_dataloader.dataset, 'multi_sentence_per_video') \ and test_dataloader.dataset.multi_sentence_per_video: multi_sentence_ = True cut_off_points_ = test_dataloader.dataset.cut_off_points # used to tag the label when calculate the metric sentence_num_ = test_dataloader.dataset.sentence_num # used to cut the sentence representation video_num_ = test_dataloader.dataset.video_num # used to cut the video representation cut_off_points_ = [itm - 1 for itm in cut_off_points_] if multi_sentence_: logger.warning("Eval under the multi-sentence per video clip setting.") logger.warning("sentence num: {}, video num: {}".format(sentence_num_, video_num_)) model.eval() with torch.no_grad(): batch_list_t = [] batch_list_v = [] batch_sequence_output_list, batch_visual_output_list = [], [] total_video_num = 0 for bid, batch in enumerate(test_dataloader): batch = tuple(t.to(device) for t in batch) input_ids, input_mask, segment_ids, video, video_mask = batch if multi_sentence_: # multi-sentences retrieval means: one frame clip has two or more descriptions. b, *_t = video.shape sequence_output = model.get_sequence_output(input_ids, segment_ids, input_mask) batch_sequence_output_list.append(sequence_output) batch_list_t.append((input_mask, segment_ids,)) s_, e_ = total_video_num, total_video_num + b filter_inds = [itm - s_ for itm in cut_off_points_ if itm >= s_ and itm < e_] if len(filter_inds) > 0: video, video_mask = video[filter_inds, ...], video_mask[filter_inds, ...] visual_output = model.get_visual_output(video, video_mask) batch_visual_output_list.append(visual_output) batch_list_v.append((video_mask,)) total_video_num += b else: sequence_output, visual_output = model.get_sequence_visual_output(input_ids, segment_ids, input_mask, video, video_mask) batch_sequence_output_list.append(sequence_output) batch_list_t.append((input_mask, segment_ids,)) batch_visual_output_list.append(visual_output) batch_list_v.append((video_mask,)) print("{}/{}\r".format(bid, len(test_dataloader)), end="") if n_gpu > 1: device_ids = list(range(n_gpu)) batch_list_t_splits = [] batch_list_v_splits = [] batch_t_output_splits = [] batch_v_output_splits = [] bacth_len = len(batch_list_t) split_len = (bacth_len + n_gpu - 1) // n_gpu # split the pairs for multi-GPU for dev_id in device_ids: s_, e_ = dev_id * split_len, (dev_id + 1) * split_len if dev_id == 0: batch_list_t_splits.append(batch_list_t[s_:e_]) batch_list_v_splits.append(batch_list_v) batch_t_output_splits.append(batch_sequence_output_list[s_:e_]) batch_v_output_splits.append(batch_visual_output_list) else: devc = torch.device('cuda:{}'.format(str(dev_id))) devc_batch_list = [tuple(t.to(devc) for t in b) for b in batch_list_t[s_:e_]] batch_list_t_splits.append(devc_batch_list) devc_batch_list = [tuple(t.to(devc) for t in b) for b in batch_list_v] batch_list_v_splits.append(devc_batch_list) if isinstance(batch_sequence_output_list[s_], tuple): # for multi_output devc_batch_list = [(b[0].to(devc), b[1].to(devc)) for b in batch_sequence_output_list[s_:e_]] else: # for single_output devc_batch_list = [b.to(devc) for b in batch_sequence_output_list[s_:e_]] batch_t_output_splits.append(devc_batch_list) devc_batch_list = [b.to(devc) for b in batch_visual_output_list] batch_v_output_splits.append(devc_batch_list) parameters_tuple_list = [(batch_list_t_splits[dev_id], batch_list_v_splits[dev_id], batch_t_output_splits[dev_id], batch_v_output_splits[dev_id]) for dev_id in device_ids] # calculate the similarity respectively and concatenate them parallel_outputs = parallel_apply(_run_on_single_gpu, model, parameters_tuple_list, device_ids) sim_matrix = [] for idx in range(len(parallel_outputs)): sim_matrix += parallel_outputs[idx] sim_matrix = np.concatenate(tuple(sim_matrix), axis=0) else: # calculate the similarity in one GPU sim_matrix = _run_on_single_gpu(model, batch_list_t, batch_list_v, batch_sequence_output_list, batch_visual_output_list) sim_matrix = np.concatenate(tuple(sim_matrix), axis=0) R1 = logging_rank(sim_matrix, multi_sentence_, cut_off_points_, logger) return R1 def logging_rank(sim_matrix, multi_sentence_, cut_off_points_, logger): """run similarity in one single gpu Args: sim_matrix: similarity matrix multi_sentence_: indicate whether the multi sentence retrieval cut_off_points_: tag the label when calculate the metric logger: logger for metric Returns: R1: rank 1 of text-to-video retrieval """ if multi_sentence_: # if adopting multi-sequence retrieval, the similarity matrix should be reshaped logger.info("before reshape, sim matrix size: {} x {}".format(sim_matrix.shape[0], sim_matrix.shape[1])) cut_off_points2len_ = [itm + 1 for itm in cut_off_points_] max_length = max([e_-s_ for s_, e_ in zip([0]+cut_off_points2len_[:-1], cut_off_points2len_)]) sim_matrix_new = [] for s_, e_ in zip([0] + cut_off_points2len_[:-1], cut_off_points2len_): sim_matrix_new.append(np.concatenate((sim_matrix[s_:e_], np.full((max_length-e_+s_, sim_matrix.shape[1]), -np.inf)), axis=0)) sim_matrix = np.stack(tuple(sim_matrix_new), axis=0) logger.info("after reshape, sim matrix size: {} x {} x {}". format(sim_matrix.shape[0], sim_matrix.shape[1], sim_matrix.shape[2])) # compute text-to-video retrieval tv_metrics = tensor_text_to_video_metrics(sim_matrix) # compute video-to-text retrieval vt_metrics = compute_metrics(tensor_video_to_text_sim(sim_matrix)) else: logger.info("sim matrix size: {}, {}".format(sim_matrix.shape[0], sim_matrix.shape[1])) # compute text-to-video retrieval tv_metrics = compute_metrics(sim_matrix) # compute video-to-text retrieval vt_metrics = compute_metrics(sim_matrix.T) logger.info('\t Length-T: {}, Length-V:{}'.format(len(sim_matrix), len(sim_matrix[0]))) # logging the result of text-to-video retrieval logger.info("Text-to-Video:") logger.info('\t>>> R@1: {:.1f} - R@5: {:.1f} - R@10: {:.1f} - Median R: {:.1f} - Mean R: {:.1f}'. format(tv_metrics['R1'], tv_metrics['R5'], tv_metrics['R10'], tv_metrics['MR'], tv_metrics['MeanR'])) # logging the result of video-to-text retrieval logger.info("Video-to-Text:") logger.info( '\t>>> V2T$R@1: {:.1f} - V2T$R@5: {:.1f} - V2T$R@10: {:.1f} - V2T$Median R: {:.1f} - V2T$Mean R: {:.1f}'.format( vt_metrics['R1'], vt_metrics['R5'], vt_metrics['R10'], vt_metrics['MR'], vt_metrics['MeanR'])) R1 = tv_metrics['R1'] return R1 <file_sep>VERSION=CLIP2Video DATA_PATH=${VERSION}/data/vatex_data/ CHECKPOINT=[downloaded trained model path] MODEL_NUM=22 python ${VERSION}/infer_retrieval.py \ --num_thread_reader=2 \ --data_path ${DATA_PATH} \ --features_path [frame path] \ --output_dir ${CHECKPOINT}/test_${MODEL_NUM}.txt \ --max_words 32 \ --max_frames 12 \ --batch_size_val 64 \ --datatype vatexEnglish \ --feature_framerate 1 \ --sim_type seqTransf \ --checkpoint ${CHECKPOINT} \ --do_eval \ --model_num ${MODEL_NUM} \ --temporal_type TDB \ --temporal_proj sigmoid_selfA \ --center_type TAB \ --centerK 7 \ --center_weight 0.5 \ --center_proj TAB_TDB \ --clip_path ${VERSION}/ViT-B-32.pt <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @File: module_clip.py # @Version: version 1.0 # Adapted from: https://github.com/openai/CLIP/blob/main/clip/clip.py from collections import OrderedDict import os import torch from torch import nn # if the pretrained model doesn't exist, please download the model from the link of openai # in this project, we adopt ViT-B/32 for pre-training _MODELS = { "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", } def available_models(): """Returns the names of available CLIP models""" return list(_MODELS.keys()) class LayerNorm(nn.LayerNorm): """Subclass torch's LayerNorm to handle fp16.""" def forward(self, x): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): """residual attention block used in transformer Attributes: attn: multi-head attention ln_1: layer normalization mlp: MLP ln_2: layer normalization attn_mask: attention mask """ def __init__(self, d_model, n_head, attn_mask=None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ("c_fc", nn.Linear(d_model, d_model * 4)), ("gelu", QuickGELU()), ("c_proj", nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x): attn_mask_ = self.attn_mask if self.attn_mask is not None and hasattr(self.attn_mask, '__call__'): attn_mask_ = self.attn_mask(x.size(0)) # LND attn_mask_ = attn_mask_.to(dtype=x.dtype, device=x.device) if attn_mask_ is not None else None return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask_)[0] def forward(self, x_tuple): x, video_frame = x_tuple x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return (x, video_frame) class Transformer(nn.Module): """basic transformer Attributes: width: dimension for the output of every layer layers: total number of layers resblocks: residual block """ def __init__(self, width, layers, heads, attn_mask = None): super().__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) def forward(self, x, video_frame=-1): return self.resblocks((x, video_frame))[0] class VisualTransformer(nn.Module): """basic vision transformer Attributes: input_resolution: input resolution of image patch_size: patch size to split image width: dimension for the output of every layer layers: total number of layers heads: head for multi-head attention output_dim: the final output of ViT """ def __init__(self, input_resolution, patch_size, width, layers, heads, output_dim): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) scale = width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width) self.transformer = Transformer(width, layers, heads) self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) def forward(self, x, video_frame=-1): x = self.conv1(x) # shape = [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] x = torch.cat( [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x, video_frame=video_frame) x = x.permute(1, 0, 2) # LND -> NLD # Move the three lines below to `encode_image` for entire hidden sequence # x = self.ln_post(x[:, 0, :]) # if self.proj is not None: # x = x @ self.proj return x class CLIP(nn.Module): """basic CLIP model Attributes: input_resolution: input resolution of image patch_size: patch size to split image width: dimension for the output of every layer layers: total number of layers heads: head for multi-head attention output_dim: the final output of ViT """ def __init__(self, embed_dim, # vision image_resolution, vision_layers, vision_width, vision_patch_size, # text context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, ): super().__init__() # the length of caption self.context_length = context_length # set vision transformer vision_heads = vision_width // 64 self.visual = VisualTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim ) # set the text transformer self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask ) self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width) self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([])) self.initialize_parameters() def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01) proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) @staticmethod def get_config(clip_path='/data/ceph_11015/ssd/howiefang/videoCLIP/CLIP2Clip/ViT-B-32.pt'): if os.path.exists(clip_path): pass else: raise RuntimeError(f"Model ViT-B/32 not found; available models = {available_models()}") try: # loading JIT archive model = torch.jit.load(clip_path, map_location="cpu").eval() state_dict = model.state_dict() except RuntimeError: state_dict = torch.load(clip_path, map_location="cpu") return state_dict def build_attention_mask(self, context_length): """build attention mask for text Args: context_length: length of caption Returns: mask: the constructed mask """ mask = torch.zeros(context_length, context_length) mask.fill_(float("-inf")) mask.triu_(1) # zero out the lower diagonal return mask @property def dtype(self): return self.visual.conv1.weight.dtype def encode_image(self, image, return_hidden=False, video_frame=-1): """image encoder Args: image: image return_hidden: whether to return hidden variable video_frame: frame length of video Returns: x: output embedding [1,512] """ hidden = self.visual(image.type(self.dtype), video_frame=video_frame) hidden = self.visual.ln_post(hidden) @ self.visual.proj x = hidden[:, 0, :] if return_hidden: return x, hidden return x def encode_text(self, text, return_hidden=False): """text encoder Args: text: caption return_hidden: whether to return hidden variable Returns: x: output embedding [1,512] """ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model] pos_emd = self.positional_embedding[:x.size(1), :].type(self.dtype) x = x + pos_emd x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD hidden = self.ln_final(x).type(self.dtype) @ self.text_projection # x.shape = [batch_size, n_ctx, transformer.width] # take features from the eot embedding (eot_token is the highest number in each sequence) x = hidden[torch.arange(hidden.shape[0]), text.argmax(dim=-1)] if return_hidden: return x, hidden return x def forward(self, image, text): """forward method for CLIP Args: image: image text: caption Returns: logits_per_image: image-to-text similarity logits_per_text: text-to-image similarity """ image_features = self.encode_image(image) text_features = self.encode_text(text) # normalized features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True) # cosine similarity as logit logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logit_scale * text_features @ image_features.t() # shape = [global_batch_size, global_batch_size] return logits_per_image, logits_per_text def convert_weights(model: nn.Module): """Convert applicable model parameters to fp16""" def _convert_weights_to_fp16(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d, nn.Linear)): l.weight.data = l.weight.data.half() if l.bias is not None: l.bias.data = l.bias.data.half() if isinstance(l, nn.MultiheadAttention): for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: tensor = getattr(l, attr) if tensor is not None: tensor.data = tensor.data.half() for name in ["text_projection", "proj"]: if hasattr(l, name): attr = getattr(l, name) if attr is not None: attr.data = attr.data.half() model.apply(_convert_weights_to_fp16)<file_sep>#coding:utf-8 # @Time : 2021/4/25 9:56 下午 # @Author : <NAME> # @File: config.py # @Version: 2021/4/25 9:56 下午 config.py import argparse def get_args(description='CLIP2Video on Dideo-Text Retrieval Task'): parser = argparse.ArgumentParser(description=description) # arugment based on CLIP4clip: # https://github.com/ArrowLuo/CLIP4Clip/blob/668334707c493a4eaee7b4a03b2dae04915ce170/main_task_retrieval.py#L457 parser.add_argument("--do_eval", action='store_true', help="Whether to run eval on the dev set.") parser.add_argument('--val_csv', type=str, default='data/.val.csv', help='') parser.add_argument('--data_path', type=str, default='data/caption.pickle', help='data pickle file path') parser.add_argument('--features_path', type=str, default='data/videos_feature.pickle', help='feature path') parser.add_argument('--num_thread_reader', type=int, default=1, help='') parser.add_argument('--batch_size_val', type=int, default=3500, help='batch size eval') parser.add_argument('--seed', type=int, default=42, help='random seed') parser.add_argument('--max_words', type=int, default=32, help='') parser.add_argument('--max_frames', type=int, default=100, help='') parser.add_argument('--feature_framerate', type=int, default=1, help='frame rate for uniformly sampling the video') parser.add_argument("--output_dir", default=None, type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.") parser.add_argument("--cross_model", default="cross-base", type=str, required=False, help="Cross module") parser.add_argument("--do_lower_case", action='store_true', help="Set this flag if you are using an uncased model.") parser.add_argument('--n_gpu', type=int, default=1, help="Changed in the execute process.") parser.add_argument("--cache_dir", default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3") parser.add_argument('--fp16', action='store_true', help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit") parser.add_argument('--fp16_opt_level', type=str, default='O1', help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html") parser.add_argument('--cross_num_hidden_layers', type=int, default=4, help="Layer NO. of cross.") # important extra argument for training and testing CLIP2Video parser.add_argument('--sim_type', type=str, default="meanP", choices=["meanP", "seqTransf"], help="choice a similarity header.") # argument for testing parser.add_argument('--checkpoint', type=str, default='', help="checkpoint dir") parser.add_argument('--model_num', type=str, default='', help="model id") parser.add_argument('--local_rank', default=0, type=int, help='shard_id: node rank for distributed training') parser.add_argument("--datatype", default="msrvtt", type=str, help="msvd | msrvtt | vatexEnglish | msrvttfull") # for different vocab size parser.add_argument('--vocab_size', type=int, default=49408, help="the number of vocab size") # for TDB block parser.add_argument('--temporal_type', type=str, default='', help="TDB type") parser.add_argument('--temporal_proj', type=str, default='', help="sigmoid_mlp | sigmoid_selfA") # for TAB block parser.add_argument('--center_type', type=str, default='', help="TAB") parser.add_argument('--centerK', type=int, default=5, help='center number for clustering.') parser.add_argument('--center_weight', type=float, default=0.5, help='the weight to adopt the main simiarility') parser.add_argument('--center_proj', type=str, default='', help='TAB | TAB_TDB') # model path of clip parser.add_argument('--clip_path', type=str, default='/data/ceph_11015/ssd/howiefang/videoCLIP/CLIP2Clip/ViT-B-32.pt', help="model path of CLIP") args = parser.parse_args() return args <file_sep># CLIP2Video: Mastering Video-Text Retrieval via Image CLIP The implementation of paper [**CLIP2Video: Mastering Video-Text Retrieval via Image CLIP**](https://arxiv.org/abs/2106.11097). CLIP2Video is a video-text retrieval model based on [CLIP (ViT-B/32)](https://github.com/openai/CLIP), which transfers the image-language pre-training model to video-text retrieval in an end-to-end manner. Our model involves a Temporal Difference Block to capture motions at fine temporal video frames, and a Temporal Alignment Block to re-align the tokens of video clips and phrases and enhance the multi-modal correlation. We conduct thorough ablation studies, and achieve state-of-the-art performance on major text-to-video and video-to-text retrieval benchmarks, including new records of retrieval accuracy on MSR-VTT, MSVD and VATEX. ![Pipeline](pipeline.png) ![Blocks](module.png) ## Introduction This is the source code of CLIP2Video, a method for Video-Text Retrieval based on temporal correlations. It is built on top of the CLIP4Clip by ([ <NAME> *et al.*](https://github.com/ArrowLuo/CLIP4Clip)) in PyTorch. ## Requirement ``` pip install -r requirements.txt ``` ## Download data and Pre-trained Model **Supported public training sets:** * MSR-VTT(9k) * MSR-VTT(full) * MSVD * VATEX-English Version **Supported public testing protocols:** * MSR-VTT 1k-A protocol (*SOTA*) * MSR-VTT full protocol (*SOTA*) * MSVD(*SOTA*) * VATEX-English version(*SOTA*) **Download official video:** Official videos of different data can be found as follows: * MSRVTT: [link](http://ms-multimedia-challenge.com/2017/dataset). * MSVD: [link](https://www.cs.utexas.edu/users/ml/clamp/videoDescription). * VATEX: [link](https://eric-xw.github.io/vatex-website/download.html). **Pre-process** To train and test the above datasets: you should use `sample_frame.py` to transform video into frames. ~~~ python sample_frame.py --input_path [raw video path] --output_path [frame path] ~~~ (*Optional*) The splits and captions can be found in the links of used dataset. For the convenience, you can also use the split in ` data/` directly. **Download CLIP model** To train and test the above datasets based on pre-trained CLIP model, you should visit [CLIP](https://github.com/openai/CLIP) and download [ViT-B/32](https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt). ## Test Model We provide three models trained on MSVD, MSR-VTT and VATEX-English. | Model Name | checkpoint| | :-----------: | :-----------: | |CLIP2Video_MSVD | [link](https://drive.google.com/drive/folders/1LKMUZFf9EAxFbGShlA22eUCeGKC8DWx4?usp=sharing) | |CLIP2Video_MSRVTT9k | [link](https://drive.google.com/drive/folders/1a5Dcg8wNh88Z-bxb0ZMV3IJFjtSe7X2A?usp=sharing) | |CLIP2Video_VATEX | [link](https://drive.google.com/drive/folders/15IDB7NdNx6DQx-LcTzvB3JiZZFu9v36l?usp=sharing) | To test the trained model, please refer `test/`. (*Optional*) If the path of trained model(`--checkpoint`) doesn't exist, the parameters of basic CLIP (`--clip_path`) will be loaded. ## Main Article Results of CLIP2Video **T2V:** | Protocol | R@1 | R@5 | R@10 | Median Rank | Mean Rank | | :-----------: | :-----------: | ---------- | :-----------: | :-----------: | :-----------: | |MSVD | 47.0 | 76.8 | 85.9 | 2 | 9.6 | |MSRVTT-9k | 45.6 | 72.6 | 81.7 | 2 | 14.6 | |MSRVTT-Full | 29.8 | 55.5 | 66.2 | 4 | 45.5 | |Vatex (English) random 1k5 split | 57.3 | 90.0 | 95.5 | 1 | 3.6 | |Vatex (English) HGR split| 61.2 | 90.9 | 95.6 | 1 | 3.4 | **V2T:** | Protocol | R@1 | R@5 | R@10 | Median Rank | Mean Rank | | :-----------: | :-----------: | ---------- | :-----------: | :-----------: | :-----------: | |MSVD | 58.7 | 85.6 | 91.6 | 1 | 4.3 | |MSRVTT-9k | 43.5 | 72.3 | 82.1 | 2 | 10.2 | |MSRVTT-Full | 54.6 | 82.1 | 90.8 | 1 | 5.3 | |Vatex (English) random 1k5 split | 76.0 | 97.7 | 99.9 | 1 | 1.5 | |Vatex (English) HGR split | 77.9 | 98.1 | 99.1 | 1 | 1.6 | **(Optional:)** Clarification of different results in VATEX: 1. In our paper, we do not strictly follow [HGR's split](https://arxiv.org/abs/2003.00392), but randomly split the test set by ourselves, which is the split in * data/vatex_data/test1k5_sec_list.txt 2. In HGR split, we adopt the totally same split following HGR, and the split can be seen as: * data/vatex_data/test_list.txt * data/vatex_data/val_list.txt We will revise the results strictly following HGR split for fair comparison in the paper later! ----------------------- # Citation If you find CLIP2Video useful in your work, you can cite the following paper: ``` @article{fang2021clip2video, title={CLIP2Video: Mastering Video-Text Retrieval via Image CLIP}, author={<NAME> and <NAME> and <NAME> and <NAME>}, journal={arXiv preprint arXiv:2106.11097}, year={2021} } ``` # Acknowledgments Some components of this code implementation are adopted from [CLIP](https://github.com/openai/CLIP) and [CLIP4Clip](https://github.com/ArrowLuo/CLIP4Clip/). We sincerely appreciate for their contributions. <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: raw_frame_util.py # @Version: version 1.0 import torch import numpy as np from PIL import Image # pytorch=1.7.1 from torchvision.transforms import Compose from torchvision.transforms import Resize from torchvision.transforms import CenterCrop from torchvision.transforms import ToTensor from torchvision.transforms import Normalize import os class RawFrameExtractor(): """frame extractor for a given of directory with video Attributes: centercrop: center crop for pre-preprocess size: resolution of images framerate: frame rate for sampling transform: transform method for pre-process train: set train for random sampling in the uniform interval """ def __init__(self, centercrop=False, size=224, framerate=-1, train='subset'): self.centercrop = centercrop self.size = size self.framerate = framerate self.transform = self._transform(self.size) self.train = True if train == 'train' else False def _transform(self, n_px): return Compose([ Resize(n_px, interpolation=Image.BICUBIC), CenterCrop(n_px), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ]) def video_to_tensor(self, video_file, max_frame, preprocess, sample_fp=0): """sample video into tensor Args: video_file: location of video file max_frame: max frame number preprocessL preprocess method sample_fp: sampling rate Returns: image_input: sample frames """ assert sample_fp > -1 video_name = os.listdir(video_file) video_name.sort() # Pre-uniform sampling current_frame = len(video_name) // sample_fp current_sample_indx = np.linspace(0, len(video_name) - 1, num=current_frame, dtype=int) # if the length of current_sample_indx is already less than max_frame, just use the current version to tensor # else continue to uniformly sample the frames whose length is max_frame # when training, the frames are sampled randomly in the uniform split interval if max_frame >= current_sample_indx.shape[0]: frame_index = np.arange(0, current_sample_indx.shape[0]) else: frame_index = np.linspace(0, current_sample_indx.shape[0] - 1, num=max_frame, dtype=int) if self.train: step_len = (frame_index[1] - frame_index[0]) // 2 if step_len > 2: random_index = np.random.randint(-1 * step_len, step_len, (frame_index.shape[0] - 2)) zero_index = np.zeros((1)) index = np.concatenate((zero_index, random_index, zero_index)) frame_index = frame_index + index # pre-process frames images = [] for index in frame_index: image_path = os.path.join(video_file, video_name[current_sample_indx[int(index)]]) images.append(preprocess(Image.open(image_path).convert("RGB"))) # convert into tensor if len(images) > 0: video_data = torch.tensor(np.stack(images)) else: video_data = torch.zeros(1) return {'video': video_data} def get_video_data(self, video_path, max_frame): """get video data Args: video_path: id max_frame: max frame number Returns: image_input: sample frames """ image_input = self.video_to_tensor(video_path, max_frame, self.transform, sample_fp=self.framerate) return image_input def process_raw_data(self, raw_video_data): """reshape the raw video Args: raw_video_data: sampled frames Returns: tensor: reshaped tensor """ tensor_size = raw_video_data.size() tensor = raw_video_data.view(-1, 1, tensor_size[-3], tensor_size[-2], tensor_size[-1]) return tensor <file_sep>#coding:utf-8 # @Time : 2021/6/19 # @Author : <NAME> # @File: dataloader_vatexEnglish_frame.py # @Version: version 1.0 import os from torch.utils.data import Dataset import numpy as np import json from dataloaders.rawframe_util import RawFrameExtractor class VATEXENGLISH_multi_sentence_dataLoader(Dataset): """VATEX with English annotations dataset loader for multi-sentence Attributes: subset: indicate train or test or val data_path: path of data list features_path: frame directory tokenizer: tokenize the word max_words: the max number of word feature_framerate: frame rate for sampling video max_frames: the max number of frame image_resolution: resolution of images """ def __init__( self, subset, data_path, features_path, tokenizer, max_words=30, feature_framerate=1.0, max_frames=100, image_resolution=224, ): self.subset = subset self.data_path = data_path self.features_path = features_path self.feature_framerate = feature_framerate self.max_words = max_words self.max_frames = max_frames self.tokenizer = tokenizer # load the id of split list assert self.subset in ["train", "val", "test"] video_id_path_dict = {} video_id_path_dict["train"] = os.path.join(self.data_path, "train_list.txt") video_id_path_dict["test"] = os.path.join(self.data_path, "test_list.txt") # construct ids for data loader with open(video_id_path_dict[self.subset], 'r') as fp: video_ids = [itm.strip() for itm in fp.readlines()] # load caption caption_file = os.path.join(self.data_path, "vatex_data.json") captions = json.load(open(caption_file, 'r')) # ensure the existing directory for training video_dict = {} for video_file in os.listdir(self.features_path): video_path = os.path.join(self.features_path, video_file) if not os.path.isdir(video_path): continue if len(os.listdir(video_path)) > 5: if video_file not in video_ids: continue video_dict[video_file] = video_path self.video_dict = video_dict # construct pairs self.sample_len = 0 self.sentences_dict = {} self.cut_off_points = [] # used to tag the label when calculate the metric for video_id in video_ids: assert video_id in captions if not video_id in self.video_dict.keys():continue for cap_txt in captions[video_id]['enCap']: self.sentences_dict[len(self.sentences_dict)] = (video_id, cap_txt) self.cut_off_points.append(len(self.sentences_dict)) # usd for multi-sentence retrieval self.multi_sentence_per_video = True # important tag for eval in multi-sentence retrieval if self.subset == "val" or self.subset == "test": self.sentence_num = len(self.sentences_dict) # used to cut the sentence representation self.video_num = len(list(self.video_dict.keys())) # used to cut the video representation assert len(self.cut_off_points) == self.video_num print("For {}, sentence number: {}".format(self.subset, self.sentence_num)) print("For {}, video number: {}".format(self.subset, self.video_num)) print("Video number: {}".format(len(self.video_dict))) print("Total Paire: {}".format(len(self.sentences_dict))) # length of dataloader for one epoch self.sample_len = len(self.sentences_dict) # frame extractor to sample frames from video self.frameExtractor = RawFrameExtractor(framerate=feature_framerate, size=image_resolution, train=self.subset) # start and end token self.SPECIAL_TOKEN = {"CLS_TOKEN": "<|startoftext|>", "SEP_TOKEN": "<|endoftext|>", "MASK_TOKEN": "[MASK]", "UNK_TOKEN": "[UNK]", "PAD_TOKEN": "[PAD]"} def __len__(self): """length of data loader Returns: length: length of data loader """ length = self.sample_len return length def _get_text(self, caption): """get tokenized word feature Args: caption: caption Returns: pairs_text: tokenized text pairs_mask: mask of tokenized text pairs_segment: type of tokenized text """ # tokenize word words = self.tokenizer.tokenize(caption) # add cls token words = [self.SPECIAL_TOKEN["CLS_TOKEN"]] + words total_length_with_CLS = self.max_words - 1 if len(words) > total_length_with_CLS: words = words[:total_length_with_CLS] # add end token words = words + [self.SPECIAL_TOKEN["SEP_TOKEN"]] # convert token to id according to the vocab input_ids = self.tokenizer.convert_tokens_to_ids(words) # add zeros for feature of the same length input_mask = [1] * len(input_ids) segment_ids = [0] * len(input_ids) while len(input_ids) < self.max_words: input_ids.append(0) input_mask.append(0) segment_ids.append(0) # ensure the length of feature to be equal with max words assert len(input_ids) == self.max_words assert len(input_mask) == self.max_words assert len(segment_ids) == self.max_words pairs_text = np.array(input_ids) pairs_mask = np.array(input_mask) pairs_segment = np.array(segment_ids) return pairs_text, pairs_mask, pairs_segment def _get_rawvideo(self, video_id): """get sampled frame Args: video_id: id of video Returns: video: sampled frame video_mask: mask of video """ video_mask = np.zeros((1, self.max_frames), dtype=np.long) # 1 x L x 1 x 3 x H x W video = np.zeros((1, self.max_frames, 1, 3, self.frameExtractor.size, self.frameExtractor.size), dtype=np.float) # video_path video_path = os.path.join(self.features_path, video_id) # get sampling frames raw_video_data = self.frameExtractor.get_video_data(video_path, self.max_frames) raw_video_data = raw_video_data['video'] # L x 1 x 3 x H x W if len(raw_video_data.shape) > 3: raw_video_data_clip = raw_video_data # L x T x 3 x H x W raw_video_slice = self.frameExtractor.process_raw_data(raw_video_data_clip) # max_frames x 1 x 3 x H x W if self.max_frames < raw_video_slice.shape[0]: sample_indx = np.linspace(0, raw_video_slice.shape[0] - 1, num=self.max_frames, dtype=int) video_slice = raw_video_slice[sample_indx, ...] else: video_slice = raw_video_slice # set max length, and save video mask and frames slice_len = video_slice.shape[0] video_mask[0][:slice_len] = [1] * slice_len video[0][:slice_len, ...] = video_slice else: print("get raw video error, skip it.") return video, video_mask def __getitem__(self, idx): """forward method Args: idx: id Returns: pairs_text: tokenized text pairs_mask: mask of tokenized text pairs_segment: type of tokenized text video: sampled frames video_mask: mask of sampled frames """ video_id, caption = self.sentences_dict[idx] # obtain text data pairs_text, pairs_mask, pairs_segment = self._get_text(caption) #obtain video data video, video_mask = self._get_rawvideo(video_id) return pairs_text, pairs_mask, pairs_segment, video, video_mask <file_sep># @Time : 2021/4/26 3:15 下午 # @Author : <NAME> # @File: get_list.py # @Version: 2021/4/26 3:15 下午 get_list.py import json import os import pandas as pd train_list = [] for i in range(0, 6513): train_list.append('video' + str(i)) val_list = [] for i in range(6513, 7010): val_list.append('video' + str(i)) test_list = [] for i in range(7010,10000): test_list.append('video' + str(i)) trainframe = pd.DataFrame({'video_id':train_list}) trainframe.to_csv("MSRVTT_train.full.csv",index=False,sep=',') valframe = pd.DataFrame({'video_id':val_list}) valframe.to_csv("MSRVTT_val.full.csv",index=False,sep=',') testframe = pd.DataFrame({'video_id':val_list}) testframe.to_csv("MSRVTT_test.full.csv",index=False,sep=',')
1f2fc2926e4113d6307653965aaa965e251ad5e4
[ "Markdown", "Python", "Text", "Shell" ]
15
Python
Venatoral/CLIP2Video
e94131800a3a1434f6d00b89b7301d741db8ba06
687fac964dcc6c7a8c6e3a5502e6c92bf3a95d52