language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
1,462
2.734375
3
[ "MIT" ]
permissive
--- layout: post title: "Computer Vision Tools for programmers" description: "recommendation of computer vision libraries for application programmers" comments: true author: Junjue Wang keywords: "computer vision, OpenCV, dlib, openVX" --- # Computer Vision Tools for programmers For application developers, especially mobile app developers, finding the correct vision library is not an easy task. A usual to-go is [OpenCV](http://opencv.org/) library, a comprehensive and robust computer vision library that can run on most platforms, including Linux, Windows, Mac OS, Android, and iOS. OpenCV is a SwissTool for computer vision. It includes an army of widely-used computer vision algorithms for simple tasks such as color conversion to complicated processing such as face recognition. However, as a SwissTool, OpenCV can be slow for a lot of computer vision tasks. Particularly, for mobile devices, OpenCV has too much footprint to satisfy the real-time latency requirements. Besides, it may also contain the particular algorithm you want. Here I put together a list of OpenCV alternatives that can facilitate building you computer vision applications. | Library | CPU | GPU Support | Mobile Oriented| Comments | |---------|-----|-----| | OpenCV | yes | no | cuda api, limited functions| | dlib | yes | no | no | | openVX | yes | no | yes | | openGL | no | yes | | GPUImage | no | yes | | Accelerated CV | | Armadillo | {: .pure-table .pure-table-bordered}
Markdown
UTF-8
965
2.59375
3
[]
no_license
## Deep learning for differentiation of benign and malignant solid liver lesions on ultrasonography ### Running this project This project can be initiated using simple scripts. 1. Inspect and edit the [`config.py`](./config.py) file to match your local installation preferences, i.e. where the project should expect to find your data files as well as where the project should output your results 2. The project expects your data to be in a folder referenced by the environment variable: `$DATA_DIR` 3. Initialize the project (creating the necessary directory and databases) using [`setup.sh`](./setup.sh) 4. Run the project using [`run.sh`](./run.sh) 5. (optional) create a `pushover-secret.sh` file to receive [pushover](https://pushover.net/) notifications when your run is completed: ### [Results](./results.ipynb) To inspect the jupyter notebook used to generate the results associated with this publication, please see [`results.ipynb`](./results.ipynb)
C++
UTF-8
1,341
2.84375
3
[]
no_license
#ifndef __DBUTIL_H__ #define __DBUTIL_H__ #include <mysql.h> #include "../util.hpp" using namespace std; class DBUtil{ public: DBUtil(); ~DBUtil(); int initDB(const string& server_host,const unsigned short port,const string& user,const string& passwd ,const string& db_name); MYSQL_RES* ExecuteSQL(const string& sql_str); int CreateTable(const string& sql_str); private: MYSQL* connection; }; DBUtil::DBUtil(){ if((connection = mysql_init(NULL)) == NULL) LOG(ERROR)<<"DBUtil init"<<endl; } DBUtil::~DBUtil(){ if(connection != NULL) mysql_close(connection); } int DBUtil::initDB(const string& server_host,const unsigned short port,const string& user,const string& passwd ,const string& db_name){ connection = mysql_real_connect(connection,server_host.c_str(),user.c_str(),passwd.c_str(),db_name.c_str(),port,NULL,0); if(connection == NULL){ LOG(ERROR)<<"mysql real connect: please check all paramters usage"<<endl; return -1; } return 0; } MYSQL_RES* DBUtil::ExecuteSQL(const string& sql_str){ if(mysql_query(connection,"set names utf8")) LOG(ERROR)<<mysql_errno(connection)<<": "<<mysql_error(connection)<<endl; if(!mysql_query(connection,sql_str.c_str())){ LOG(ERROR)<<"mysql_query: invalid sql_str"<<endl; return NULL; }else return mysql_use_result(connection); } #endif
PHP
UTF-8
416
2.640625
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Artist extends Model { protected $table = 'artists'; protected $fillable = ['name']; /** * Get the vinyls for the artist. */ public function vinyls() { return $this->hasMany('App\Vinyl'); } public function saveArtist($data) { $this->name = $data['name']; $this->save(); } }
Java
UTF-8
1,716
2.609375
3
[]
no_license
package com.example.liubiljett.handlers; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.liubiljett.classes.Post; import com.example.liubiljett.R; import java.util.ArrayList; /** * A custom adapter class used for creating the main feed, followed users feed and like posts */ public class FeedAdapter extends BaseAdapter { private ArrayList<Post> singleRow; private LayoutInflater mInflater; public FeedAdapter(Context context, ArrayList<Post> mRow){ this.singleRow = mRow; mInflater = (LayoutInflater.from(context)); } /** * Getters */ @Override public int getCount() { return singleRow.size(); } @Override public Object getItem(int position) { return singleRow.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null){ convertView = mInflater.inflate(R.layout.listview_row, parent, false); TextView headline = convertView.findViewById(R.id.headlineID); TextView price = convertView.findViewById(R.id.priceID); TextView description = convertView.findViewById(R.id.descID); Post currentRow = (Post) getItem(position); headline.setText(currentRow.getTitle()); price.setText(currentRow.getPrice()); description.setText(currentRow.getDesc()); } return convertView; } }
Markdown
UTF-8
906
2.984375
3
[]
no_license
# Project 9 - Drawing https://www.hackingwithswift.com/100/swiftui/43 Includes solutions to the [challenges](https://www.hackingwithswift.com/books/ios-swiftui/drawing-wrap-up). ## Topics Paths, shapes, strokes, transforms, drawing groups, animating values, Core Animation, Metal ## Challenges From [Hacking with Swift](https://www.hackingwithswift.com/books/ios-swiftui/drawing-wrap-up): >1. Create an Arrow shape made from a rectangle and a triangle – having it point straight up is fine. >2. Make the line thickness of your Arrow shape animatable. >3. Create a ColorCyclingRectangle shape that is the rectangular cousin of ColorCyclingCircle, allowing us to control the position of the gradient using a property. ## Screenshots ![screenshot1](screenshots/screen01.png) ![screenshot2](screenshots/screen02.png) ![screenshot3](screenshots/screen03.png) ![screenshot4](screenshots/screen04.png)
C++
UTF-8
1,227
2.8125
3
[]
no_license
/* * This test prints encoder values to the Serial Monitor for both wheels * To check, manually spin wheels and see if values change properly */ #include <VL6180X.h> #include <i2c_t3.h> #include <config.h> #include <Encoder.h> Encoder encoderLeft(pins::encoderL1, pins::encoderL2); Encoder encoderRight(pins::encoderR1, pins::encoderR2); void setup() { // put your setup code here, to run once: // quiet the buzzer pinMode(pins::buzzer, OUTPUT); digitalWrite(pins::buzzer, LOW); Serial.begin(9600); Serial.print("Right + Left Encoder Test:"); } long positionLeft = -999; long positionRight = -999; void loop() { long newLeft, newRight; newLeft = encoderLeft.read(); newRight = encoderRight.read(); if (newLeft != positionLeft || newRight != positionRight) { Serial.print("Left = "); Serial.print(newLeft); Serial.print(", Right = "); Serial.print(newRight); Serial.println(); positionLeft = newLeft; positionRight = newRight; } // if a character is sent from the serial monitor, // reset both back to zero. if (Serial.available()) { Serial.read(); Serial.println("Reset both knobs to zero"); encoderLeft.write(0); encoderRight.write(0); } }
Markdown
UTF-8
4,309
3.40625
3
[]
no_license
# Bayesian Knowledge Tracing Explainable Bayesian Knowledge Tracing (BKT) is a ML algorithm used in many intelligent tutoring systems to model a student's "mastery" of a particular skill with a series of questions. While many learners rely on this algorithm to accurately model their learning, most do not actually understand how BKT works. The goal of this project is to convey this information to potential users, comparing both interactive and static (reading through text summaries) approaches, through a web-based scrollable "explainable." We will then assess how each technique affects comprehension and sentiments (fairness, trust). ## Methodology We will perform our study on Mechanical Turk, randomly providing a link to either version of the explainables and using the survey as our primary method for both pre-test and post-test. For our explainble, we aim to teach the following tasks, as categorized by the Cognitive Process Dimension, a modified version of Bloom's Taxonomy: 1. Recall what BKT stands for. 2. Explain the context in which BKT is used. 3. List the 4 parameters used in the algorithm and be able to explain what each means: * P(G): guess parameter, does not know skill but correct response * P(S): slip parameter, knows skill but incorrect response * P(L_0): initial probability of knowing each skill * P(T): probability of learning the skill 4. Explain what it means for parameters to have “weights” and who ultimately determines these weights. 5. Calculate probability of mastery before the student answers any questions given the four parameter values and weights. 6. Know which formula to use (or at least, that the formulas are different) depending on whether the student gets the subsequent question correct or incorrect. 7. Explain how before a student gives a response, system re-calculates probability that the student knew the skill before response (conditional probability) 8. Assign a skill to be mastered/unmastered based on the current mastery percentage. 9. Be able to make commentaries about whether the algorithm is reliable and whether there are any circumstances where it fails to capture mastery of a certain skill. The Knowledge Dimension | Remember | Understand | Apply | Analyze | Evaluate | Create ------------- | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- Factual | 1 | | | | 5 | | Conceptual | 2, 3 | 4 | | | 8 | 12 Procedural | | 10 | 6 | 7 | | 13 Meta-cognitive | | | | 9 | | | For our survey, we aim to measure how effectively the explainable enhances users' understanding of the knowledge components covered by the explainable. In the survey, we follow the framework provided by Min Kyung Lee to measure fairness, trust, and emotion and the one provided by Poursabzi-Sangdeh to measure model intrepretability. ## Running on local host First, install Idyll using `npm` ``` $ npm install -g idyll ``` Then, install all the necessary package dependencies with ``` $ npm install ``` The working model can now be run on localhost:3000 using the command ``` $ idyll index.idyll --watch ``` Note: Two versions of the explainable, an interactive version and a static version, were created to quantify the effects of including clikable elements to engage the user. Currently, the interactive version is stored in `index.idyll` (default Idyll go-to when running the `--watch` command and the static version is stored in `index_static.idyll`. Running the above code by replacing `index.idyll` with `index_static.idyll` will not work because Idyll has other dependencies linked to that particular filename. Instead, the current workaround would be to rename each file (we did not elect to place them in completely separate repositories as that would generate a large amount of duplicate files). ## Deploying to web The necessary files for deployment are generated when the `--watch` command is run, as Idyll produces raw HTML/css scripts from our wrapper and stores them in the `\build` folder. Alternatively, if watching was not necessary and only the raw scripts were desired, run `npm build` instead for the same results. We chose to host these sites on GitHub Pages. Interactive version: https://eutopi.github.io/bkt-explorable/ Non-interactive version: https://eutopi.github.io/bkt-static/
C++
UTF-8
698
3.375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void sumNumbers(TreeNode* root, int res) { int tmp = res*10 + root->val; if(!root->left && !root->right){ sum += tmp; return; } if(root->left) sumNumbers(root->left, tmp); if(root->right) sumNumbers(root->right, tmp); } int sumNumbers(TreeNode* root) { if(!root) return 0; sumNumbers(root, 0); return sum; } private: int sum; };
C++
UTF-8
1,607
3.328125
3
[ "MIT" ]
permissive
#ifndef _CIRC_FIFO_HPP #define _CIRC_FIFO_HPP #include "msp430/msp_sys.hpp" template<class T, int _size, class _lock, class _unlock> class FifoBuffer { public: bool push(const T data){ if(full()) { return false; } //Put at the head of the buffer --mHead; mBuffer[mHead] = data; //When we reach 0 wrap around the buffer if(0 == mHead) mHead = _size; //Lock before checking because this could be accessed in an ISR //Note the template passes in the class with overloaded operator for functor Lock(); if(mTail == mHead) mHead = 0; UnLock(); return true; } bool pop (T& return_data){ if(empty()) { return false; } // If we were full head==0 then we set head to where tail used to be Lock(); if(full()) mHead = mTail; UnLock(); //Pop from tail --mTail; return_data = mBuffer[mTail]; //After setting head if full we can safely set the tail to wrap around if(0 == mTail) mTail = _size; return true; } void init() { mHead = _size; mTail = _size; } inline bool full() { return (mHead == 0); } inline bool empty() { return (mTail == mHead); } private: static _lock Lock; static _unlock UnLock; volatile T mBuffer[_size]; volatile uint8_t mHead; volatile uint8_t mTail; }; class FakeFifoBuffer { public: template<class T> bool push(T data){ return false; } template<class T> bool pop (T& return_data){ return false; } void init() { //do nothing } inline bool full() { //do nothing return true; } inline bool empty() { //do nothing return true; } }; #endif //_CIRC_FIFO_HPP
C#
UTF-8
1,058
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Common { [Serializable] [DataContract] public class DataStatistic { [DataMember] public string reg { get; set; } [DataMember] public int sat { get; set; } [DataMember] public int prog { get; set; } //prognozirano [DataMember] public int izm { get; set; } //izmereno [DataMember] public double dev { get; set; } //devijacija public DataStatistic(string Reg, int Sat, int Prog, int Izm) { reg = Reg; sat = Sat; prog = Prog; izm = Izm; dev = devijacija(Izm, Prog); } public DataStatistic() { } double devijacija(int izm, int prog) { return ((double)(izm - prog)/(double)prog)*100; } } }
PHP
UTF-8
1,031
2.59375
3
[ "MIT" ]
permissive
<?php namespace Blog; use Illuminate\Database\Eloquent\Model; use Cviebrock\EloquentSluggable\SluggableInterface; use Cviebrock\EloquentSluggable\SluggableTrait; use Carbon\Carbon; class Post extends Model implements SluggableInterface { use SluggableTrait; protected $sluggable = [ 'build_from' => 'title', 'save_to' => 'slug', ]; public function comments() { return $this->hasMany('Blog\Comment')->orderBy('created_at','DESC'); } public function category() { return $this->belongsTo('Blog\Category'); } public function user() { return $this->belongsTo('Blog\User'); } public function tags() { return $this->belongsToMany('Blog\Tag','tag_post'); } public function dateFormator() { $now = Carbon::now(); if($now->diffInDays($this->created_at) > 5) { return $this->created_at->toFormattedDateString(); } return $this->created_at->diffForHumans(); } }
Java
UTF-8
3,574
2.65625
3
[]
no_license
package me.itsjaar.antielytra.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class ReflectionUtils { ReflectionUtils() { } public static Object getHandle(Object obj) throws Exception { Method method = obj.getClass().getDeclaredMethod("getHandle", new Class[0]); if (!method.isAccessible()) { method.setAccessible(true); } return method.invoke(obj, new Object[0]); } public static Object invokeMethod(Object obj, String name) throws Exception { return ReflectionUtils.invokeMethod(obj, name, true); } public static Object invokeMethod(Object obj, String name, boolean declared) throws Exception { Method met = declared ? obj.getClass().getDeclaredMethod(name, new Class[0]) : obj.getClass().getMethod(name, new Class[0]); return met.invoke(obj, new Object[0]); } public static Object getNMSPlayer(Player p) throws Throwable { return ReflectionUtils.getHandle((Object)p); } public static Class<?> getNMSClass(String name) throws ClassNotFoundException { return Class.forName("net.minecraft.server." + ReflectionUtils.getPackageVersion() + "." + name); } public static Class<?> getCraftClass(String className) throws ClassNotFoundException { return Class.forName("org.bukkit.craftbukkit." + ReflectionUtils.getPackageVersion() + "." + className); } public static Field getField(Object clazz, String name) throws Exception { return ReflectionUtils.getField(clazz, name, true); } public static Field getField(Object clazz, String name, boolean declared) throws Exception { return ReflectionUtils.getField(clazz.getClass(), name, declared); } public static Field getField(Class<?> clazz, String name) throws Exception { return ReflectionUtils.getField(clazz, name, true); } public static Field getField(Class<?> clazz, String name, boolean declared) throws Exception { Field field; Field field2 = field = declared ? clazz.getDeclaredField(name) : clazz.getField(name); if (!field.isAccessible()) { field.setAccessible(true); } return field; } public static void modifyFinalField(Field field, Object target, Object newValue) throws Exception { field.setAccessible(true); ReflectionUtils.getField(Field.class, "modifiers").setInt(field, field.getModifiers() & 0xFFFFFFEF); field.set(target, newValue); } public static Object getFieldObject(Object object, Field field) throws Exception { return field.get(object); } public static void setField(Object object, String fieldName, Object fieldValue) throws Exception { ReflectionUtils.getField(object, fieldName).set(object, fieldValue); } public static void sendPacket(Player player, Object packet) { try { Object playerHandle = ReflectionUtils.getNMSPlayer(player); Object playerConnection = ReflectionUtils.getFieldObject(playerHandle, ReflectionUtils.getField(playerHandle, "playerConnection")); playerConnection.getClass().getDeclaredMethod("sendPacket", ReflectionUtils.getNMSClass("Packet")).invoke(playerConnection, packet); } catch (Throwable t) { t.printStackTrace(); } } public static String getPackageVersion() { return Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; } }
C++
UTF-8
9,192
2.796875
3
[ "MIT" ]
permissive
// // Created by nivtal9 & AVI on 27.4.2020. // #include "solver.hpp" #include <cmath> #include <langinfo.h> #include "math.h" solver::RealVariable &solver::operator*(double DV1, solver::RealVariable &RV2) { RealVariable &x= *new RealVariable(DV1*RV2.a , DV1*RV2.b, DV1*RV2.c); return x; } solver::RealVariable &solver::operator*(solver::RealVariable &RV1, double DV2) { RealVariable &x= *new RealVariable(DV2*RV1.a, DV2*RV1.b, DV2*RV1.c); return x; } solver::RealVariable &solver::operator+(solver::RealVariable &RV1, solver::RealVariable &RV2) { RealVariable &x= *new RealVariable(RV1.a + RV2.a, RV1.b + RV2.b, RV1.c + RV2.c); return x; } solver::RealVariable &solver::operator+(double DV1, solver::RealVariable &RV2) { RealVariable &x= *new RealVariable(DV1+RV2.a, RV2.b, RV2.c); return x; } solver::RealVariable &solver::operator+(solver::RealVariable &RV1, double DV2) { RealVariable &x= *new RealVariable(DV2+RV1.a, RV1.b, RV1.c); return x; } solver::RealVariable &solver::operator/(double DV1, solver::RealVariable &RV2) { RealVariable &x= *new RealVariable(DV1/RV2.a, DV1/RV2.b, DV1/RV2.c); return x; } solver::RealVariable &solver::operator/(solver::RealVariable &RV1, double DV2) { if(DV2==0){ throw std::runtime_error("cant divide by 0"); } RealVariable &x= *new RealVariable(RV1.a/DV2, RV1.b/DV2, RV1.c/DV2); return x; } solver::RealVariable &solver::operator==(solver::RealVariable &RV1, solver::RealVariable &RV2) { RealVariable &x1= *new RealVariable(RV1.a-RV2.a, RV1.b-RV2.b, RV1.c-RV2.c); return x1; } solver::RealVariable &solver::operator==(double DV1, solver::RealVariable &RV2) { RealVariable &x1= *new RealVariable(RV2.a-DV1, RV2.b, RV2.c); return x1; } solver::RealVariable &solver::operator==(solver::RealVariable &RV1, double DV2) { RealVariable &x1= *new RealVariable(RV1.a-DV2, RV1.b, RV1.c); return x1; } solver::RealVariable &solver::operator^(solver::RealVariable &RV1, double DV2) { if(DV2>2){ throw std::runtime_error("power can't be biger then 2"); } if(DV2==1){ return RV1; } if(DV2==0){ RV1.a=1; RV1.a=0; RV1.a=0; return RV1; } RealVariable& RV3=*new RealVariable(RV1.a,RV1.b,RV1.c); for (int i = 0; i < DV2; ++i) { RV3.a= RV3.a*RV1.a; } if(RV3.b>0){ RV3.c=RV3.b; RV3.b=0; } return RV3; } solver::RealVariable &solver::operator-(solver::RealVariable &RV1, solver::RealVariable &RV2) { RealVariable &x= *new RealVariable(RV1.a-RV2.a, RV1.b-RV2.b, RV1.c-RV2.c); return x; } solver::RealVariable &solver::operator-(double DV1, solver::RealVariable &RV2) { RealVariable &x= *new RealVariable(DV1-RV2.a, RV2.b, RV2.c); return x; } solver::RealVariable &solver::operator-(solver::RealVariable &RV1, double DV2) { RealVariable &x= *new RealVariable(RV1.a-DV2, RV1.b, RV1.c); return x; } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// solver::ComplexVariable &solver::operator*(solver::ComplexVariable &CV1, solver::ComplexVariable &CV2) { ComplexVariable &x=*new ComplexVariable(CV1.real*CV2.real , CV1.imag*CV2.imag ,CV1.pow_2*CV2.pow_2); return x; } solver::ComplexVariable &solver::operator*(double DV1, solver::ComplexVariable &CV2) { ComplexVariable &x=*new ComplexVariable(DV1*CV2.real , DV1*CV2.imag, DV1*CV2.pow_2); return x; } solver::ComplexVariable &solver::operator*(solver::ComplexVariable &CV1, double DV2) { ComplexVariable &x=*new ComplexVariable(DV2*CV1.real , DV2*CV1.imag,DV2*CV1.pow_2); return x; } solver::ComplexVariable &solver::operator/(solver::ComplexVariable &CV1, double DV2) { if(DV2==0) { throw std::runtime_error("divided by zero"); } else{ ComplexVariable &x = *new ComplexVariable(CV1.real / DV2, CV1.imag / DV2 , CV1.pow_2/DV2); return x; } } solver::ComplexVariable &solver::operator==(solver::ComplexVariable &CV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(CV1.real - CV2.real, CV1.imag - CV2.imag, CV1.pow_2 - CV2.pow_2); return x; } solver::ComplexVariable &solver::operator==(double DV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(DV1 - CV2.real, CV2.imag, CV2.pow_2); return x; } solver::ComplexVariable &solver::operator==(solver::ComplexVariable &CV1, double DV2) { ComplexVariable &x = *new ComplexVariable(CV1.real - DV2, CV1.imag ,CV1.pow_2); return x; } solver::ComplexVariable &solver::operator^(solver::ComplexVariable &CV1, double DV2) { if(DV2>2){ throw std::runtime_error("power can't be biger then 2"); } else if(DV2==0){ ComplexVariable &x = *new ComplexVariable(1,0,0); return x; } else if(DV2==1){ ComplexVariable &x = *new ComplexVariable(CV1.real,CV1.imag,CV1.pow_2); return x; } ComplexVariable &x = *new ComplexVariable(CV1.real*CV1.real,0,CV1.pow_2+1); return x; } solver::ComplexVariable &solver::operator-(solver::ComplexVariable &CV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(CV1.real-CV2.real, CV1.imag- CV2.imag, CV1.pow_2- CV2.pow_2); return x; } solver::ComplexVariable &solver::operator-(double DV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(DV1-CV2.real, CV2.imag, CV2.pow_2); return x; } solver::ComplexVariable &solver::operator-(solver::ComplexVariable &CV1, double DV2) { ComplexVariable &x = *new ComplexVariable(CV1.real-DV2, CV1.imag, CV1.pow_2); return x; } solver::ComplexVariable &solver::operator-(std::complex<double> CDV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(CDV1 -CV2.real, CV2.imag,CV2.pow_2); return x; } solver::ComplexVariable &solver::operator-(solver::ComplexVariable &CV1, std::complex<double> CDV2) { ComplexVariable &x = *new ComplexVariable(CV1.real-CDV2, CV1.imag,CV1.pow_2); return x; } solver::ComplexVariable &solver::operator+(solver::ComplexVariable &CV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(CV1.real+CV2.real, CV1.imag+ CV2.imag,CV1.pow_2+ CV2.pow_2); return x; } solver::ComplexVariable &solver::operator+(double DV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(CV2.real+DV1, CV2.imag, CV2.pow_2); return x; } solver::ComplexVariable &solver::operator+(solver::ComplexVariable &CV1, double DV2) { ComplexVariable &x = *new ComplexVariable(CV1.real+DV2, CV1.imag, CV1.pow_2); return x; } solver::ComplexVariable &solver::operator+(std::complex<double> CDV1, solver::ComplexVariable &CV2) { ComplexVariable &x = *new ComplexVariable(CDV1+CV2.real, CV2.imag,CV2.pow_2); return x; } solver::ComplexVariable &solver::operator+(solver::ComplexVariable &CV1, std::complex<double> CDV2) { ComplexVariable &x = *new ComplexVariable(CDV2+CV1.real, CV1.imag, CV1.pow_2); return x; } double solver::solve(solver::RealVariable &RV) { double a = RV.get_a(); double b = RV.get_b(); double c=RV.get_c(); double results =0; if(a*b!=0 && c==0){ results = (a/b)*(-1); return results; } if(a==0 && b!=0 && c==0){ return 0; } if(a==0 && b==0 && c!=0){ return 0; } if(a*c!=0){ if(pow(b,2)-4*a*c<0){ throw std::invalid_argument(" There is no real solution"); } if(a!=0 && b==0 && c!=0){ a=-a/c; a=sqrt(a); c=sqrt(c); return results=a; } results = (-b+(sqrt(pow(b,2)-4*a*c)))/2*c; return results; } if(a==0 && b!=0 && c!=0){ return 0; } throw std::invalid_argument(" There is no real solution"); } std::complex<double> solver::solve(solver::ComplexVariable &CV1){ std:: complex<double> x1=0; float realPart=0; float imaginaryPart =0; if(CV1.get_pow()==0){ if (CV1.get_imag()==0 ) throw std::invalid_argument("Roots are complex and different.\n"); std::complex<double> res = ((CV1.get_real()))/CV1.get_imag(); res *=-1; return res; } std::complex<double> discriminant = CV1.get_imag() * CV1.get_imag() - 4 * CV1.get_pow() * CV1.get_real(); if (discriminant.real() > 0) { sqrt(discriminant); x1 = (-CV1.get_imag() + sqrt(discriminant)) / (2*CV1.get_pow()); return x1; } else { std::complex<double> s =std::complex<double>(-1) * CV1.get_imag(); return s + sqrt(discriminant)/(CV1.get_pow()*2); } }
Markdown
UTF-8
2,811
2.96875
3
[]
no_license
# pyABCDobj ## * rev 2 2014-03-10 * a object oriented framework to calculate the propagation of gaussian beams * provides 2 Classes: * **GaussianBeam** - to calculate the beam parameters * **LensSystem** - to calculate the propagation using the ABCD formalism ## class GaussianBeam ## * **initialization** beam = **GaussianBeam( wavelength, mode, arg )** * wavelength is the wavelength in nm * mode is either 'q' or 'rw', which means you can define your beam by the complex beam parameters or a pair of radius of curvature and waist (both given in meters) * examples: * b1 = GaussianBeam( 633e-9, 'q', 0 + .45j ) * b2 = GaussianBeam( 1064-9, 'rw', [30, 2e-3]) * from the input parameters, the following physical values are calculated automatically: * **GaussianBeam.q** - the complex parameter q * **GaussianBeam.r** - the radius of curvature (phase) * **GaussianBeam.w** - the beam waist * **GaussianBeam.divergence** - the divergence in the far field * furthermore, the beam wavelength is stored **GaussianBeam.wavelength** * for convenience, all parameters can be printed out by **GaussianBeam.print\_params()** --- ## class LensSystem ## ### public methods * **\_\_init\_\_(wavelength)** * initializes an empty lens system (wavelength in nm) * **add_beam(mode, params)**: * adds a gaussian bean at z=0 * **mode** is either 'rw' or 'q' * **add_element( Type, zpos, params )**: * adds an element to the system. * **Type** can be * 'lens' (params = [focal length]) * 'curvedmirror' (params = [Radius of curvature]) * **zpos** is the z position of the element * **params** is a list of params (e.g. [f] for a simple lens) * **calc_beam(zend,points)**: * calculates the beam up to **zend** with **points** as the number or points * returns : [ w,r,d,z,q ], where * **w** is the list of waists(z) * **r** is the list of beam curvatures * **d** is the list of divergences * **z** is the list of z values * **q** is the list of q values * **calc\_propmatrix\_until\_z(z_end)** * calculates the propagation matrix up to z * **clone()** * returns a copy of the lens system (without beams) * **print_positions()**: * print positions of elements ### private methods * **\_\_get\_list\_order** get the order of the elements in the lens system * **\_\_matrix\_lens( f )** returns the ABCD matrix of a lens with focal length _f_ * **\_\_matrix\_free\_space( L, n)** returns the ABCD matrix of a free space propagation (length _L_, refractive index _n_) * **\_\_matrix\_curved\_mirror(self, R)** returns the ABCD matrix of a curved mirror with radius _R_ * **\_\_matrix\_multiplication( A, B )** perform matrix multiplication of _A_ and _B_
Java
UTF-8
1,977
2.796875
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Sascha Haeberling * * 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. */ package com.s13g.aoc.aoc2016; import com.s13g.aoc.Puzzle; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * http://adventofcode.com/2016/day/20 */ public class Puzzle20 implements Puzzle { @Override public Solution solve(String input) { List<Range> ranges = new ArrayList<>(); for (String entry : input.split("\\r?\\n")) { String[] parts = entry.split("-"); ranges.add(new Range(Long.parseLong(parts[0]), Long.parseLong(parts[1]))); } Collections.sort(ranges); long numUnblocked = 0; long previousMax = -1; for (Range r : ranges) { if (r.from > previousMax) { numUnblocked += (r.from - previousMax - 1); } previousMax = Math.max(previousMax, r.to); } numUnblocked += (4294967295L - previousMax); long lowestToTest = 0; for (Range r : ranges) { if (r.from <= lowestToTest) { lowestToTest = r.to + 1; } } return new Solution(lowestToTest, numUnblocked); } static class Range implements Comparable<Range> { final long from; final long to; Range(long from, long to) { this.from = from; this.to = to; } @Override public int compareTo(Range o) { return from - o.from > 0 ? 1 : -1; } @Override public String toString() { return from + " - " + to; } } }
JavaScript
UTF-8
1,363
3.78125
4
[]
no_license
var myHeading = document.querySelector('h1'); // Grab reference to the heading and store it in a variable // This is very similar to what we did using CSS selectors. // When wanting to do something to an element, you first need to select it. myHeading.textContent = 'Hello, world!'; // Set the value of the myHeading variable's textContent property // (which represents the content of the heading) to "Hello world!". var myImage = document.querySelector('img'); myImage.onclick = function() { var mySrc = myImage.getAttribute('src'); if (mySrc === 'images/honey-muffin-2.jpg') { myImage.setAttribute('src', 'images/black-capped-conure.png'); } if (mySrc === 'images/black-capped-conure.png') { myImage.setAttribute('src', 'images/honey-muffin-2.jpg'); } } var myButton = document.querySelector('button'); var myHeading = document.querySelector('h1'); myButton.onclick = function() { setUserName(); } if (!localStorage.getItem('name')) { setUserName(); } else { myHeading.innerHTML = 'Welcome back, ' + localStorage.getItem('name'); } function setUserName() { var myName = prompt('Please enter your name: '); // prompt() brings up a dialog box, a bit like alert() localStorage.setItem('name', myName); // localStorage() stores data in the browser and later retrieve it myHeading.innerHTML = 'Welcome to our page, ' + myName; }
JavaScript
UTF-8
109
2.796875
3
[]
no_license
//undefined //declared but not defined is undefined // var a; console.log(a); var b = 10; console.log(b);
Python
UTF-8
303
2.640625
3
[]
no_license
import re import unicodedata from text_processors.text_processor import TextProcessor class WhitespaceCharactersProcessor(TextProcessor): def process(self, text): pattern = r'^\s*|\s\s*' text = re.sub(pattern, ' ', text).strip() return TextProcessor.process(self, text)
C++
UTF-8
658
2.8125
3
[]
no_license
//#include<iostream> #include<iostream> #include <stdlib.h> #include"TagParser.hpp" using std::cout; void TagParser::ParseNextLine(string line) { Bracket b(line); if(b.IsOpening()) // opening tag { if(tags.size()>0) { if( tags.back().HasBeenClosed() ) tags.push_back( Tag(b) ); else tags.back().InsertSubTag(b); } else tags.push_back( Tag(b) ); } else // closing tag { assert( tags.size()>0 ); assert( !tags.back().HasBeenClosed() ); tags.back().InsertSubTag(b); } }
Python
UTF-8
1,984
4.0625
4
[]
no_license
# class Person: # def __init__(self,name,age,weight,height): # self.name = name # self.age = age # self.weight = weight # self.height = height # self.__score = 70 # #将某个方法伪装成属性,这个方法需要有返回值 # # @property # # def bmi(self): # # return self.weight/(self.height*self.height) # #属性一般有三种访问方式:获取,修改,删除 # # #当对象.score 被放在print中的时候,会自动调用property下面那个方法 # @property # def score(self): # return self.__score + 30 # #一定先有取值的方法,才能写设置值或者删除值的方法 # #在@后面写刚才取值的那个方法的方法名,后面写。setter # #接下来,定义一个方法,方法名也要和取值的方法同名 # #这个方法需要接收一个参数,用来给私有属性赋值 # #如果是赋值操作,自动调用setter后面的方法 # @score.setter # def score(self,sc): # if sc < 0: # print("输入有误") # else: # self.__score = sc # @score.deleter # def score(self): # del self.__score # #总结,如果一个私有属性加上了property,那么他当前就变为可读的 # #再加上setter之后,他就变成了可读可写 # p1 = Person("shang",32,80,1.9) # print(p1.score) # p1.score = 123 # print(p1.score) # #当通过。去访问这个伪装过的属性时,可以获取到方法的返回值 # # print(p1.bmi) # # bmi = p1.bmi() # # print(bmi) import time class P(): def __init__(self): self.__score = 60 @property def score(self): return self.__score + 30 @score.setter def score(self,new_score): self.__score = new_score @score.deleter def score(self): del self.__score print('已删除') p = P() print(p.score) p.score = 70 print(p.score) time.sleep(1) del p.score
PHP
UTF-8
8,035
2.5625
3
[]
no_license
<?php include ('inc/init.inc.php'); if (isset($_GET['id'])){ $requete = "SELECT a.id_vehicule, marque, modele, couleur, immatriculation, prenom, nom FROM association_vehicule_conducteur as a INNER JOIN conducteur as c ON a.id_conducteur=c.id_conducteur INNER JOIN vehicule as v ON a.id_vehicule=v.id_vehicule WHERE a.id_conducteur = :id"; $req = $pdo -> prepare($requete); $req -> bindParam(':id', $_GET['id'], PDO::PARAM_INT); $req -> execute(); } elseif (isset($_GET['sans-conducteur'])){ $requete = "SELECT * FROM vehicule WHERE id_vehicule NOT IN (SELECT id_vehicule FROM association_vehicule_conducteur)"; $req = $pdo -> query ($requete); } else{ $requete = "SELECT * FROM vehicule"; $req = $pdo -> query ($requete); } $vehicules = $req -> fetchAll(PDO::FETCH_ASSOC); $nb = $req -> rowCount(); // initilistion de message d'erreur $erreurmarque = ''; $erreurmodele = ''; $erreurcouleur = ''; $erreurimmatriculation = ''; // traitement d'une demande de suppresion ou de modification if (isset($_GET['action']) && isset($_GET['id'])) { // cas d'une suppresion if ($_GET['action'] == "suppr"){ $req = $pdo -> prepare ("DELETE FROM `vehicule` WHERE id_vehicule = :id"); $req -> bindParam(':id', $_GET['id'], PDO::PARAM_INT); $req -> execute(); header('location: vehicules.php'); } // cas de la modification d'un conducteur if ($_GET['action'] == "modif"){ $req = $pdo -> prepare ("SELECT * FROM vehicule WHERE id_vehicule = :id"); $req -> bindParam(':id', $_GET['id'], PDO::PARAM_INT); $req -> execute(); $vehicule = $req -> fetch(PDO::FETCH_ASSOC); extract($vehicule); } } // traitement du formulaire if (!empty($_POST)) { // on éclate le $_POST en tableau qui permet d'accéder directement aux champs par des variables extract($_POST); // cas d'un ajout if (empty($id_vehicule)){ if (!empty($marque) && !empty($modele) && !empty($couleur) && !empty($immatriculation)){ $req = $pdo -> prepare ("INSERT INTO vehicule(marque, modele, couleur, immatriculation) VALUES (:marque, :modele, :couleur, :immatriculation)"); $req -> bindParam(':marque', $marque, PDO::PARAM_STR); $req -> bindParam(':modele', $modele, PDO::PARAM_STR); $req -> bindParam(':couleur', $couleur, PDO::PARAM_STR); $req -> bindParam(':immatriculation', $immatriculation, PDO::PARAM_STR); $req -> execute(); header('location: vehicules.php'); } else { $erreurmarque = (empty($erreurmarque)) ? 'Indiquez une marque' : null; $erreurmodele = (empty($erreurmodele)) ? 'Indiquez un modèle' : null; $erreurcouleur = (empty($erreurcouleur)) ? 'Indiquez une couleur' : null; $erreurimmatriculation = (empty($erreurimmatriculation)) ? 'Indiquez une immatriculation' : null; } } // cas d'une modification else { if (!empty($marque) && !empty($modele) && !empty($couleur) && !empty($immatriculation)){ $req = $pdo -> prepare ("UPDATE vehicule SET marque = :marque, modele = :modele, couleur = :couleur, immatriculation = :immatriculation WHERE id_vehicule = :id"); $req -> bindParam(':id', $id_vehicule, PDO::PARAM_INT); $req -> bindParam(':marque', $marque, PDO::PARAM_STR); $req -> bindParam(':modele', $modele, PDO::PARAM_STR); $req -> bindParam(':couleur', $couleur, PDO::PARAM_STR); $req -> bindParam(':immatriculation', $immatriculation, PDO::PARAM_STR); $req -> execute(); header('location: vehicules.php'); } else { $erreurmarque = (empty($erreurmarque)) ? 'Indiquez une marque' : null; $erreurmodele = (empty($erreurmodele)) ? 'Indiquez un modèle' : null; $erreurcouleur = (empty($erreurcouleur)) ? 'Indiquez une couleur' : null; $erreurimmatriculation = (empty($erreurimmatriculation)) ? 'Indiquez une immatriculation' : null; } } } include ('inc/head.inc.php'); ?> <main class="container"> <a href="?tous=1"> <button class="btn btn-info">Tous</button> </a> <a href="?sans-conducteur=1"> <button class="btn btn-info">sans conducteur</button> </a> <h1 class="text-center">Liste des <?= $nb ?> véhicules <?= (isset($_GET['sans-conducteur']))? " sans conducteur":((isset($_GET['id']))?" conduits par " . $vehicules[0]['prenom'] . ' ' . $vehicules[0]['nom']:""); ?></h1> <!-- Affichage de la Liste des conducteurs --> <table class="table table-striped"> <tr> <th>id_véhicule</th> <th>Marque</th> <th>Modèle</th> <th>Couleur</th> <th>Immatriculation</th> <th class="text-center">Modification</th> <th class="text-center">Suppression</th> </tr> <?php foreach ($vehicules as $vehicule) : ?> <tr> <td><?= $vehicule['id_vehicule'] ?></td> <td><?= $vehicule['marque'] ?></td> <td><?= $vehicule['modele'] ?></td> <td><?= $vehicule['couleur'] ?></td> <td><?= $vehicule['immatriculation'] ?></td> <td class="text-center"> <a href="?action=modif&id=<?= $vehicule['id_vehicule'] ?>"> <button type="button" class="btn btn-info"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> </button> </a> </td> <td class="text-center"> <a href="?action=suppr&id=<?= $vehicule['id_vehicule'] ?>"> <button class="btn btn-danger"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> </button> </a> </td> </tr> <?php endforeach; ?> </table> <!-- formulaire de saisie pour un ajout --> <form method="post"> <input type="hidden" name="id_vehicule" value="<?= isset($id_vehicule)?$id_vehicule:0 ?>"> <div class="form-group"> <?php if (!empty($erreurmarque)) : ?> <p class="alert alert-danger"><?= $erreurmarque ?></p> <?php endif; ?> <label for="marque">Marque :</label> <input type="text" name="marque" class="form-control" id="marque" value="<?= (isset($marque))?$marque:'' ?>"> </div> <div class="form-group"> <?php if (!empty($erreurmodele)) : ?> <p class="alert alert-danger"><?= $erreurmodele ?></p> <?php endif; ?> <label for="modele">Modèle :</label> <input type="text" name="modele" class="form-control" id="prenom" value="<?= (isset($modele))?$modele:'' ?>"> </div> <div class="form-group"> <?php if (!empty($erreurcouleur)) : ?> <p class="alert alert-danger"><?= $erreurcouleur ?></p> <?php endif; ?> <label for="couleur">Couleur :</label> <input type="text" name="couleur" class="form-control" id="couleur" value="<?= (isset($couleur))?$couleur:'' ?>"> </div> <div class="form-group"> <?php if (!empty($erreurimmatriculation)) : ?> <p class="alert alert-danger"><?= $erreurimmatriculation ?></p> <?php endif; ?> <label for="nom">Immatriculation :</label> <input type="text" name="immatriculation" class="form-control" id="immatriculation" value="<?= (isset($immatriculation))?$immatriculation:'' ?>"> </div> <?php $action=(isset($id_vehicule)?"Modifier le":"Ajouter un ") ?> <button type="submit" class="btn btn-submit"><?= $action ?>véhicule</button> </form> </main> <?php include ('inc/footer.inc.php'); ?>
Markdown
UTF-8
3,875
2.578125
3
[]
no_license
FXZ === A recreation of sfxr. Wish me luck! All credit for the synth goes to [Dr. Petter](http://www.drpetter.se/project_sfxr.html), I just ported a port and wrote down a binary format :) Goals ----- - [ ] An embeddable synthesizer in < 1kb js (minified and gzipped) - [x] A binary format for saving and loading effects in 100 bytes - [ ] Synth implementations in common languages (C, C#, Java, Lua, etc.) FXZ Binary Format Specification ------------------------------- FXZ data is 100 bytes long. All multi-byte numeric types are little endian. | Offset | Size | Type | Field | Range | |--------|------|---------|------------------|--------| | 0 | 3 | ascii | Magic Number | 'fxz' | | 3 | 1 | uint8 | version | 1 | | 4 | 1 | uint8 | wave shape | 0-3 | | 5 | 3 | - | unused | 0 | | 8 | 4 | float32 | attack time | [ 0,1] | | 12 | 4 | float32 | sustain time | [ 0,1] | | 16 | 4 | float32 | sustain punch | [ 0,1] | | 20 | 4 | float32 | decay time | [ 0,1] | | 24 | 4 | float32 | start frequency | [ 0,1] | | 28 | 4 | float32 | frequency cutoff | [ 0,1] | | 32 | 4 | float32 | frequency slide | [-1,1] | | 36 | 4 | float32 | delta slide | [-1,1] | | 40 | 4 | float32 | vibrato depth | [ 0,1] | | 44 | 4 | float32 | vibrato speed | [ 0,1] | | 48 | 4 | float32 | arp amount | [-1,1] | | 52 | 4 | float32 | arp change speed | [ 0,1] | | 56 | 4 | float32 | Square duty | [ 0,1] | | 60 | 4 | float32 | Duty sweep | [-1,1] | | 64 | 4 | float32 | Repeat speed | [ 0,1] | | 68 | 4 | float32 | Flanger offset | [-1,1] | | 72 | 4 | float32 | Flanger sweep | [-1,1] | | 76 | 4 | float32 | LPF cutoff | [ 0,1] | | 80 | 4 | float32 | LPF cutoff sweep | [-1,1] | | 84 | 4 | float32 | LPF resonance | [ 0,1] | | 88 | 4 | float32 | HPF cutoff | [ 0,1] | | 92 | 4 | float32 | HPF cutoff sweep | [-1,1] | | 96 | 4 | float32 | Volume | [ 0,1] | Recommended MIME type `application/fxz`. Recommended file extension `.fxz`. FXX Binary Format Specification ------------------------------- FXX is an FXZ Pack. It can contain up to uint32max entries. The size of the pack is `8 + 116 * numberOfEntries` bytes. It adds 16 byte identifiers to each entry so they can be named. If you want them nameless to save those bytes you can glob up fxz data, just smash them all together, I don't think it warrants a formal specification. All multi-byte numeric types are little endian. | Offset | Size | Type | Field | Range | |--------|------|---------|------------------|--------------| | 0 | 3 | ascii | Magic Number | 'fxx' | | 3 | 1 | uint8 | version | 1 | | 4 | 4 | uint32 | # of entries | 0-4294967295 | | * | 16 | ascii | fxz entry name | | | *+16 | 100 | fxz | fxz entry data | valid fxz | `* = 8 + n * 116` where `n = [0, 1, ..., numberOfEntries-1]` Recommended MIME type `application/fxx`. Recommended file extension `.fxx`. Status ------ Currently in beta. I want to review the synth and see if I can adjust the params to reduce the amount that create empty or "bad" sounds. Juice the most information out of those bits! I also want to investigate using the full float32 range or expanding the recommended range and see what impact that will have, but I need to learn more about how the synth operates to be sure. This could also involve humanizing the units somewhat but it will require learning a lot more about the internals of the synthesis. Glossary -------- - freq: frequency - LPF: Low pass filter - vol: Volume
Python
UTF-8
3,145
2.515625
3
[]
no_license
import numpy as np import cv2 import utils from skimage.measure import compare_ssim as ssim from detection_attempts.att_1.detect_on_video import (get_capture_and_calibration_image_video2, Calibrator, Detector, CvNamedWindow, detect_and_show) """ - fast mean ellipse color - all frame -> label for each ellipse - bounding rect -> mask -> mean - n points in m level ellipses - n random points??? - ssim (structured similarity index) - key points matching??? """ def get_detector(): video, calibration_image = get_capture_and_calibration_image_video2() calibrator = Calibrator.calibrate(calibration_image, 2) if not calibrator.calibrated: print('System was not calibrated.') return detector = Detector(calibrator) return detector wnd = CvNamedWindow('detection', cv2.WINDOW_NORMAL) image = video.read_at_pos(820) cv2.imshow('111', image) detect_and_show(wnd, detector, image, video.frame_pos() - 1) def calc_ssi(im1, im2): ind1 = ssim(im1, im2, multichannel=True, data_range=im2.max() - im2.min()) ind2 = ssim(im1, im2, multichannel=True) return ind1, ind2 def test_ssim(): video, calibration_image = get_capture_and_calibration_image_video2() frame = video.read_at_pos(286) true_ellipse_image1 = frame[551: 551 + 67, 418: 418 + 69] true_ellipse_image2 = video.read_at_pos(820)[269: 269 + 67, 659: 659 + 69] false_ellipse_image = frame[501: 501 + 67, 745: 745 + 69] # false_ellipse_image = cv2.resize(false_ellipse_image, (true_ellipse_image.shape[1], true_ellipse_image.shape[0])) detector = get_detector() # ind1, ind2 = calc_ssi(true_ellipse_image1, false_ellipse_image) # print('ssind', ind1, ind2) # ind1, ind2 = calc_ssi(true_ellipse_image1, true_ellipse_image2) # print('ssind', ind1, ind2) # ind1, ind2 = calc_ssi(true_ellipse_image2, false_ellipse_image) # print('ssind', ind1, ind2) # print('-------------------') # ind1, ind2 = calc_ssi(true_ellipse_image1, true_ellipse_image1) # print('ssind', ind1, ind2) # ind1, ind2 = calc_ssi(true_ellipse_image2, true_ellipse_image2) # print('ssind', ind1, ind2) # ind1, ind2 = calc_ssi(false_ellipse_image, false_ellipse_image) # print('ssind', ind1, ind2) i = 1000 print(utils.timeit(lambda: calc_ssi(true_ellipse_image1, false_ellipse_image), i)) print(utils.timeit(lambda: calc_ssi(true_ellipse_image1, true_ellipse_image2), i)) print(utils.timeit(lambda: calc_ssi(true_ellipse_image2, false_ellipse_image), i)) return true_ellipse_wnd1 = CvNamedWindow('true_ellipse1', cv2.WINDOW_NORMAL) detect_and_show(true_ellipse_wnd1, detector, true_ellipse_image1.copy(), None, wait=False) false_ellipse_wnd = CvNamedWindow('false_ellipse', cv2.WINDOW_NORMAL) detect_and_show(false_ellipse_wnd, detector, false_ellipse_image.copy(), None, wait=True) # ssim_const = ssim(img1, img2, multichannel=True, data_range=img2.max() - img2.min()) # print(ssim_const) def main(): test_ssim() def main__(): pass main()
TypeScript
UTF-8
6,041
3.21875
3
[ "MIT" ]
permissive
import { expect } from "chai"; import Lazy from "../../src"; import { asyncGenerator } from "../helpers"; describe("ƒ join()", function () { it("should join numbers with comma and space", function () { const result = Lazy.from([1, 2, 3]).join(", "); expect(result).to.be.equal("1, 2, 3"); }); it("should join booleans with comma and space", function () { const result = Lazy.from([true, false, true]).join(", "); expect(result).to.be.equal("true, false, true"); }); it("should join strings with comma and space", function () { const result = Lazy.from(["value1", "value 2", "value, 3"]).join(", "); expect(result).to.be.equal("value1, value 2, value, 3"); }); it("should join numbers with comma and space from objects", function () { const result = Lazy.from([{ n: true }, { n: false }, { n: true }, { n: false }]).join(", ", (obj) => obj.n); expect(result).to.be.equal("true, false, true, false"); }); it("should join booleans with comma and space from objects", function () { const result = Lazy.from([{ n: 2 }, { n: 4 }, { n: 1 }, { n: 3 }]).join(", ", (obj) => obj.n); expect(result).to.be.equal("2, 4, 1, 3"); }); it("should join strings with comma and space from objects", function () { const result = Lazy.from([{ n: "value1" }, { n: "value 2" }, { n: "value, 3" }]).join(", ", (obj) => obj.n); expect(result).to.be.equal("value1, value 2, value, 3"); }); it("should join specific members of an object", function () { class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } const people = [ new Person("Josh", 25), new Person("Michael", 36), new Person("Jonathan", 30), new Person("Bob", 50), ]; const result = Lazy.from(people).join(", ", person => person.name); expect(result).to.be.equal("Josh, Michael, Jonathan, Bob"); }); it("should join all returned strings from 'toString' method", function () { class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } toString(): string { return `Name: ${this.name}, Age: ${this.age}`; } } const people = [ new Person("Josh", 25), new Person("Michael", 36), new Person("Jonathan", 30), ]; const result = Lazy.from(people).join("; "); expect(result).to.be.equal("Name: Josh, Age: 25; Name: Michael, Age: 36; Name: Jonathan, Age: 30"); }); }); describe("ƒ joinAsync()", function () { it("should join numbers with comma and space", async function () { const result = await Lazy.fromAsync(asyncGenerator([1, 2, 3])).join(", "); expect(result).to.be.equal("1, 2, 3"); }); it("should join booleans with comma and space", async function () { const result = await Lazy.fromAsync(asyncGenerator([true, false, true])).join(", "); expect(result).to.be.equal("true, false, true"); }); it("should join strings with comma and space", async function () { const result = await Lazy.fromAsync(asyncGenerator(["value1", "value 2", "value, 3"])).join(", "); expect(result).to.be.equal("value1, value 2, value, 3"); }); it("should join numbers with comma and space from objects", async function () { const result = await Lazy.fromAsync(asyncGenerator([{ n: true }, { n: false }, { n: true }, { n: false }])).join(", ", (obj) => obj.n); expect(result).to.be.equal("true, false, true, false"); }); it("should join booleans with comma and space from objects", async function () { const result = await Lazy.fromAsync(asyncGenerator([{ n: 2 }, { n: 4 }, { n: 1 }, { n: 3 }])).join(", ", (obj) => obj.n); expect(result).to.be.equal("2, 4, 1, 3"); }); it("should join strings with comma and space from objects", async function () { const result = await Lazy.fromAsync(asyncGenerator([{ n: "value1" }, { n: "value 2" }, { n: "value, 3" }])).join(", ", (obj) => obj.n); expect(result).to.be.equal("value1, value 2, value, 3"); }); it("should join specific members of an object", async function () { class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } const people = [ new Person("Josh", 25), new Person("Michael", 36), new Person("Jonathan", 30), new Person("Bob", 50), ]; const result = await Lazy.fromAsync(asyncGenerator(people)).join(", ", person => person.name); expect(result).to.be.equal("Josh, Michael, Jonathan, Bob"); }); it("should join all returned strings from 'toString' method", async function () { class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } toString(): string { return `Name: ${this.name}, Age: ${this.age}`; } } const people = [ new Person("Josh", 25), new Person("Michael", 36), new Person("Jonathan", 30), ]; const result = await Lazy.fromAsync(asyncGenerator(people)).join("; "); expect(result).to.be.equal("Name: Josh, Age: 25; Name: Michael, Age: 36; Name: Jonathan, Age: 30"); }); });
C#
UTF-8
1,699
3.59375
4
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace _10._Car_Salesman { public class Car { public string Model { get; private set; } public Engine Engine { get; private set; } public int Weight { get; set; } public string Color { get; set; } public Car(string model, Engine engine, int weight, string color) { this.Model = model; this.Engine = engine; this.Weight = weight; this.Color = color; } public Car(string model, Engine engine, int weight) : this(model, engine, weight, "n/a") { } public Car(string model, Engine engine, string color) : this(model, engine, -1, color) { } public Car(string model, Engine engine) : this(model, engine, -1, "n/a") { } public override string ToString() { var car = new StringBuilder(); car.AppendLine($"{Model}:"); car.AppendLine($" {Engine.Model}:"); car.AppendLine($" Power: {Engine.Power}"); if (Engine.Displacement > -1) { car.AppendLine($" Displacement: {Engine.Displacement}"); } else { car.AppendLine($" Displacement: n/a"); } car.AppendLine($" Efficiency: {Engine.Efficiency}"); if (Weight > -1) { car.AppendLine($" Weight: {Weight}"); } else { car.AppendLine($" Weight: n/a"); } car.Append($" Color: {Color}"); return car.ToString(); } } }
Python
UTF-8
103
3.671875
4
[]
no_license
fahrenheit = float(input("enter your fahrenheit:")) celsius = (fahrenheit - 32) * 5 / 9 print(celsius)
Java
UTF-8
2,202
2.4375
2
[]
no_license
package com.mobilemarket.sessionBeans; import com.mobilemarket.beans.model.Osoba; import java.util.List; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author NemanjaTrnjak */ @Stateless public class RegistrationBean implements RegistrationBeanLocal { @PersistenceContext(unitName = "MobileMarketPU") private EntityManager em; /* * Metoda koja registruje novog korisnika u bazu */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @Override public boolean register(String userName, String password, String email, String name, String surname, String mobile) { Query query = em.createNamedQuery("Osoba.findByKorisnickoIme"); query.setParameter("korisnickoIme", userName); try { Osoba o = (Osoba) query.getSingleResult(); if (o != null) { return false; } } catch (NoResultException nre) { System.out.println("Osoba ne postoji"); } catch (Exception e) { e.printStackTrace(); return false; } Osoba noviKorisnik = new Osoba(); noviKorisnik.setKorisnickoIme(userName); noviKorisnik.setLozinka(password); noviKorisnik.setEmail(email); noviKorisnik.setIme(name); noviKorisnik.setPrezime(surname); noviKorisnik.setMobilniTelefon(mobile); noviKorisnik.setPrivilegija("korisnik"); em.persist(noviKorisnik); return true; } @Override public List<Osoba> getAllOsobe() { Query query = em.createNamedQuery("Osoba.findAll"); List<Osoba> result = (List<Osoba>) query.getResultList(); return result; } }
Python
UTF-8
14,500
2.84375
3
[]
no_license
import numpy as np from numpy.polynomial.chebyshev import chebval2d import scipy.ndimage.filters from . import psf from . import utils # Okay, here we start the A&L basis functions... # Update: it looks like the actual code in the stack uses chebyshev1 polynomials! # Note these are essentially the same but with different scale factors. # Here beta is a rescale factor but this is NOT what it is really used for. # Can be used to rescale so that sigGauss[1] = sqrt(sigmaPsf_I^2 - sigmaPsf_T^2) def chebGauss2d(x, y, m=None, s=None, ord=[0, 0], beta=1., verbose=False): if m is None: m = [0., 0.] if s is None: s = [1., 1.] # cov = [[s[0], 0], [0, s[1]]] coefLen = np.max(ord)+1 coef0 = np.zeros(coefLen) coef0[ord[0]] = 1 coef1 = np.zeros(coefLen) coef1[ord[1]] = 1 if verbose: print s, beta, ord, coef0, coef1 ga = psf.singleGaussian2d(x, y, 0, 0, s[0]/beta, s[1]/beta) ch = chebval2d(x, y, c=np.outer(coef0, coef1)) return ch * ga # use same parameters as from the stack. # TBD: is a degGauss of 2 mean it goes up to order 2 (i.e. $x^2$)? Or # is it 2 orders so it only goes up to linear ($x$)? Probably the # former, so that's what we'll use. # Parameters from stack # betaGauss is actually the scale factor for sigGauss -> sigGauss[0] = sigGauss[1]/betaGauss and # sigGauss[2] = sigGauss[1] * betaGauss. Looks like here, betaGauss is 2 (see sigGauss below) but # we'll just set it to 1. # Note should rescale sigGauss so sigGauss[1] = sqrt(sigma_I^2 - sigma_T^2) # betaGauss = 1 # in the Becker et al. paper betaGauss is 1 but PSF is more like 2 pixels? # sigGauss = [0.75, 1.5, 3.0] # degGauss = [4, 2, 2] # # Parameters from and Becker et al. (2012) # degGauss = [6, 4, 2] def getALChebGaussBases(x0, y0, sigGauss=None, degGauss=None, betaGauss=1, verbose=True): sigGauss = [0.75, 1.5, 3.0] if sigGauss is None else sigGauss #degGauss = [4, 2, 2] if degGauss is None else degGauss degGauss = [6, 4, 2] if degGauss is None else degGauss # Old, too many bases: #basis = [chebGauss2d(x0, y0, grid, m=[0,0], s=[sig0,sig1], ord=[deg0,deg1], beta=betaGauss, verbose=False) for i0,sig0 in enumerate(sigGauss) for i1,sig1 in enumerate(sigGauss) for deg0 in range(degGauss[i0]) for deg1 in range(degGauss[i1])] def get_valid_inds(Nmax): tmp = np.add.outer(range(Nmax+1), range(Nmax+1)) return np.where(tmp <= Nmax) inds = [get_valid_inds(i) for i in degGauss] if verbose: for i in inds: print i basis = [chebGauss2d(x0, y0, m=[0,0], s=[sig,sig], ord=[inds[i][0][ind], inds[i][1][ind]], beta=betaGauss, verbose=verbose) for i,sig in enumerate(sigGauss) for ind in range(len(inds[i][0]))] return basis # Convolve im1 (template) with the basis functions, and make these the *new* bases. # Input 'basis' is the output of getALChebGaussBases(). def makeImageBases(im1, basis): #basis2 = [scipy.signal.fftconvolve(im1, b, mode='same') for b in basis] basis2 = [scipy.ndimage.filters.convolve(im1, b, mode='constant', cval=np.nan) for b in basis] return basis2 def makeSpatialBases(im1, basis, basis2, spatialKernelOrder=2, spatialBackgroundOrder=2, verbose=False): # Then make the spatially modified basis by simply multiplying the constant # basis (basis2 from makeImageBases()) by a polynomial along the image coordinate. # Note that since we *are* including i=0, this new basis *does include* basis2 and # thus can replace it. # Here beta is a rescale factor but this is NOT what it is really used for. # Can be used to rescale so that sigGauss[1] = sqrt(sigmaPsf_I^2 - sigmaPsf_T^2) # Apparently the stack uses a spatial kernel order of 2? (2nd-order?) #spatialKernelOrder = 2 # 0 # Same for background order. #spatialBackgroundOrder = 2 def cheb2d(x, y, ord=[0,0], verbose=False): coefLen = np.max(ord)+1 coef0 = np.zeros(coefLen) coef0[ord[0]] = 1 coef1 = np.zeros(coefLen) coef1[ord[1]] = 1 if verbose: print ord, coef0, coef1 ch = chebval2d(x, y, c=np.outer(coef0, coef1)) return ch def get_valid_inds(Nmax): tmp = np.add.outer(range(Nmax+1), range(Nmax+1)) return np.where(tmp <= Nmax) spatialBasis = bgBasis = None spatialInds = get_valid_inds(spatialKernelOrder) if verbose: print spatialInds #xim = np.arange(np.int(-np.floor(im1.shape[0]/2.)), np.int(np.floor(im1.shape[0]/2))) #yim = np.arange(np.int(-np.floor(im1.shape[1]/2.)), np.int(np.floor(im1.shape[1]/2))) x0im, y0im = utils.getImageGrid(im1) # np.meshgrid(xim, yim) # Note the ordering of the loop is important! Make the basis2 the last one so the first set of values # that are returned are all of the original (basis2) unmodified bases. # Store "spatialBasis" which is the kernel basis and the spatial basis separated so we can recompute the # final kernel at the end. Include in index 2 the "original" kernel basis as well. if spatialKernelOrder > 0: spatialBasis = [[basis2[bi], cheb2d(x0im, y0im, ord=[spatialInds[0][i], spatialInds[1][i]], verbose=False), basis[bi]] for i in range(1,len(spatialInds[0])) for bi in range(len(basis2))] # basis2m = [b * cheb2d(x0im, y0im, ord=[spatialInds[0][i], spatialInds[1][i]], verbose=False) for # i in range(1,len(spatialInds[0])) for b in basis2] spatialBgInds = get_valid_inds(spatialBackgroundOrder) if verbose: print spatialBgInds # Then make the spatial background part if spatialBackgroundOrder > 0: bgBasis = [cheb2d(x0im, y0im, ord=[spatialBgInds[0][i], spatialBgInds[1][i]], verbose=False) for i in range(len(spatialBgInds[0]))] return spatialBasis, bgBasis # Collect the bases into a single matrix # ITMT, let's make sure all the bases are on a reasonable scale. def collectAllBases(basis2, spatialBasis, bgBasis, verbose=False): basis2a = np.vstack([b.flatten() for b in basis2]).T constKernelIndices = np.arange(0, basis2a.shape[1]) if verbose: print constKernelIndices nonConstKernelIndices = None if spatialBasis is not None: b1 = np.vstack([(b[0]*b[1]).flatten() for b in spatialBasis]).T nonConstKernelIndices = np.arange(basis2a.shape[1], basis2a.shape[1]+b1.shape[1]) basis2a = np.hstack([basis2a, b1]) if verbose: print nonConstKernelIndices bgIndices = None if bgBasis is not None: b1 = np.vstack([b.flatten() for b in bgBasis]).T bgIndices = np.arange(basis2a.shape[1], basis2a.shape[1]+b1.shape[1]) basis2a = np.hstack([basis2a, b1]) if verbose: print bgIndices # Rescale the bases so that the "standard" A&L linear fit will work (i.e. when squared, not too large!) basisOffset = 0. # basis2a.mean(0) + 0.1 basisScale = basis2a.std(0) + 0.1 # avoid division by zero basis2a = (basis2a-basisOffset)/(basisScale) return basis2a, (constKernelIndices, nonConstKernelIndices, bgIndices), (basisOffset, basisScale) # Do the linear fit to compute the matching kernel. This is NOT the # same fit as is done by standard A&L but gives the same results. This # will not work for very large images. See below. The resulting fit is # the matched template. def doTheLinearFitOLD(basis2a, im2, verbose=False): pars, resid, _, _ = np.linalg.lstsq(basis2a, im2.flatten()) fit = (pars * basis2a).sum(1).reshape(im2.shape) if verbose: print resid, np.sum((im2 - fit.reshape(im2.shape))**2) return pars, fit, resid # Create the $b_i$ and $M_{ij}$ from the A&L (1998) and Becker (2012) # papers. This was done wrong in the previous version of notebook 3 # (and above), although it gives identical results. def doTheLinearFitAL(basis2a, im2, verbose=False): b = (basis2a.T * im2.flatten()).sum(1) M = np.dot(basis2a.T, basis2a) pars, resid, _, _ = np.linalg.lstsq(M, b) fit = (pars * basis2a).sum(1).reshape(im2.shape) if verbose: print resid, np.sum((im2 - fit.reshape(im2.shape))**2) return pars, fit, resid # Also generate the matching kernel from the resulting pars. # Look at the resulting matching kernel by multiplying the fitted # parameters times the original basis funcs. and test that actually # convolving it with the template gives us a good subtraction. # Here, we'll just compute the spatial part at x,y=0,0 # (i.e. x,y=256,256 in img coords) def getMatchingKernelAL(pars, basis, constKernelIndices, nonConstKernelIndices, spatialBasis, basisScale, basisOffset=0, xcen=256, ycen=256, verbose=False): kbasis1 = np.vstack([b.flatten() for b in basis]).T kbasis1 = (kbasis1 - basisOffset) / basisScale[constKernelIndices] kfit1 = (pars[constKernelIndices] * kbasis1).sum(1).reshape(basis[0].shape) kbasis2 = np.vstack([(b[2]*b[1][xcen, ycen]).flatten() for b in spatialBasis]).T kbasis2 = (kbasis2 - basisOffset) / basisScale[nonConstKernelIndices] kfit2 = (pars[nonConstKernelIndices] * kbasis2).sum(1).reshape(basis[0].shape) kfit = kfit1 + kfit2 if verbose: print kfit1.sum(), kfit2.sum(), kfit.sum() # this is necessary if the source changes a lot - prevent the kernel from incorporating that change in flux kfit /= kfit.sum() return kfit # Here, im2 is science, im1 is template def performAlardLupton(im1, im2, sigGauss=None, degGauss=None, betaGauss=1, kernelSize=25, spatialKernelOrder=2, spatialBackgroundOrder=2, doALZCcorrection=True, preConvKernel=None, sig1=None, sig2=None, im2Psf=None, verbose=False): x = np.arange(-kernelSize+1, kernelSize, 1) y = x.copy() x0, y0 = np.meshgrid(x, y) im2_orig = im2 if preConvKernel is not None: im2 = scipy.ndimage.filters.convolve(im2, preConvKernel, mode='constant', cval=np.nan) basis = getALChebGaussBases(x0, y0, sigGauss=sigGauss, degGauss=degGauss, betaGauss=betaGauss, verbose=verbose) basis2 = makeImageBases(im1, basis) spatialBasis, bgBasis = makeSpatialBases(im1, basis, basis2, verbose=verbose) basis2a, (constKernelIndices, nonConstKernelIndices, bgIndices), (basisOffset, basisScale) \ = collectAllBases(basis2, spatialBasis, bgBasis) del bgBasis del basis2 pars, fit, resid = doTheLinearFitAL(basis2a, im2) del basis2a xcen = np.int(np.floor(im1.shape[0]/2.)) ycen = np.int(np.floor(im1.shape[1]/2.)) kfit = getMatchingKernelAL(pars, basis, constKernelIndices, nonConstKernelIndices, spatialBasis, basisScale, basisOffset, xcen=xcen, ycen=ycen, verbose=verbose) del basis del spatialBasis diffim = im2 - fit psf = im2Psf if doALZCcorrection: if sig1 is None: _, sig1, _, _ = computeClippedImageStats(im1) if sig2 is None: _, sig2, _, _ = computeClippedImageStats(im2) pck = computeDecorrelationKernel(kfit, sig1**2, sig2**2, preConvKernel=preConvKernel) pci = scipy.ndimage.filters.convolve(diffim, pck, mode='constant', cval=np.nan) if im2Psf is not None: psf = computeCorrectedDiffimPsf(kfit, im2Psf, svar=sig1**2, tvar=sig2**2) diffim = pci return diffim, psf, kfit # Compute the "ALZC" post-conv. kernel from kfit # Note unlike previous notebooks, here because the PSF is varying, # we'll just use `fit2` rather than `im2-conv_im1` as the diffim, # since `fit2` already incorporates the spatially varying PSF. # sig1 and sig2 are the same as those input to makeFakeImages(). # def computeCorrectionKernelALZC(kappa, sig1=0.2, sig2=0.2): # def kernel_ft2(kernel): # FFT = fft2(kernel) # return FFT # def post_conv_kernel_ft2(kernel, sig1=1., sig2=1.): # kft = kernel_ft2(kernel) # return np.sqrt((sig1**2 + sig2**2) / (sig1**2 + sig2**2 * kft**2)) # def post_conv_kernel2(kernel, sig1=1., sig2=1.): # kft = post_conv_kernel_ft2(kernel, sig1, sig2) # out = ifft2(kft) # return out # pck = post_conv_kernel2(kappa, sig1=sig2, sig2=sig1) # pck = np.fft.ifftshift(pck.real) # #print np.unravel_index(np.argmax(pck), pck.shape) # # I think we actually need to "reverse" the PSF, as in the ZOGY (and Kaiser) papers... let's try it. # # This is the same as taking the complex conjugate in Fourier space before FFT-ing back to real space. # if False: # # I still think we need to flip it in one axis (TBD: figure this out!) # pck = pck[::-1, :] # return pck # Compute the (corrected) diffim's new PSF # post_conv_psf = phi_1(k) * sym.sqrt((sig1**2 + sig2**2) / (sig1**2 + sig2**2 * kappa_ft(k)**2)) # we'll parameterize phi_1(k) as a gaussian with sigma "psfsig1". # im2_psf is the the psf of im2 # def computeCorrectedDiffimPsfALZC(kappa, im2_psf, sig1=0.2, sig2=0.2): # def post_conv_psf_ft2(psf, kernel, sig1=1., sig2=1.): # # Pad psf or kernel symmetrically to make them the same size! # if psf.shape[0] < kernel.shape[0]: # while psf.shape[0] < kernel.shape[0]: # psf = np.pad(psf, (1, 1), mode='constant') # elif psf.shape[0] > kernel.shape[0]: # while psf.shape[0] > kernel.shape[0]: # kernel = np.pad(kernel, (1, 1), mode='constant') # psf_ft = fft2(psf) # kft = fft2(kernel) # out = psf_ft * np.sqrt((sig1**2 + sig2**2) / (sig1**2 + sig2**2 * kft**2)) # return out # def post_conv_psf(psf, kernel, sig1=1., sig2=1.): # kft = post_conv_psf_ft2(psf, kernel, sig1, sig2) # out = ifft2(kft) # return out # im2_psf_small = im2_psf # # First compute the science image's (im2's) psf, subset on -16:15 coords # if im2_psf.shape[0] > 50: # x0im, y0im = getImageGrid(im2_psf) # x = np.arange(-16, 16, 1) # y = x.copy() # x0, y0 = np.meshgrid(x, y) # im2_psf_small = im2_psf[(x0im.max()+x.min()+1):(x0im.max()-x.min()+1), # (y0im.max()+y.min()+1):(y0im.max()-y.min()+1)] # pcf = post_conv_psf(psf=im2_psf_small, kernel=kappa, sig1=sig2, sig2=sig1) # pcf = pcf.real / pcf.real.sum() # return pcf
JavaScript
UTF-8
1,878
3.8125
4
[]
no_license
//----------- DOM INTRODUCTION ------------ const boxes = document.getElementsByTagName('div'); boxes[1].innerHTML = "<p>DOM Introduction</p>"; boxes[2].innerHTML = "<button>Submit</button>"; boxes[3].innerHTML = "<h3>Good Bye</h3>"; // ---------------------------------------- const box1 = document.getElementById('box1'); box1.innerHTML = '<u> Hello 2 </u>'; //----------------------------------------- // ---- Creating Nodes for JavaScript ----- const OrangeBox = document.createElement('div'); // ---- Creating text for nodes ------ const OrangeContent = document.createTextNode("New Block"); // ---- Adding text content to created node ------ OrangeBox.appendChild(OrangeContent); // ---- performing attributes for new node ------ OrangeBox.setAttribute('class', 'box orange'); OrangeBox.setAttribute('id', 'box5'); // ------ Adding new element to DOM ------- const container = document.getElementById('container'); container.appendChild(OrangeBox); // ----- Creating another block (node in red) ------ const RedBox = document.createElement('div'); const RedContent = document.createTextNode("New Block in Red"); RedBox.appendChild(RedContent); RedBox.setAttribute('class', 'box red'); RedBox.setAttribute('id', 'box6'); container.appendChild(RedBox); // ---- Adding new node and setting in position ----- const GreenBox = document.createElement('div'); const GreentContent = document.createTextNode('New Block in Green'); GreenBox.appendChild(GreentContent); GreenBox.id = "box6"; // This is another way to set attributes in JS GreenBox.className = "box green"; // ---- Finding out the parent element ----- const parentSection = box1.parentNode; parentSection.insertBefore(GreenBox, boxes[1]); // ---- Replacing existint blocks ---- parentSection.replaceChild(RedBox,boxes[3]); // ---- Removing block (node) ------ parentSection.removeChild(box[4]);
Java
UTF-8
522
3.25
3
[]
no_license
package easy.array; public class Easy977 { public int[] sortedSquares(int[] A) { int[] r = new int[A.length]; int start = 0; int end = A.length-1; for(int i=r.length-1; i>=0; i--) { boolean endBigger = Math.abs(A[end]) > Math.abs(A[start]); if (endBigger) { r[i] = A[end] * A[end]; end--; } else { r[i] = A[start] * A[start]; start++; } } return r; } }
Java
UTF-8
748
2.375
2
[]
no_license
package web; import bean.Address; import dao.AddressDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/DeleteAddressServlet") public class DeleteAddressServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int addressNo = Integer.parseInt(request.getParameter("addressNo")); try { new AddressDao().deleteaddress(addressNo); } catch (Exception e) { e.printStackTrace(); } } }
TypeScript
UTF-8
5,974
2.53125
3
[]
no_license
import * as http from 'http-status-codes'; import * as logic from './logicHandlers'; import { RouteDefinition, StoreInterface, DataStoreType } from 'src/types'; export const get: { [key: string]: RouteDefinition } = { getConfigs: { route: '/configs', callback: (req, res) => { console.log('getting configs'); logic.getConfigs((configs: StoreInterface[]) => { if (configs) res.send({ configs }); else res.status(http.INTERNAL_SERVER_ERROR).send({ message: 'Could not retrieve configs' }); }); } }, getConfig: { route: '/configs/:name', callback: (req, res) => logic.getConfig( req.params.name, (config: StoreInterface) => { if (config) res.send({ config }); else res.status(http.NOT_FOUND).send({ message: `Your config, ${name} was not found` }); }, error => console.error(`Failed to retrieve ${name}: ${error}`) ) }, getConfigType: { route: '/configs/:name/type', callback: (req, res) => logic.getConfigType(req.params.name, (type: DataStoreType) => type ? res.send({ [req.params.name]: type }) : res .status(http.NOT_FOUND) .send({ message: `A type could not be found for config: ${name}` }) ) }, getConfigVersions: { route: '/configs/:name/versions', callback: (req, res) => logic.getConfigVersions(req.params.name, (store: Map<string, any>[]) => store ? res.send({ [req.params.name]: [...store] }) : res.status(http.NOT_FOUND).send({ message: `The config could not be found: ${name}` }) ) }, getConfigStoreAtVersion: { route: '/configs/:name/versions/:version', callback: (req, res) => logic.getConfigVersions(req.params.name, (store: Map<string, any>[]) => store ? res.send({ [req.params.name]: [store[req.params.version]] }) : res.status(http.NOT_FOUND).send({ message: `The config could not be found: ${name}` }) ) }, getConfigValue: { route: '/configs/:name/key/:key', callback: (req, res) => logic.getConfigVersions(req.params.name, (store: {}[]) => { console.log('store :', store); store ? res.send({ [req.params.name]: { [req.params.key]: store[store.length - 1][req.params.key] } }) : res.status(http.NOT_FOUND).send({ message: `The config could not be found: ${name}` }); }) }, getConfigValueAtVersion: { route: '/configs/:name/versions/:version/:key', callback: (req, res) => logic.getConfigVersions(req.params.name, (store: {}[]) => store ? res.send({ [req.params.name]: { [req.params.key]: store[req.params.version][req.params.key] } }) : res.status(http.NOT_FOUND).send({ message: `The config could not be found: ${name}` }) ) } }; export const post: { [key: string]: RouteDefinition } = { createConfig: { route: '/configs/', callback: (req, res) => logic.createConfig( req.body.name, req.body.type, req.body.values, config => { if (config) res.send({ config }); else res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Failed to create config ${req.body.name}` }); }, error => { res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Failed to create config ${req.body.name} due to ${error}` }); } ) }, setConfigValues: { route: '/configs/:name/values', callback: (req, res) => logic.setConfigValues( req.params.name, req.body.type, req.body.values, (config: StoreInterface) => { if (config) res.send({ config }); else res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Could not update ${req.params.name}!` }); }, (error: Error) => res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Could not update ${req.params.name} due to ${error}` }) ) }, deleteConfigValue: { route: '/configs/:name/delete', callback: (req, res) => logic.deleteConfigValue( req.params.name, req.body.key, (config: StoreInterface) => { if (config) res.send({ config }); else res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Failed to delete ${req.body.key} from ${req.body.name}` }); }, (error: Error) => { res.status(http.INTERNAL_SERVER_ERROR).send({ message: `Failed to delete ${req.body.key} from ${req.body.name} due to ${error}` }); } ) }, versionConfig: { route: '/configs/:name/version', callback: (req, res) => logic.versionConfig( req.body.name, req.body.type, req.body.values, (config: StoreInterface) => { if (config) res.send({ config }); else res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Could not version the config: ${req.body.name}` }); }, error => { res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Encountered error during versioning: ${error}` }); } ) } }; export const methods = { get, post, delete: { deleteConfig: { route: '/configs/:name', callback: (req, res) => logic.getConfig(req.params.name, config => logic.deleteConfig( req.params.name, () => res.send({ [req.params.name]: config }), () => res .status(http.INTERNAL_SERVER_ERROR) .send({ message: `Failed to delete ${req.params.name}` }) ) ) } } };
C++
UTF-8
2,914
3.171875
3
[]
no_license
/* 차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. (한 배추의 상하좌우 네 방향에 다른 배추가 위치한 경우에 서로 인접해있다고 간주한다) 한나가 배추를 재배하는 땅은 고르지 못해서 배추를 군데군데 심어놓았다. 배추들이 모여있는 곳에는 배추흰지렁이가 한 마리만 있으면 되므로 서로 인접해있는 배추들이 몇 군데에 퍼져있는지 조사하면 총 몇 마리의 지렁이가 필요한지 알 수 있다. 예를 들어 배추밭이 아래와 같이 구성되어 있으면 최소 5마리의 배추흰지렁이가 필요하다. (0은 배추가 심어져 있지 않은 땅이고, 1은 배추가 심어져 있는 땅을 나타낸다.) 문제가 굉장히 이상한 문제 문제가 이상한게 아니라 지문이 이상해서 도저히 틀린게 없는데 이유를 몰랐던 문제 알고리즘 자체는 단순하다 주어진 배열안에서 그래프의 개수만 찾으면 되는 그래프의 기초적인 문제 그러나 지문에 가로 세로 정의가 이상하다 가로 3 세로 2가 주어진다면 누구라도 [0,0] [0,1] [0,2] [1,0] [1,1] [1,2] 이렇게 생각할텐데 문제는 [0,0] [0,1] [1,0] [1,1] [2,0] [2,1] 이렇게 풀어야 한다... 내가 잘못이해한건지 지문이 이상한건지 ~~ */ #include <cstdio> #include <iostream> #include <cstring> using namespace std; int map[51][51] = { 0, }; int dirx[4] = { 0,0,1,-1 }; int diry[4] = { 1,-1,0,0 }; int T, M, N, K; void Organic(int x, int y) { if (x < 0 || y < 0 || x >= M || y >= N) // 주어진 배열 범위 초과하면 리턴 return; map[x][y] = 0; // 0으로 다녀간 표시 for (int i = 0; i < 4; i++) { int nx = x + dirx[i]; int ny = y + diry[i]; if (map[nx][ny]) // 배추 있으면 Organic(nx, ny); } } int main(void) { int x, y; scanf("%d", &T); while (T--) { int worm = 0; scanf("%d %d %d", &M, &N, &K); for (int i = 0; i < K; i++) { scanf("%d %d", &x, &y); map[x][y] = 1; } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (map[i][j]) { Organic(i, j); worm++; } } } printf("%d\n", worm); memset(map, 0, sizeof(map)); // 각각 테스트케이스를 위한 초기화 } return 0; }
Java
UTF-8
60
1.539063
2
[ "Apache-2.0" ]
permissive
package o; public abstract interface cg extends cd.iF {}
C++
GB18030
3,255
2.671875
3
[]
no_license
#pragma once #include <string> #include <sys/uio.h> #include <functional> namespace vDB { /* * db_storeĺϷ־ * INSERT * REPLACE滻 * STORE滻 */ enum DB_STORE_FLAG{STORE_MIN_FLAG, DB_INSERT, DB_REPLACE, DB_STORE, STORE_MAX_FLAG}; const int kIndex_min = 6; //indexСΪ6keysepstartseplength\n const int kIndex_max = 1024; //index󳤶ȣԼ const int kData_min = 2; //dataСΪ2һֽڼһз const int kData_max = 1024; //data󳤶ȣԼ using std::string; typedef unsigned int DBHASH; //hashֵ /* * һkey->valueݿ⣬ݿ򿪺ļ.idx.datļ * .idx洢keyصϢ.dat洢 * keyvalueΪstring * ע⣬lseekԶͬһ˵ЩӿڶDz */ class DB { public: explicit DB(); DB(const DB&) = delete; virtual ~DB(); /* * 򿪻ߴݿ⣬openϵͳһ * ɹTrueʧܷFalse */ virtual bool db_open(const string&, int, ...); /* * ݿķ */ virtual void db_close(); /* * keyȡӦvalue򷵻ؿstring */ virtual string db_fetch(const string&); /* * ɾָkeyļ¼ * ɹtrueʧܷfalse */ virtual bool db_delete(const string&); /* * Ѽ¼洢ݿ * һkeyڶvalueDzı־ * ɹ0󷵻-1ڶָDB_INSERT򷵻1 */ virtual int db_store(const string&, const string&, int); private: string pathname_; //ݿ· //һζдindex¼ʱǰһڵͺһڵƫ off_t pre_offset_, next_offset_; //db_storeͬflagӦӳ亯 std::function<int(const string&, const string&, bool, off_t)> store_function_map[STORE_MAX_FLAG]; struct Handle { int fd; //ļ off_t offset; //һζд¼ʱƫ int length; //һζдļ¼ char *buffer; //д¼ʱõĻ }index_, data_; //idxļdatļ void _db_bind_function(); bool _db_allocate(); void _db_free(); DBHASH _db_hash(const string&); bool _db_find(const string&, off_t); off_t _db_read_ptr(off_t); off_t _db_read_idx(off_t); char *_db_read_data(); bool _db_do_delete(); bool _db_write_data(const char*, off_t, int); bool _db_lock_and_write_data(const char*, off_t, int); bool _db_write_idx(const char*, off_t, int, off_t); bool _db_lock_and_write_idx(const char*, off_t, int, off_t); bool _db_pre_write_idx(const char*, off_t, struct iovec*, char*); bool _db_do_write_idx(off_t, int, struct iovec*); bool _db_write_ptr(off_t, off_t); int _db_store_insert(const string&, const string&, bool, off_t); int _db_store_replace(const string&, const string&, bool, off_t); int _db_store_ins_or_rep(const string&, const string&, bool, off_t); bool _db_find_and_delete_free(int, int); }; }
Java
UTF-8
9,809
2.09375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package View; import Controller.PujaController; import Model.Puja; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author Dell */ public class VentanaHistorialPujas extends javax.swing.JFrame { /** * Creates new form VentanaHistorialPujas */ private double idSubasta; private DefaultTableModel modelo; private PujaController pujaController; private ArrayList<Puja> listaPujas; private int selectedRow; public VentanaHistorialPujas(double idSubasta) throws SQLException { initComponents(); System.out.println(idSubasta); modelo = new DefaultTableModel(); modelo = (DefaultTableModel) jTableHPujas.getModel(); this.idSubasta = idSubasta; pujaController = new PujaController(); selectedRow = -1; llenarJTable(); } private VentanaHistorialPujas() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelListado = new javax.swing.JPanel(); btnHistorialComprador = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTableHPujas = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanelListado.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Listado de pujas de la subasta", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); btnHistorialComprador.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N btnHistorialComprador.setText("Ver historial del comprador"); btnHistorialComprador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHistorialCompradorActionPerformed(evt); } }); jTableHPujas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Usuario", "Precio", "Fecha" } ) { boolean[] canEdit = new boolean [] { false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTableHPujas.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTableHPujasMouseClicked(evt); } }); jScrollPane1.setViewportView(jTableHPujas); javax.swing.GroupLayout jPanelListadoLayout = new javax.swing.GroupLayout(jPanelListado); jPanelListado.setLayout(jPanelListadoLayout); jPanelListadoLayout.setHorizontalGroup( jPanelListadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelListadoLayout.createSequentialGroup() .addContainerGap(29, Short.MAX_VALUE) .addGroup(jPanelListadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 741, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanelListadoLayout.createSequentialGroup() .addGap(196, 196, 196) .addComponent(btnHistorialComprador))) .addGap(361, 361, 361)) ); jPanelListadoLayout.setVerticalGroup( jPanelListadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelListadoLayout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnHistorialComprador) .addContainerGap(45, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jPanelListado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(jPanelListado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(42, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnHistorialCompradorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHistorialCompradorActionPerformed if (!(selectedRow==-1)){ try { double idComprador = listaPujas.get(selectedRow).getCompradorId(); VentanaHistorialComprador ventanaComprador = new VentanaHistorialComprador(idComprador); ventanaComprador.setVisible(true); } catch (SQLException ex) { Logger.getLogger(VentanaHistorialPujas.class.getName()).log(Level.SEVERE, null, ex); } } else{ JOptionPane.showMessageDialog(null, "Seleccione una puja para ver su comprador"); } }//GEN-LAST:event_btnHistorialCompradorActionPerformed private void jTableHPujasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableHPujasMouseClicked int posicion = jTableHPujas.getSelectedRow(); selectedRow = posicion; }//GEN-LAST:event_jTableHPujasMouseClicked private void llenarJTable(){ vaciarJTable(); listaPujas = pujaController.listarPujas(idSubasta); if(!listaPujas.isEmpty()){ for (int i = 0; i < listaPujas.size(); i++){ modelo.addRow(new Object[]{listaPujas.get(i).getNombreComprador(),listaPujas.get(i).getPrecio(), listaPujas.get(i).getFecha()}); jTableHPujas.setModel(modelo); } } else{ JOptionPane.showMessageDialog(null, "No hay pujas para esta subasta"); } } private void vaciarJTable(){ DefaultTableModel temp = (DefaultTableModel) jTableHPujas.getModel(); temp.setRowCount(0); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VentanaHistorialPujas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VentanaHistorialPujas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VentanaHistorialPujas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaHistorialPujas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new VentanaHistorialPujas().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnHistorialComprador; private javax.swing.JPanel jPanelListado; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTableHPujas; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
1,334
3.65625
4
[]
no_license
**题目描述** Given *n* non-negative integers *a1*, *a2*, ..., *an* , where each represents a point at coordinate (*i*, *ai*). *n* vertical lines are drawn such that the two endpoints of line *i* is at (*i*, *ai*) and (*i*, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. **Note:** You may not slant the container and *n* is at least 2. ![img](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg) The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. **Example1** ``` Input: [1,8,6,2,5,4,8,3,7] Output: 49 ``` **难度系数** Medium 解法:左右各一个指针,每次移动高度小的方向,同时保留最大值 ```c++ class Solution { public: int maxArea(vector<int>& height) { int start, end; int ret = 0; start = 0; end = height.size() - 1; while (start < end) { ret = max(ret, min(height[start], height[end])*(end - start)); if (height[start] < height[end]) { start++; } else end--; } return ret; } }; ```
JavaScript
UTF-8
12,668
2.609375
3
[]
no_license
//step 1: function to instantiate the Leaflet map function createMap(){ // var southWest = L.latLng(44.893141, -93.327398), // northEast = L.latLng(45.013166, -93.118221), // bounds = L.latLngBounds(southWest, northEast); //create the map var map = L.map('map', { center: [0, 0], zoom: 2, minZoom: 1, // maxBounds: bounds, }); // function overlay () { // var bridge = L.marker([44.980530, -93.254743]).bindPopup('Stone Arch Bridge'), // midtown = L.marker([44.950503, -93.269043]).bindPopup('Midtown Greenway'); // var landmarks = L.layerGroup ([bridge, midtown]); // var overlayMap = { // "Landmarks": landmarks // }; // L.control.layers(overlayMap).addTo(map); // }; //add Stamen base tilelayer L.tileLayer('https://a.tiles.mapbox.com/v3/mapbox.world-bright/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://maps.stamen.com/toner-hybrid/#12/37.7707/-122.3783</a>' }).addTo(map); //call getData function getData(map); }; function processData(data) { //empty array var attributes = []; //properties of the first feature in the dataset var properties = data.features[0].properties; //push each attribute name into attributes array for (var attribute in properties) { //only take attributes with bike count values if (attribute.indexOf("Im") > -1) { attributes.push(attribute); }; }; return attributes; }; //get data function to retrieve geojson function getData(map, attributes){ //load the geoJSON data $.ajax("data/test.json", { dataType: "json", success: function(response){ var attributes = processData (response); //call functions to create proportional symbols and sequencer // createPropSymbols (response, map, attributes); // createSequenceControls (map, attributes); // createLegend (map, attributes); } }); }; // //calculate radius of each proportional symbol // function calcPropRadius (attValue){ // //scale factor to adjust symbol size // var scaleFactor = 1.5; // //area based on attribute value and scale factor // var area = attValue * scaleFactor; // //radius calculated based on area // var radius = Math.sqrt(area/Math.PI); // return radius; // }; // //sequence controls // function createSequenceControls(map, attributes) { // var SequenceControl = L.Control.extend({ // options: { // position: 'bottomleft' // }, // onAdd: function (map) { // // create the control container div with a particular class name // var container = L.DomUtil.create('div', 'sequence-control-container'); // //kill any mouse event listeners on the map // $(container).on('mousedown dblclick', function(e){ // L.DomEvent.stopPropagation(e); // }); // // ... initialize other DOM elements, add listeners, etc. // $(container).append('<input class="range-slider" type="range">'); // // //reverse and skip buttons // $(container).append('<button class="skip" id="reverse"> Reverse </button>'); // $(container).append('<button class="skip" id="forward"> Skip </button>'); // return container; // } // }); // map.addControl(new SequenceControl()); // // //implement slider // //set slider attributes // $('.range-slider').attr({ // max: 7, // min: 0, // value: 0, // step: 1 // }); // // replace reverse and skip with images instead// // $('#reverse').html('<img src="img/left.png"> <id="left">'); // $('#forward').html('<img src="img/right.png"> <id="right">'); // //click listener // $('.skip').click(function(){ // //sequence // //get the old index value // var index = $('.range-slider').val(); // // increment or decrement depending on button clicked // if ($(this).attr('id')== 'forward'){ // index++ // //step 7: if past the last attribute, wrap aroudn to the first attribute // index = index > 7 ? 0 : index; // } else if ($(this).attr('id') == 'reverse'){ // index --; // //if past the first attribute, wrap around to last // index = index < 0 ? 7 : index; // }; // //update slider // $('.range-slider').val(index); // //pass new attribute to update symbols // updatePropSymbols (map, attributes [index]); // }); // //input listener for slider // $('.range-slider').on('input', function(){ // //get new index value // var index = $(this).val(); // //pass new attribute to update symbols // updatePropSymbols (map, attributes[index]); // }); // }; // //create legend // //PSEUDO-CODE FOR ATTRIBUTE LEGEND // // 1. Add an `<svg>` element to the legend container // // 2. Add a `<circle>` element for each of three attribute values: max, mean, and min // // 3. Assign each `<circle>` element a center and radius based on the dataset max, mean, and min values of the current attribute // // 4. Create legend text to label each circle // // 5. Update circle attributes and legend text when the data attribute is changed by the user // function createLegend (map, attributes) { // var LegendControl = L.Control.extend ({ // options: { // position: 'bottomright' // }, // onAdd: function (map) { // //create the control container w/ particular class name // var container = L.DomUtil.create ('div', 'legend-control-container'); // //script for temporal legend // // //add city to legend content string // // var legendContent = "<p><b>Bicyclists in:&nbsp;&nbsp;</b>" + year + ":&nbsp;&nbsp;</b>" + props[attribute] + "</p>"; // //use jquerty to append to div // $(container).append('<div id="temporal-legend">') // //Step 1: start attribute legend svg string // var svg = '<svg id="attribute-legend" width="160px" height="60px">'; // //array of circle names to base loop on // var circles = { // max: 20, // mean: 40, // min: 60, // }; // //Step 2: loop to add each circle and text to svg string // for (var circle in circles){ // //circle string // svg += '<circle class="legend-circle" id="' + circle + // '" fill="#4EB0AC" fill-opacity="0.8" stroke="#F1F2F2" cx="80"/>'; // //text string // svg += '<text id="' + circle + '-text" x="130" y=" ' + circles[circle] + ' "></text>'; // }; // //close svg string // svg += "</svg>"; // //add attribute legend svg to container // $(container).append(svg); // return container; // } // }); // map.addControl (new LegendControl()); // updateLegend(map, attributes[0]); // }; // //Calculate the max, mean, and min values for a given attribute // function getCircleValues(map, attribute){ // //start with min at highest possible and max at lowest possible number // var min = Infinity, // max = -Infinity; // map.eachLayer(function(layer){ // //get the attribute value // if (layer.feature){ // var attributeValue = Number(layer.feature.properties[attribute]); // //test for min // if (attributeValue < min){ // min = attributeValue; // }; // //test for max // if (attributeValue > max){ // max = attributeValue; // }; // }; // }); // //set mean // var mean = (max + min) / 2; // //return values as an object // return { // max: max, // mean: mean, // min: min // }; // }; // //Update the legend with new attribute // function updateLegend(map, attribute){ // //create content for legend // var year = attribute.split("_")[1]; // var content = "Immigrants in " + year; // //replace legend content // $('#temporal-legend').html(content); // //get the max, mean, and min values as an object // var circleValues = getCircleValues(map, attribute); // for (var key in circleValues) { // //get the radius // var radius = calcPropRadius (circleValues[key]); // //assign cy and r attributes // $('#' + key).attr({ // cy: 84 - radius, // r: radius // }); // //Step 4: add legend text // $('#'+key+'-text').text(Math.round(circleValues[key]*100)/100); // }; // updateLegend(map, attributes[1]); // }; // // update prop symbols // function updatePropSymbols (map, attribute) { // map.eachLayer (function(layer){ // if (layer.feature && layer.feature.properties[attribute]){ // //update the layer style and popup // //access feature properties // var props = layer.feature.properties; // //update feature's radius based on new attribute values // var radius = calcPropRadius (props[attribute]); // layer.setRadius(radius); // //add city to popup content string // var popupContent = "<p><b>Location:&nbsp;&nbsp;</b>" + props.Location + "</p>"; // //add formatted attribute to panel content string // var year = attribute.split ("_") [1]; // popupContent += "<p><b> Immigrants in " + year + ":&nbsp;&nbsp;</b>" + props[attribute] + "</p>"; // //replace the layer popup // layer.bindPopup(popupContent, { // offset: new L.Point (0, -radius) // }); // }; // }); // // allow legend circles to change when attribute changes // updateLegend(map, attribute); // }; // function pointToLayer (feature, latlng, attributes) { // var attribute = attributes [0]; // //check console // console.log(attribute); // //create circle marker options // var options = { // radius: 8, // fillColor: "#4fb0ad", // color: "#fff", // weight: 2, // opacity: 1, // fillOpacity: 0.7 // }; // //determine value for selected attribute // var attValue = Number(feature.properties[attribute]); // //Step 6: Give circle markers radius based on attribute value // options.radius = calcPropRadius (attValue); // //create circle marker layer // var layer = L.circleMarker (latlng, options); // //build popup content string // var popupContent = "<p><b>Location:&nbsp;&nbsp;</b>" + feature.properties.Location + "</p><p><b>" + "</b></p>"; // //add formatted attribute to popup content string // var year = attribute.split ("_") [1]; // popupContent += "<p><b>Immigrants in " + year + ":&nbsp;&nbsp;</b>" + feature.properties [attribute] + "</p>"; // //bind popup to circle marker // layer.bindPopup (popupContent, { // offset: new L.Point (0, -options.radius) // }); // // event listeners to open popup on hover // layer.on({ // mouseover: function () { // this.openPopup(); // }, // mouseout: function () { // this.closePopup (); // } // }); // // return circle marker to L.geoJson pointToLayer option; // return layer; // }; // function createPropSymbols (data, map, attributes) { // L.geoJson(data, { // pointToLayer: function (feature, latlng) { // return pointToLayer(feature, latlng, attributes); // } // }).addTo(map); // }; $(document).ready(createMap);
PHP
UTF-8
4,713
2.515625
3
[ "Apache-2.0" ]
permissive
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/10/28 0028 * Time: 上午 11:18 */ namespace gyo2o\dao; use gyo2o\model\Common; use think\Db; use think\Model; class RiderDao extends Model { // 表名 protected $name = 'rider'; // 自动写入时间戳字段 protected $autoWriteTimestamp = 'int'; // 定义时间戳字段名 protected $createTime = 'createtime'; protected $updateTime = false; // 追加属性 protected $append = [ 'sex_text', 'type_text', 'jointime_text', 'leavetime_text', 'stationmaster_text', 'workstatus_text', ]; protected $readonly = ['starttime','endtime']; public function getSexlist() { return ['男' => __('男'),'女' => __('女')]; } public function getTypelist() { return ['试用期员工' => __('试用期员工'),'正式员工' => __('正式员工'),'已离职' => __('已离职')]; } public function getStationmasterlist() { return ['否' => __('否'),'是' => __('是')]; } public function getWorkstatuslist() { return ['工作' => __('工作'),'休假' => __('休假')]; } public function getSexTextAttr($value, $data) { $value = $value ? $value : $data['sex']; $list = $this->getSexList(); return isset($list[$value]) ? $list[$value] : ''; } public function getTypeTextAttr($value, $data) { $value = $value ? $value : $data['type']; $list = $this->getTypeList(); return isset($list[$value]) ? $list[$value] : ''; } public function getJointimeTextAttr($value, $data) { $value = $value ? $value : $data['jointime']; return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value; } public function getStationmasterTextAttr($value, $data) { $value = $value ? $value : $data['stationmaster']; $list = $this->getStationmasterList(); return isset($list[$value]) ? $list[$value] : ''; } public function getLeavetimeTextAttr($value, $data) { $value = $value ? $value : $data['leavetime']; if(empty($value)){ return '-'; } return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value; } public function getWorkstatusTextAttr($value, $data) { $value = $value ? $value : $data['workstatus']; $list = $this->getWorkstatusList(); return isset($list[$value]) ? $list[$value] : ''; } protected function setJointimeAttr($value) { return $value && !is_numeric($value) ? strtotime($value) : $value; } protected function setLeavetimeAttr($value) { return $value && !is_numeric($value) ? strtotime($value) : $value; } //获取(全部/站点)骑手列表 public function getRiders($where,$sort,$order,$offset,$limit,$site_id){ if(empty($site_id)){ $list = $this ->where($where) ->order($sort, $order) ->limit($offset, $limit) ->select(); }else{ $list = $this ->where($where) ->where("site_id=$site_id") ->order($sort, $order) ->limit($offset, $limit) ->select(); } return $list; } //获取符合条件的总记录数 public function getTotal($where,$sort,$order,$site_id){ if(empty($site_id)) return $this->where($where)->order($sort, $order)->count(); return $this->where($where)->where("site_id=$site_id")->order($order)->count(); } //按ID获取骑手信息 public function getRider($riderid){ return $this->find($riderid); } //按条件获取站点骑手统计信息 public function statisticBySite($where){ return $this->field('site_id,count(id) pnu')->where($where)->group('site_id')->select(); } //按站点获取站点在职骑手 public function getRiderBySite($siteid,$time){ return Db::name('rider')->field('id,name')->where("site_id = $siteid and jointime<=$time and (leavetime = 0 or leavetime>$time)")->select(); } //根据身份证获取骑手信息 public function getByIdcard($idcard){ return $this->where("idcard='$idcard'")->find(); } //根据openID获取骑手信息 public function getRiderByOpenid($openid){ return $this->where("open_id='$openid'")->find(); } //根据userid获取骑手信息 public function getRiderByUserid($userid){ return $this->where("user_id=$userid")->find(); } }
Python
UTF-8
5,134
3.34375
3
[]
no_license
# coding: utf-8 import csv import matplotlib.pyplot as plt from datetime import datetime as dt import matplotlib.dates as md import pandas as pd from datetime import timedelta as td def read(): dates = [] values = [] with open('000001-clip.csv', 'rb') as f: lines = csv.reader(f) for row in lines: dates.append(row[0]) # 日期 values.append(row[8]) # 涨跌额 return dates, values # data = read() # x = [i for i in data[0]] # x.pop(0) # y = [i for i in data[1]] # y.pop(0) def draw_bar(): data = pd.read_csv('000001-clip-1.csv', encoding='utf-8') x = data[u'日期'].T.values y = data[u'涨跌额'].T.values fmt = '%Y-%m-%d' fig = plt.figure() plt.gca().xaxis.set_major_formatter(md.DateFormatter(fmt)) fig.autofmt_xdate() x = [dt.strptime(k, fmt).date() for k in x] color_list = [] for i in y: if i > 0: color_list.append('r') else: color_list.append('g') plt.bar(x, y, color=color_list) plt.show() # 按时间序列分组汇总 def draw_bar_month(): data = pd.read_csv('000001-clip-1.csv', encoding='utf-8') data.index = pd.to_datetime(data[u'日期']) # 索引设置为日期格式数据列 data = data.groupby(pd.Grouper(freq='M')) # 按月累加 data = data.sum() x = data.index.values y = data[u'涨跌幅'].values plt.gca().xaxis.set_major_formatter(md.DateFormatter('%Y-%m')) plt.gca().xaxis.set_major_locator(md.MonthLocator()) # 以月为间隔 color_list = [] for i, j in zip(x, y): if j > 0: color_list.append('r') plt.text(i, j, '%.2f' % j, va='bottom', ha='center', size=8) # 柱状图上添加数字 else: color_list.append('g') plt.text(i, j, '%.2f' % j, va='top', ha='center', size=8) plt.bar(x, y, color=color_list, width=20) plt.xlabel(u'月份') plt.ylabel(u'上证指数涨跌幅度') plt.title(u'上证指数月度涨跌幅度') plt.xticks(rotation=60) plt.show() # 按时间序列分组汇总双柱图 def draw_double_bar_month(): data = pd.read_csv('000001-clip-1.csv', encoding='utf-8') data.index = pd.to_datetime(data[u'日期']) # 索引设置为日期格式数据列 data = data.groupby(pd.Grouper(freq='M')) # 按月累加 data = data.sum() x = data.index.values y1 = data[u'涨跌幅'].values y2 = data[u'涨跌额'].values plt.gca().xaxis.set_major_formatter(md.DateFormatter('%Y-%m')) plt.gca().xaxis.set_major_locator(md.MonthLocator()) # 以月为间隔 g = (x[1] - x[0]) / 2 # 间隔 color_list1 = [] color_list2 = [] for i, j, k in zip(x, y1, y2): if j > 0: color_list1.append('r') color_list2.append('cyan') plt.text(i - g, j, '%.2f' % j, va='bottom', ha='center', size=8) # 柱状图上添加数字 plt.text(i, k, '%.2f' % k, va='bottom', ha='center', size=8) # 柱状图上添加数字 else: color_list1.append('g') color_list2.append('blue') plt.text(i - g, j, '%.2f' % j, va='top', ha='center', size=8) plt.text(i, k, '%.2f' % k, va='top', ha='center', size=8) plt.bar(x - g, y1, color=color_list1, width=10) plt.bar(x, y2, color=color_list1, width=10) plt.xlabel(u'月份') plt.ylabel(u'上证指数涨跌幅度') plt.title(u'上证指数涨跌幅度与点数图') plt.xticks(rotation=45) plt.show() # 汇总每个月份涨跌个数 def draw_bar_month_count(): data = pd.read_csv('000001-clip-1.csv', encoding='utf-8') data.index = pd.to_datetime(data[u'日期']) # 索引设置为日期格式数据列 data = data.groupby(pd.Grouper(freq='M')) # 按月累加 x = []#时间序列 y1 = []#上涨个数 y2 = []#下跌个数 for i in data[u'涨跌幅']: x.append(pd.Timestamp(i[0]).to_pydatetime()) up = 0 down = 0 for j in i[1]: if j >= 0: up += 1 else: down += 1 y1.append(up) y2.append(down) plt.gca().xaxis.set_major_formatter(md.DateFormatter('%Y-%m')) plt.gca().xaxis.set_major_locator(md.MonthLocator())#以月为间隔 g = (x[1] - x[0]) / 2 # 间隔 x1 = [] x2 = [] for i in x: x1.append(i - g / 6) x2.append(i + g / 2) for i, j in zip(x1, y1): plt.text(i, j, j, va='bottom', ha='center', size=8) # 柱状图上添加数字 for i, j in zip(x2, y2): plt.text(i, j, j, va='bottom', ha='center', size=8) # 柱状图上添加数字 plt.bar(x1, y1, color='r', width=10, label=u'上涨天数') plt.bar(x2, y2, color='g', width=10, label=u'下跌天数') plt.legend(loc='upper right') plt.xlabel(u'月份') plt.ylabel(u'上证指数涨跌个数') plt.title(u'上证指数月度涨跌天数') plt.xticks(rotation=45) plt.show() if __name__ == '__main__': # draw_bar() # draw_bar_month() # draw_double_bar_month() draw_bar_month_count()
Python
UTF-8
1,424
2.828125
3
[]
no_license
# -*- coding:utf-8 -*- import math import re rp = re.compile("[\t ]") def dist(x1, x2): return math.sqrt(sum((x1[i] - x2[i]) ** 2 for i in xrange(0, len(x1)))) def getNeighborsCount(xs, x0, r): return len(getNeighbors(xs, x0, r)) def getNeighbors(xs, x0, r): l = list() set((l.append(x) if dist(x, x0) <= r else None for x in xs)) return l def train(xs, minpts, r): """ :param xs: 样本集合 :param minpts: r邻域的向量数量 :param r: r邻域的距离阈值 :return: """ stack = list() cluster = list() neighbors = dict() for x in xs: nbs = getNeighbors(xs, x, r) nbsc = len(nbs) if nbsc >= minpts: stack.append(x) neighbors. while len(stack) >= 0: clu = list() o = stack.pop() nbs = getNeighbors(xs, o, r) if len(nbs) >= minpts: clu.append(*nbs) for c in clu: getNe def main(): train_file = './test1.dat' minpts = 10 r = 20 train_data = list() with open(train_file, 'r') as f: for line in f: l = [int(s.replace('\n', '')) for s in rp.split(line)] l[0] = 0 s = sum(l) l = [float(i) / s for i in l] train_data.append(l) train(train_data, minpts, r)
Python
UTF-8
254
3.8125
4
[]
no_license
#Задание 4 from itertools import chain def up_and_down(n): # 1,2, ..., n, ..., 2, 1 return chain(range(1, n), range(n, 0, -1)) def diamond(n): for i in up_and_down(n): print((n-i)*' ', *up_and_down(i), sep='') print(diamond(3))
Java
UTF-8
619
1.867188
2
[]
no_license
package com.google.android.exoplayer2.source.dash; /* compiled from: lambda */ /* renamed from: com.google.android.exoplayer2.source.dash.-$$Lambda$DashMediaSource$e1nzB-O4m3YSG1BkxQDKPaNvDa8 */ public final /* synthetic */ class C0207-$$Lambda$DashMediaSource$e1nzB-O4m3YSG1BkxQDKPaNvDa8 implements Runnable { private final /* synthetic */ DashMediaSource f$0; public /* synthetic */ C0207-$$Lambda$DashMediaSource$e1nzB-O4m3YSG1BkxQDKPaNvDa8(DashMediaSource dashMediaSource) { this.f$0 = dashMediaSource; } public final void run() { this.f$0.lambda$new$0$DashMediaSource(); } }
Java
UTF-8
12,666
1.734375
2
[]
no_license
package com.sccodesoft.schoolfinder; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.GeoDataClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.List; public class PlacePickerActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleMap mMap; private GoogleApiClient googleApiClient; private LocationRequest locationRequest; private Marker currentUserLocationMarker; private static final int Request_User_Location_Code = 99; private double latitude, longitude = ' '; private ImageButton searchLocation; private EditText addressfld; private TextView geocodeAddress; private LinearLayout pickLocation; private ProgressDialog Loadingbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_place_picker); initializeFields(); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkUserLocationPermission(); } // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.placepicker); mapFragment.getMapAsync(this); Loadingbar = new ProgressDialog(this); pickLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Loadingbar.setTitle("Please Wait"); Loadingbar.setMessage("Please Wait While We are Getting Place Information.."); Loadingbar.show(); Loadingbar.setCanceledOnTouchOutside(false); if(TextUtils.isEmpty(geocodeAddress.getText())) { Loadingbar.dismiss(); Toast.makeText(PlacePickerActivity.this, "Please Select Location..", Toast.LENGTH_SHORT).show(); } else { Intent resultintent = new Intent(); resultintent.putExtra("lati",latitude); resultintent.putExtra("longti",longitude); resultintent.putExtra("address",geocodeAddress.getText()); Loadingbar.dismiss(); setResult(Activity.RESULT_OK,resultintent); finish(); } } }); } private void initializeFields() { searchLocation = (ImageButton)findViewById(R.id.search_Location); addressfld = (EditText)findViewById(R.id.location_search); geocodeAddress = (TextView)findViewById(R.id.geocode_address); pickLocation = (LinearLayout)findViewById(R.id.pick_location_btn); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buidGoogleApiClient(); mMap.setMyLocationEnabled(true); } mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { mMap.clear(); mMap.addMarker(new MarkerOptions().position(latLng).title("Selected Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); latitude = latLng.latitude; longitude = latLng.longitude; Geocoder geocoder = new Geocoder(getApplicationContext()); List<Address> addresses = null; try { addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses.size() == 0) { Toast.makeText(getApplicationContext(), "Please select proper location", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); } String address = addresses.get(0).getAddressLine(0); geocodeAddress.setText(address); } }); searchLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String address = addressfld.getText().toString(); List<Address> addressList = null; MarkerOptions userMarkerOptions = new MarkerOptions(); if (!TextUtils.isEmpty(address)) { Geocoder geocoder = new Geocoder(getApplicationContext()); try { addressList = geocoder.getFromLocationName(address,6); } catch (IOException e) { e.printStackTrace(); } if(addressList != null) { for(int i = 0; i<addressList.size();i++) { Address userAddress = addressList.get(i); LatLng latLng = new LatLng(userAddress.getLatitude(),userAddress.getLongitude()); userMarkerOptions.position(latLng); userMarkerOptions.title(address); userMarkerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); mMap.clear(); mMap.addMarker(userMarkerOptions); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(10)); latitude = latLng.latitude; longitude = latLng.longitude; geocodeAddress.setText(address); break; } } else { Toast.makeText(PlacePickerActivity.this, "Location Not Found", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(PlacePickerActivity.this, "Please Enter a Location Name", Toast.LENGTH_SHORT).show(); } } }); } @Override public void onConnected(@Nullable Bundle bundle) { locationRequest = new LocationRequest(); locationRequest.setInterval(1100); locationRequest.setFastestInterval(1100); locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } public boolean checkUserLocationPermission() { if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code); } else { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code); } return false; } else { return true; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case Request_User_Location_Code: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if(googleApiClient == null) { buidGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { Toast.makeText(this, "Permission Denied..", Toast.LENGTH_SHORT).show(); } return; } } protected synchronized void buidGoogleApiClient() { googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); googleApiClient.connect(); } @Override public void onLocationChanged(Location location) { latitude = location.getLatitude(); longitude = location.getLongitude(); if(currentUserLocationMarker != null) { currentUserLocationMarker.remove(); } LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("Your Current Location"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)); currentUserLocationMarker = mMap.addMarker(markerOptions); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomBy(12)); if(googleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this); } } }
Java
UTF-8
2,416
1.96875
2
[ "MIT" ]
permissive
package com.zenden2k.VfFrameworkIdeaPlugin.reference; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.zenden2k.VfFrameworkIdeaPlugin.utils.AutocompleteHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; /* Reference to xml (or php) guide file from xml file <field name="name" export="true" guide="[REFERENCE]" sorting="true/> TODO: merge with PhpGuideReference */ public class XmlGuideReference extends PsiReferenceBase<PsiElement> { protected final Project project; protected final String guideName; public XmlGuideReference(String guideName, PsiElement element, TextRange textRange, Project project) { super(element, textRange,false); this.project = project; this.guideName = guideName; } @Override @NotNull public Object @NotNull [] getVariants() { return AutocompleteHelper.getGuideList(this.project).toArray(); } @Override @Nullable public PsiElement resolve() { final VirtualFile[] vFiles = ProjectRootManager.getInstance(this.project).getContentRoots(); if (vFiles.length != 0) { final String guideNameLower = guideName.toLowerCase(Locale.ROOT); VirtualFile vf = vFiles[0].findFileByRelativePath("system/application/guide/" + guideNameLower + ".xml"); if (vf == null) { vf = vFiles[0].findFileByRelativePath("system/application/guide/" + guideNameLower + ".php"); } if (vf != null) { final PsiFile psiFile = PsiManager.getInstance(project).findFile(vf); if (psiFile instanceof XmlFile) { final XmlFile xmlFile = (XmlFile) psiFile; final XmlTag tag = xmlFile.getRootTag(); if (tag != null) { return tag; } return xmlFile; } else { return psiFile; } } } return null; } @Override @NotNull public String getCanonicalText() { return guideName; } }
C
UTF-8
2,181
3.96875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef int ElementType; #define MinData -1 typedef struct HeapStruct *PriorityQueue; struct HeapStruct { ElementType *Elements; int Capacity; int Size; }; PriorityQueue Initialize( int MaxElements ); /* details omitted */ void PercolateUp( int p, PriorityQueue H ); void PercolateDown( int p, PriorityQueue H ); void Insert( ElementType X, PriorityQueue H ) { int p = ++H->Size; H->Elements[p] = X; PercolateUp( p, H ); } ElementType DeleteMin( PriorityQueue H ) { ElementType MinElement; MinElement = H->Elements[1]; H->Elements[1] = H->Elements[H->Size--]; PercolateDown( 1, H ); return MinElement; } int main() { int n, i, op, X; PriorityQueue H; scanf("%d", &n); H = Initialize(n); for ( i=0; i<n; i++ ) { scanf("%d", &op); switch( op ) { case 1: scanf("%d", &X); Insert(X, H); break; case 0: printf("%d ", DeleteMin(H)); break; } } printf("\nInside H:"); for ( i=1; i<=H->Size; i++ ) printf(" %d", H->Elements[i]); return 0; } /* Your function will be put here */ PriorityQueue Initialize(int MaxElements) { PriorityQueue q = malloc(sizeof(*q)); q->Elements = malloc(sizeof(ElementType) * (MaxElements+1)); q->Capacity = MaxElements; q->Size = 0; return q; } void swap(PriorityQueue H, int a, int b) { int t = H->Elements[a]; H->Elements[a] = H->Elements[b]; H->Elements[b] = t; } void PercolateUp(int p, PriorityQueue H) { int pp; while (p > 1) { pp = p / 2; if (H->Elements[pp] > H->Elements[p]) { swap(H, pp, p); p = pp; continue; } break; } } void PercolateDown(int p, PriorityQueue H) { int left = p << 1; int right = (p << 1) + 1; int min = p; if (left <= H->Size && H->Elements[left] < H->Elements[p]) min = left; if (right <= H->Size && H->Elements[right] < H->Elements[min]) min = right; if (min != p) { swap(H, min, p); PercolateDown(min, H); } }
C#
UTF-8
4,600
2.546875
3
[]
no_license
 namespace Admin.Books { using Admin.Helpers; using BL.Managers; using DAL.Entities; using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Linq; using BL.Constants; public partial class Manage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["message"]) && Request["message"] == "BookUpdatedSuccess") { lblMessage.Text = FlowMessages.BookUpdatedSuccess; lblMessage.CssClass = "SuccessBox"; } if (!Page.IsPostBack) { InitializeUsersTable(); } } private void InitializeUsersTable() { var user = Session[SessionConstants.LoginUser] as User; var books = BooksManager.GetAllBooks(user.Library.Id); foreach (Book book in books) { TableRow row = new TableRow(); HyperLink link = new HyperLink { NavigateUrl = "~/Loans/Search.aspx?bookId=" + book.Id, CssClass = "toClickOn", Text = "Împrumuturi" }; TableCell bookId = new TableCell(); bookId.Controls.Add(link); row.Cells.Add(bookId); HyperLink linkEditUser = new HyperLink { NavigateUrl = "~/Books/Add.aspx?bookId=" + book.Id, CssClass = "toClickOn", Text = "Editează" }; TableCell userEditCell = new TableCell(); userEditCell.Controls.Add(linkEditUser); row.Cells.Add(userEditCell); TableCell bookStatus = new TableCell { Text = book.BookStatus.ToString() }; row.Cells.Add(bookStatus); TableCell bookInternalNr = new TableCell { Text = book.InternalNr }; row.Cells.Add(bookInternalNr); var bookIsbns = book.ISBNs.Select(b => b.Value); TableCell bookIsbn = new TableCell { Text = string.Join(", ", bookIsbns) }; row.Cells.Add(bookIsbn); TableCell bookTitle = new TableCell { Text = book.Title }; row.Cells.Add(bookTitle); TableCell bookPublishYear = new TableCell { Text = (book.PublishYear != null) ? book.PublishYear.ToString() : string.Empty }; row.Cells.Add(bookPublishYear); string authors = "Fără autor(i)"; if(book.Authors.Count >= 1) { authors = book.Authors[0].Name; } if(book.Authors.Count > 1) { var count = book.Authors.Count() - 1; authors = authors + " + " + count; } TableCell bookAuthors = new TableCell { Text = authors }; row.Cells.Add(bookAuthors); TableCell bookNrPages = new TableCell { Text = book.NrPages.ToString() }; row.Cells.Add(bookNrPages); TableCell bookPublisher = new TableCell { Text = book.Publisher.Name }; row.Cells.Add(bookPublisher); TableCell bookVolume = new TableCell { Text = book.Volume }; row.Cells.Add(bookVolume); TableCell bookCondition = new TableCell { Text = book.BookCondition.ToString() }; row.Cells.Add(bookCondition); TableCell bookFormat = new TableCell { Text = book.BookFormat.ToString() }; row.Cells.Add(bookFormat); TableCell userLanguage = new TableCell { Text = book.BookLanguage.ToString() }; row.Cells.Add(userLanguage); datatableResponsive.Rows.Add(row); } } } }
Java
UTF-8
1,070
3.828125
4
[]
no_license
package com.lec.java.collection10; import java.util.Iterator; import java.util.TreeSet; public class Collection10Main { public static void main(String[] args) { System.out.println("TreeSet 연습"); // String 타입을 저장할 수 있는 TreeSet 인스턴스 생성 // 5개 이상의 데이터를 저장해보고 // 오름차순, 내림차순으로 출력해보기 TreeSet<String> tset = new TreeSet<String>(); tset.add("a"); tset.add("b"); tset.add("c"); tset.add("d"); tset.add("e"); System.out.println("오름차순:"); Iterator<String> itr = tset.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } System.out.println(); System.out.println("내림차순:"); // 내림차순 Iterator : descendingIterator() 사용 Iterator<String> itr2 = tset.descendingIterator(); while(itr2.hasNext()) { System.out.println(itr2.next()); } System.out.println("\n프로그램 종료"); } // end main } // end class
PHP
UTF-8
1,250
2.515625
3
[]
no_license
<html> <body> <head> <title>AYAYA Ayoub</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <?php include 'connexpdo.php'; $dsn = 'pgsql:host=localhost;port=5432;dbname=citations;'; $user = 'postgres'; $password = 'Slender44'; $idcon = connexpdo($dsn, $user, $password); echo "<h1>"."Auteur de la BD"."</h1>"; echo "<table>"; echo "<tr>"; echo "<td>"."Nom"."</td>>"; echo "<td>"."Prenom"."</td>"; echo "</tr>"; $query1 = "SELECT * FROM auteur"; $result1 = $idcon->query($query1); foreach($result1 as $data) { echo "<tr>"; echo "<td>".$data['nom']."</td>>"; echo "<td>".$data['prenom']."</td>"; echo "</tr>"; } echo "</table>"; echo "<br>"; echo "<h1>Citations de la BD</h1>"; $query2 = "SELECT * FROM citation"; $result2 = $idcon->query($query2); foreach ($result2 as $data){ echo $data['phrase']."<br>"; } echo "<br>"; echo "<h1>Siecles de la BD</h1>"; $query3 = "SELECT * FROM siecle"; $result3 = $idcon->query($query3); foreach ($result3 as $data){ echo $data['numero']."<br>"; } ?> </body> </html>
Markdown
UTF-8
12,137
2.6875
3
[ "Apache-2.0" ]
permissive
# AWS Custom Namespace Monitoring Extension ## Use Case Captures Custom Namespace statistics from Amazon CloudWatch and displays them in the AppDynamics Metric Browser. Before you configure this extension, you can take a look [here](https://developer.cisco.com/codeexchange/explore/#products=AppDynamics%20Extension) to see if any specific extension is available for your AWS services which you are planning to monitor. Using specific extension provides more configurability and better monitoring. ## Prerequisites 1. Before the extension is installed, the prerequisites mentioned [here](https://community.appdynamics.com/t5/Knowledge-Base/Extensions-Prerequisites-Guide/ta-p/35213) need to be met. Please do not proceed with the extension installation if the specified prerequisites are not met. 2. Please give the following permissions to the account being used to with the extension. ``` cloudwatch:ListMetrics cloudwatch:GetMetricStatistics ``` ## Installation 1. Run `mvn clean install` from aws-customnamespace-monitoring-extension 2. Copy and unzip AWSCustomNamespaceMonitor-\<version\>.zip from 'target' directory into \<MachineAgent_Home\>/monitors/ directory. 3. Edit the config.yml file located at MachineAgent_Home/monitors/AWSCustomNamespaceMonitor and provide the required configuration (see Configuration section) 4. The metricPrefix of the extension has to be configured as specified [here](https://community.appdynamics.com/t5/Knowledge-Base/How-do-I-troubleshoot-missing-custom-metrics-or-extensions/ta-p/28695#Configuring%20an%20Extension). Please make sure that the right metricPrefix is chosen based on your machine agent deployment, otherwise this could lead to metrics not being visible in the controller. 5. Restart the Machine Agent. Please place the extension in the **"monitors"** directory of your **Machine Agent** installation directory. Do not place the extension in the **"extensions"** directory of your **Machine Agent** installation directory. ## Configuration In order to use the extension, you need to update the config.yml file that is present in the extension folder. The following is an explanation of the configurable fields that are present in the config.yml file. 1. If SIM is enabled, then use the following metricPrefix `metricPrefix: "Custom Metrics|AWS DynamoDB"` else configure the `COMPONENT_ID` under which the metrics need to be reported. This can be done by changing the value of <COMPONENT_ID> in `metricPrefix: "Server|Component:<COMPONENT_ID>|Custom Metrics|AWS DynamoDB|"`. For example, `metricPrefix: "Server|Component:100|Custom Metrics|Amazon Custom Namespace|"` More details around metric prefix can be found [here](https://community.appdynamics.com/t5/Knowledge-Base/How-do-I-troubleshoot-missing-custom-metrics-or-extensions/ta-p/28695). 2. Provide accessKey(required) and secretKey(required) of AWS account(s), also provide displayAccountName(any name that represents your account) and regions(required). If you are running this extension inside an EC2 instance which has IAM profile configured then awsAccessKey and awsSecretKey can be kept empty, extension will use IAM profile to authenticate. ``` accounts: - awsAccessKey: "XXXXXXXX1" awsSecretKey: "XXXXXXXXXX1" displayAccountName: "TestAccount_1" regions: ["us-east-1","us-west-1","us-west-2"] - awsAccessKey: "XXXXXXXX2" awsSecretKey: "XXXXXXXXXX2" displayAccountName: "TestAccount_2" regions: ["eu-central-1","eu-west-1"] ``` 3. Please specify the AWS Namespace that you would like to monitor. Please note that only 1 AWS Namespace can be monitored using this extension. Inorder to monitor multiple Namespaces, please have multiple copies of this extension. However, multiple accounts can be configured under the `accounts` to monitor the namespace. Example is `namespace: "AWS/DynamoDB"` 4. If you want to encrypt the "awsAccessKey" and "awsSecretKey" then follow the "Credentials Encryption" section and provide the encrypted values in "awsAccessKey" and "awsSecretKey". Configure "enableDecryption" of "credentialsDecryptionConfig" to true and provide the encryption key in "encryptionKey" For example, ``` #Encryption key for Encrypted password. credentialsDecryptionConfig: enableDecryption: "true" encryptionKey: "XXXXXXXX" ``` 5. Configure proxy details if there is a proxy between MachineAgent and AWS. ``` proxyConfig: host: port: username: password: ``` 6. To report metrics from specific dimension values, configure the `dimesions` section. The dimensions varies with AWS Namespace. Please refer to AWS [doc](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension) for details on dimensions. Example below: ``` dimensions: - name: "TableName" displayName: "Table Name" values: ["ABC", "DEF"] - name: "AvailabilityZone" displayName: "Availability Zone" values: [".*"] ``` name is the dimension name and values are comma separated values of the dimension. displayName is the name with which it appears on the AppDynamics Metric Browser. If these fields are left empty, none of your instances will be monitored. In order to monitor everything under a dimension, you can simply use ".*" to pull everything from your AWS Environment. 7. Configure the metrics section. For configuring the metrics, the following properties can be used: | Property | Default value | Possible values | Description | | :---------------- | :-------------- | :------------------------------ | :------------------------------------------------------------------------------------------------------------- | | alias | metric name | Any string | The substitute name to be used in the metric browser instead of metric name. | | statType | "ave" | "AVERAGE", "SUM", "MIN", "MAX" | AWS configured values as returned by API | | aggregationType | "AVERAGE" | "AVERAGE", "SUM", "OBSERVATION" | [Aggregation qualifier](https://docs.appdynamics.com/display/latest/Build+a+Monitoring+Extension+Using+Java) | | timeRollUpType | "AVERAGE" | "AVERAGE", "SUM", "CURRENT" | [Time roll-up qualifier](https://docs.appdynamics.com/display/latest/Build+a+Monitoring+Extension+Using+Java) | | clusterRollUpType | "INDIVIDUAL" | "INDIVIDUAL", "COLLECTIVE" | [Cluster roll-up qualifier](https://docs.appdynamics.com/display/latest/Build+a+Monitoring+Extension+Using+Java)| | multiplier | 1 | Any number | Value with which the metric needs to be multiplied.| | convert | null | Any key value map | Set of key value pairs that indicates the value to which the metrics need to be transformed. eg: UP:0, DOWN:1 | | delta | false | true, false | If enabled, gives the delta values of metrics instead of actual values.| For example, ``` - name: "ConsumedReadCapacityUnits" alias: "Consumed Read Capacity Units" statType: "ave" delta: false multiplier: 1 aggregationType: "AVERAGE" timeRollUpType: "AVERAGE" clusterRollUpType: "INDIVIDUAL" ``` **All these metric properties are optional, and the default value shown in the table is applied to the metric(if a property has not been specified) by default.** 8. For several services AWS CloudWatch does not instantly update the metrics but it goes back in time to update that information. This delay sometimes can take upto 5 minutes. The extension runs every minute(Detailed) or every 5 minutes (Basic) and gets the latest value at that time. There may be a case where the extension may miss the value before CloudWatch updates it. In order to make sure we don't do that, the extension has the ability to look for metrics during a certain interval, where we already have set it to default at 5 minutes but you can change it as per your requirements. ``` metricsTimeRange: startTimeInMinsBeforeNow: 10 endTimeInMinsBeforeNow: 5 ``` 9. This field is set as per the defaults suggested by AWS. You can change this if your limit is different. ``` getMetricStatisticsRateLimit: 400 ``` 10. The maximum number of retry attempts for failed requests that can be retried. ``` maxErrorRetrySize: 3 ``` 11. CloudWatch can be used in two formats, Basic and Detailed. You can specify how you would like to run the extension by specifying the chosen format here. By default, the extension is set to Basic, which makes the extension run every 5 minutes. Refer https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch-new.html for more information. ``` #Allowed values are Basic and Detailed. # Basic will fire CloudWatch API calls every 5 minutes # Detailed will fire CloudWatch API calls every 1 minutes cloudWatchMonitoring: "Basic" ``` Please avoid using tab (\t) when editing yaml files. Please copy all the contents of the config.yml file and go to [Yaml Validator](https://jsonformatter.org/yaml-validator) . On reaching the website, paste the contents and press the “Validate YAML” button. If you get a valid output, that means your formatting is correct and you may move on to the next step. ## Metrics Typical metric path: **Application Infrastructure Performance|\<Tier\>|Custom Metrics|Amazon Custom Namespace|\<NameSpace\>|\<Account Name\>|Region|Dimension Name|Dimension Value|** followed by the AWS Namespace configured metrics ## Credentials Encryption Please visit [this page](https://community.appdynamics.com/t5/Knowledge-Base/How-to-use-Password-Encryption-with-Extensions/ta-p/29397) to get detailed instructions on encryption. The steps in this document will guide you through the whole process. ## Extensions Workbench Workbench is an inbuilt feature provided with each extension in order to assist you to fine tune the extension setup before you actually deploy it on the controller. Please review the following document on [How to use the Extensions WorkBench](https://community.appdynamics.com/t5/Knowledge-Base/How-to-use-the-Extensions-WorkBench/ta-p/30130) ## Troubleshooting Please follow the steps listed in this [troubleshooting document](https://community.appdynamics.com/t5/Knowledge-Base/How-do-I-troubleshoot-missing-custom-metrics-or-extensions/ta-p/28695) in order to troubleshoot your issue. These are a set of common issues that customers might have faced during the installation of the extension. ## Contributing Always feel free to fork and contribute any changes directly via [GitHub](https://github.com/Appdynamics/aws-customnamespace-monitoring-extension). ## Version | Name | Version | |--------------------------|------------| |Extension Version |2.0.3 | |Last Update |20/05/2022| |Changes list|[ChangeLog]((https://github.com/Appdynamics/aws-customnamespace-monitoring-extension/blob/master/CHANGELOG.md))| **Note**: While extensions are maintained and supported by customers under the open-source licensing model, they interact with agents and Controllers that are subject to [AppDynamics’ maintenance and support policy](https://docs.appdynamics.com/latest/en/product-and-release-announcements/maintenance-support-for-software-versions). Some extensions have been tested with AppDynamics 4.5.13+ artifacts, but you are strongly recommended against using versions that are no longer supported.
Python
UTF-8
719
2.9375
3
[ "MIT" ]
permissive
import pyb from pyb import LED l1 = pyb.LED(1) l2 = pyb.LED(2) l3 = pyb.LED(3) l4 = pyb.LED(4) leds = [LED(i) for i in range(1, 5)] pwm_leds = leds[2:] # test printing for l in leds: print(l) # test on and off for l in leds: l.on() assert l.intensity() == 255 pyb.delay(100) l.off() assert l.intensity() == 0 pyb.delay(100) ''' # test toggle for l in 2 * leds: l.toggle() assert l.intensity() in (0, 255) pyb.delay(100) # test intensity for l in pwm_leds: for i in range(256): l.intensity(i) assert l.intensity() == i pyb.delay(1) for i in range(255, -1, -1): l.intensity(i) assert l.intensity() == i pyb.delay(1) '''
Markdown
UTF-8
1,338
2.921875
3
[ "MIT" ]
permissive
# koa-lvcnf Koa middleware for [lvcnf](https://npmjs.com/package/lvcnf). -------- ## Installation `npm i koa-lvcnf` ## Usage ```javascript const Koa = require('koa') const app = new Koa() const Config = require('lvcnf') const koaConfig = require('koa-lvcnf') // config instance to pass into the middleware const config = new Config(initialConfig) // other middlewares app.use(koaConfig({ prefix: '/config', config })) // route prefix app.listen(8888, () => { console.log('i am an app!') }) ``` ``` GET /config => all config values GET /config/foo => config for foo GET /config/foo.bar.baz => the baz value in { foo: { bar: { baz } } } DELETE /config/foo.bar.baz => deletes foo.bar.baz POST /config { "foo": { "bar": 1 } } => merged with current config PATCH /config/foo.bar.baz => updates foo.bar.baz ``` ## Securing The Endpoint There's no built in security, but you can easily wrap this in your own middleware. Example: ```javascript const jwt = require('jwt') app.use(async (ctx, next) => { const authCookie = ctx.cookies.get('some-auth-cookie') const permissions = authCookie && jwt.decode(authCookie).permissions const canEditConfig = permissions.split(',').includes('configManager') if (canEditConfig) { koaConfig({ prefix, config })(ctx, next) } await next() }) ``` ## License [MIT](./LICENSE.md)
PHP
UTF-8
1,938
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php namespace PhpBrew\Tests; use PhpBrew\ReleaseList; use PHPUnit\Framework\TestCase; /** * @small */ class ReleaseListTest extends TestCase { public $releaseList; protected function setUp(): void { $this->releaseList = new ReleaseList(); $this->releaseList->loadJsonFile(__DIR__ . '/../fixtures/php-releases.json'); } public function testGetVersions() { $versions = $this->releaseList->getVersions("7.2"); $this->assertSame( $versions['7.2.0'], array( 'version' => "7.2.0", 'announcement' => "https://php.net/releases/7_2_0.php", 'date' => "30 Nov 2017", 'filename' => "php-7.2.0.tar.bz2", 'name' => "PHP 7.2.0 (tar.bz2)", 'sha256' => "2bfefae4226b9b97879c9d33078e50bdb5c17f45ff6e255951062a529720c64a", 'museum' => false ) ); } public function versionDataProvider() { return array( array("7.3", "7.3.0"), array("7.2", "7.2.13"), array("5.4", "5.4.45"), array("5.6", "5.6.39"), ); } /** * @dataProvider versionDataProvider */ public function testLatestPatchVersion($major, $minor) { $version = $this->releaseList->getLatestPatchVersion($major, $minor); $this->assertInternalType('array', $version); $this->assertEquals($version['version'], $minor); } /** * @dataProvider versionDataProvider */ public function testGetLatestVersion($major, $minor) { $latestVersion = $this->releaseList->getLatestVersion(); $this->assertNotNull($latestVersion); $versions = $this->releaseList->getVersions($major); foreach ($versions as $versionInfo) { $this->assertTrue($latestVersion >= $versionInfo['version']); } } }
Java
UTF-8
27,108
2.328125
2
[]
no_license
package UI; import Java.*; import java.awt.Frame; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.JOptionPane; public class Master_Customer extends javax.swing.JDialog { // Object private Connect connection; // private ArrayList<ListCustomer> list; private ArrayList<myArrlist> arrlist; private myArrlist myarrlist; private ListCustomer listCustomer; private ListSalesman listSalesman; private ResultSet hasil; private PreparedStatement PS; private modelTabelCustomer model; private Frame parent; String kode; // Var public Master_Customer() { initComponents(); } public Master_Customer(java.awt.Frame parent, boolean modal, Connect connection) { super(parent, modal); this.parent = parent; initComponents(); // code here this.connection = connection; tampilTabel("1"); } private void tampilTabel(String param) { int i = 0; try { String datax = "SELECT * " + "from customer c, salesman s " + "where " + (param.equals("1") || param.equals("0") ? "c.status_customer =" + Integer.parseInt(param) : "c.nama_customer like '%" + param + "%'") + " and c.kode_salesman = s.kode_salesman"; hasil = connection.ambilData(datax); setModel(hasil); } catch (NumberFormatException e) { System.out.println("Error tampil tabel"); } } private int getNewId() { String sql = "SELECT kode_customer FROM customer ORDER BY kode_customer DESC LIMIT 1"; int id = 0; try { hasil = connection.ambilData(sql); while (hasil.next()) { id = hasil.getInt("kode_customer") + 1; } } catch (SQLException e) { e.printStackTrace(); } return id; } private void setModel(ResultSet hasil) { try { myarrlist = new myArrlist(); // list = new ArrayList<>(); while (hasil.next()) { listCustomer = new ListCustomer(); this.listCustomer.setKode_customer(hasil.getInt("kode_customer")); this.listCustomer.setNama_customer(hasil.getString("nama_customer")); this.listCustomer.setKota_customer(hasil.getString("kota_customer")); this.listCustomer.setAlamat_customer(hasil.getString("alamat_customer")); this.listCustomer.setProvinsi_customer(hasil.getString("provinsi_customer")); this.listCustomer.setTelepon_customer(hasil.getString("telepon_customer")); this.listCustomer.setContact_customer(hasil.getString("contact_customer")); this.listCustomer.setHari_tagihan(hasil.getString("hari_tagihan")); this.listCustomer.setStatus_customer(hasil.getInt("status_customer")); this.myarrlist.getLc().add(listCustomer); listCustomer = null; listSalesman = new ListSalesman(); listSalesman.setNama_salesman(hasil.getString("nama_salesman")); this.myarrlist.getLs().add(listSalesman); listSalesman = null; } model = new modelTabelCustomer(myarrlist.getLc()); tbl_Customer.setModel(model); } catch (SQLException e) { e.printStackTrace(); } } private void deleteData(String kode_customer) { PS = null; try { String sql = "DELETE FROM customer WHERE kode_customer = ?"; PS = connection.Connect().prepareStatement(sql); PS.setString(1, kode_customer); PS.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel14 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jLabel16 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane7 = new javax.swing.JScrollPane(); tbl_Customer = new javax.swing.JTable(); jCheckBox1 = new javax.swing.JCheckBox(); jSeparator3 = new javax.swing.JSeparator(); jSeparator4 = new javax.swing.JSeparator(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JSeparator(); jSeparator6 = new javax.swing.JSeparator(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); jLabel14.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel14.setText("Kriteria"); jTextField5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray)); jTextField5.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTextField5KeyReleased(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.gray, java.awt.Color.lightGray)); jLabel16.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel16.setText("DAFTAR CUSTOMER"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(jLabel16) .addGap(3, 3, 3)) ); jSeparator2.setForeground(new java.awt.Color(153, 153, 153)); tbl_Customer.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String [] { "Kode", "Nama", "Contact", "Telepon", "Wilayah", "Alamat" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tbl_Customer.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbl_CustomerMouseClicked(evt); } }); jScrollPane7.setViewportView(tbl_Customer); jCheckBox1.setText("Tampilkan Customer Deactive"); jCheckBox1.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jCheckBox1ItemStateChanged(evt); } }); jCheckBox1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jCheckBox1MouseClicked(evt); } }); jSeparator3.setForeground(new java.awt.Color(153, 153, 153)); jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL); jSeparator4.setForeground(new java.awt.Color(153, 153, 153)); jLabel18.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/if_manilla-folder-new_23456.png"))); // NOI18N jLabel18.setText("F2-New"); jLabel18.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel18MouseClicked(evt); } }); jLabel19.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/if_gtk-edit_20500.png"))); // NOI18N jLabel19.setText("F3-Edit"); jLabel19.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel19MouseClicked(evt); } }); jLabel20.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/cancel (3).png"))); // NOI18N jLabel20.setText("F5-Delete"); jLabel20.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel20MouseClicked(evt); } }); jSeparator5.setForeground(new java.awt.Color(153, 153, 153)); jSeparator5.setOrientation(javax.swing.SwingConstants.VERTICAL); jSeparator6.setForeground(new java.awt.Color(153, 153, 153)); jSeparator6.setOrientation(javax.swing.SwingConstants.VERTICAL); jMenuBar1.setPreferredSize(new java.awt.Dimension(0, 0)); jMenu1.setText("File"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0)); jMenuItem1.setText("New"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0)); jMenuItem2.setText("Edit"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0)); jMenuItem3.setText("Delete"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator2) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 864, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBox1) .addGroup(layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(jLabel18) .addGap(18, 18, 18) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(jLabel19) .addGap(18, 18, 18) .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(jLabel20) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jScrollPane7, javax.swing.GroupLayout.Alignment.TRAILING) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel18) .addComponent(jLabel19) .addComponent(jLabel20))) .addComponent(jSeparator5, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator6, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(2, 2, 2) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(jCheckBox1) .addGap(4, 4, 4) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE) .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents String cbox_tampil_customer = "1"; private void jLabel18MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel18MouseClicked Master_Customer_NewEdit mcne = new Master_Customer_NewEdit(new Awal(rootPaneCheckingEnabled), rootPaneCheckingEnabled, listCustomer, getNewId(), connection); mcne.setLocationRelativeTo(new Awal(rootPaneCheckingEnabled)); mcne.setVisible(true); mcne.setLocationRelativeTo(this); tampilTabel(cbox_tampil_customer); }//GEN-LAST:event_jLabel18MouseClicked private void jLabel19MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel19MouseClicked // listCustomer = list.get(jTable7.getSelectedRow()); listCustomer = (ListCustomer) myarrlist.getLc().get(tbl_Customer.getSelectedRow()); listSalesman = (ListSalesman) myarrlist.getLs().get(tbl_Customer.getSelectedRow()); // Object[] temp = {listCustomer, listSalesman}; Object[] temp = {listCustomer, listSalesman}; Master_Customer_NewEdit mcne = new Master_Customer_NewEdit(new Awal(rootPaneCheckingEnabled), rootPaneCheckingEnabled, temp, true, connection); // Master_Customer_NewEdit mcne = new Master_Customer_NewEdit(new Awal(rootPaneCheckingEnabled), rootPaneCheckingEnabled, new Object[] {listCustomer, listSalesman}, true); mcne.setLocationRelativeTo(new Awal(rootPaneCheckingEnabled)); mcne.setVisible(true); tampilTabel(cbox_tampil_customer); }//GEN-LAST:event_jLabel19MouseClicked private void tbl_CustomerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_CustomerMouseClicked kode = tbl_Customer.getValueAt(tbl_Customer.getSelectedRow(), 0).toString(); System.out.println(kode); if (evt.getClickCount() == 2 && !evt.isConsumed()) { evt.consume(); System.out.println("Double Click"); Master_Customer_KartuPiutang mckp = new Master_Customer_KartuPiutang(parent, rootPaneCheckingEnabled, connection, this.kode); mckp.setVisible(true); mckp.setFocusable(true); // this.dispose(); } }//GEN-LAST:event_tbl_CustomerMouseClicked private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel20MouseClicked int hapus = JOptionPane.showConfirmDialog(null, "Apakah Anda yakin Menghapus data ini ?", "Konfimasi Tolak Hapus Data", JOptionPane.OK_CANCEL_OPTION); if (hapus == JOptionPane.OK_OPTION) { int baris = tbl_Customer.getSelectedRow(); deleteData(tbl_Customer.getValueAt(baris, 0).toString()); JOptionPane.showMessageDialog(null, "Data sudah dihapus."); } }//GEN-LAST:event_jLabel20MouseClicked private void jCheckBox1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jCheckBox1MouseClicked if (jCheckBox1.isSelected()) { cbox_tampil_customer = "0"; tampilTabel(cbox_tampil_customer); } else { cbox_tampil_customer = "1"; tampilTabel(cbox_tampil_customer); } }//GEN-LAST:event_jCheckBox1MouseClicked private void jTextField5KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField5KeyReleased tampilTabel(jTextField5.getText()); }//GEN-LAST:event_jTextField5KeyReleased private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed Master_Customer_NewEdit mcne = new Master_Customer_NewEdit(new Awal(rootPaneCheckingEnabled), rootPaneCheckingEnabled, listCustomer, getNewId(), connection); mcne.setLocationRelativeTo(new Awal(rootPaneCheckingEnabled)); mcne.setVisible(true); mcne.setLocationRelativeTo(this); tampilTabel(cbox_tampil_customer); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // listCustomer = list.get(jTable7.getSelectedRow()); listCustomer = (ListCustomer) myarrlist.getLc().get(tbl_Customer.getSelectedRow()); listSalesman = (ListSalesman) myarrlist.getLs().get(tbl_Customer.getSelectedRow()); // Object[] temp = {listCustomer, listSalesman}; Object[] temp = {listCustomer, listSalesman}; Master_Customer_NewEdit mcne = new Master_Customer_NewEdit(new Awal(rootPaneCheckingEnabled), rootPaneCheckingEnabled, temp, true, connection); // Master_Customer_NewEdit mcne = new Master_Customer_NewEdit(new Awal(rootPaneCheckingEnabled), rootPaneCheckingEnabled, new Object[] {listCustomer, listSalesman}, true); mcne.setLocationRelativeTo(new Awal(rootPaneCheckingEnabled)); mcne.setVisible(true); tampilTabel(cbox_tampil_customer); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed int hapus = JOptionPane.showConfirmDialog(null, "Apakah Anda yakin Menghapus data ini ?", "Konfimasi Tolak Hapus Data", JOptionPane.OK_CANCEL_OPTION); if (hapus == JOptionPane.OK_OPTION) { int baris = tbl_Customer.getSelectedRow(); deleteData(tbl_Customer.getValueAt(baris, 0).toString()); JOptionPane.showMessageDialog(null, "Data sudah dihapus."); } tampilTabel(cbox_tampil_customer); }//GEN-LAST:event_jMenuItem3ActionPerformed private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBox1ItemStateChanged if (jCheckBox1.isSelected()) { cbox_tampil_customer = "0"; tampilTabel(cbox_tampil_customer); } else { cbox_tampil_customer = "1"; tampilTabel(cbox_tampil_customer); } }//GEN-LAST:event_jCheckBox1ItemStateChanged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Master_Customer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Master_Customer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Master_Customer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Master_Customer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Master_Customer().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox jCheckBox1; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel20; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JSeparator jSeparator6; private javax.swing.JTextField jTextField5; private javax.swing.JTable tbl_Customer; // End of variables declaration//GEN-END:variables }
C++
UTF-8
923
2.640625
3
[]
no_license
#ifndef SHAREDIMAGEBUFFER_H #define SHAREDIMAGEBUFFER_H #include <set> #include <mutex> #include <condition_variable> #include <unordered_map> #include <map> #include <opencv2/core/mat.hpp> #include "Buffer.h" using namespace std; class SharedImageBuffer { public: SharedImageBuffer(); void add(int deviceNumber, Buffer<cv::Mat> *imageBuffer, bool sync = false); Buffer<cv::Mat>* getByDeviceNumber(int deviceNumber); void removeByDeviceNumber(int deviceNumber); void sync(int deviceNumber); void notifyAll(); void setSyncEnabled(bool enable); bool isSyncEnabledForDeviceNumber(int deviceNumber); bool getSyncEnabled(); private: //unordered_map<int, Buffer<cv::Mat>*> m_imageBufferMap; map<int, Buffer<cv::Mat>*> m_imageBufferMap; set<int> m_syncSet; condition_variable m_cv; mutex m_mutex; int m_nArrived; bool m_doSync; }; #endif // SHAREDIMAGEBUFFER_H
PHP
UTF-8
5,039
2.78125
3
[]
no_license
<?php /** * Abreeza Scraper * * Parses schedules for Abreeza. * * @package Silver * @author brux * @since 0.1.0 */ namespace App\Scrapers; use App\Exceptions\ParseException; use Carbon\Carbon; class Abreeza extends Base { const SLUG = 'abreeza'; /** * The page we will be scraping. * * @var string */ const URL = 'http://www.sureseats.com/theaters/search.asp?tid=ABRZ'; /** * Contains the phpQuery object wrapping the page we will be scraping. * * @var phpQuery */ protected $page; /** * Fetches schedules from the page. * * @return this */ public function fetch() { $this->page = $this->loadPage(self::URL); $blocks = $this->extractBlocks(); $this->processBlocks($blocks); return $this; } protected function extractBlocks() { $tables = $this->page->find('.rounded-half-nbp table[width=135]'); // Log a message if we failed to extract movies if ( empty($tables) ) { throw new ParseException('Abreeza', 'Failed to extract movies!'); } return $tables; } protected function processBlocks($blocks) { foreach ( $blocks as $block ) { $this->processMovie(pq($block)); } } protected function processMovie($block) { $is_3d = false; // If we failed to extract a title, log then stop. $movie = strtolower(trim($block->find('.SEARCH_TITLE')->text())); $movie = $this->cleanMovieTitle($movie); if ( empty($movie) ) { $this->logger->addCritical('[Abreeza] Failed to extract a movie title.'); return; } else { // Extract 3D suffix if ( preg_match('/^\(3d\)/', $movie) ) { $is_3d = true; $movie = preg_replace('/^\(3d\)\s/', '', $movie); } // Create a new record if the movie doesn't exist yet if ( ! isset($this->movies[$movie]) ) { $this->movies[$movie] = [ 'title' => $movie, 'screening_times' => [] ]; } } // Make sure we have a valid cinema $cinema = $block->find('tr:eq(0)')->text(); $cinema = trim($cinema); if ( ! preg_match('/^Cinema [1-4]$/', $cinema) ) { throw new ParseException('Abreeza', 'Invalid cinema name.', $cinema); } else { $cinema = (int) str_replace('Cinema ', '', $cinema); } // Extract the MTRCB rating and make sure it is a correct one. $rating = $block->find('.SEARCH_RATING')->text(); $rating = str_replace('Rating: ', '', $rating); if ( ! in_array($rating, static::$RATINGS) ) { $this->logger->addWarning(sprintf('[Abreeza] "%s" is not a valid MTRCB rating for the movie "%s". Removing it for now.', $rating, $movie)); } else { $this->movies[$movie]['rating'] = $rating; } // Extract the price $price = str_replace('Price: ', '', $block->find('.SEARCH_PRICE')->text()); $price = trim($price); if ( ! preg_match('/^[0-9]+$/', $price) ) { $this->logger->addWarning(sprintf('[Abreeza] "%s" is not a valid ticket price for the movie "%s".', $price, $movie)); $price = null; } else { $price = (int) $price; } // Extract the date $date = trim($block->find('.SEARCH_DATE')->text()); if ( ! preg_match('/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s[0-9]{1,2},\s20[0-9]{2}$/i', $date) ) { throw new ParseException('Abreeza', 'Invalid screening date.', $date); } // Extract screening times and build the date objects foreach ( $block->find('.SEARCH_SCHED') as $s ) { // Validate the time $s = trim(pq($s)->text()); if ( ! preg_match('/((?:1[012]|[1-9]):[0-5][0-9]\s(?i)(?:am|pm))/', $s, $matches) ) { $this->logger->addWarning(sprintf('[Abreeza] "%s" is not a valid time for "%s". Skipping.', $s, $movie)); continue; } else { $s = $matches[1]; } $arr = [ 'cinema' => $cinema, 'time' => Carbon::parse($date . ' ' . $s) ]; // Add ticket price if we have one if ( $price !== null ) { $arr['ticket']['price'] = $price; } // Add a 3D designator if it is one. if ( $is_3d ) { $arr['format'] = '3D'; } $this->movies[$movie]['screening_times'][] = $arr; } } protected function consolidate($movies) { $m = []; $map = []; $i = 0; foreach ( $movies as $movie ) { if ( isset($map[$movie['title']]) ) { $index = $map[$movie['title']]; $m[$index]['screening_times'] = array_merge($m[$index]['screening_times'], $movie['screening_times']); if ( isset($movie['rating']) ) { $m[$index]['rating'] = $movie['rating']; } } else { $map[$movie['title']] = $i; $m[$i] = $movie; $i++; } } return $m; } }
Markdown
UTF-8
3,409
3.28125
3
[]
no_license
## URL [Lecture 4: Reinforcement Learning Introduction](http://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-4.pdf) ## Notes ~Introduction to Reinforcement Learning~ ### Definition of a MDP $$ M = \{S, T \} \\ S: \text{State space(discrete or continuous) , } s \in S \\ A: \text{Action space(discrete or continuous) , } a \in A \\ T: \text{Transition Matrix} \\ r: \text{Reward function , } r: S \times A \rightarrow \mathbb{R} $$ <img src="./images/slide8.png" width="80%"> ### Definition of RL problem Given a trajectory, we would like a policy which maximise the long term reward. $$ \underbrace{p_{\theta}(s_1, a_1, \dots, s_T, a_T)}_{p_{\theta}(\tau)} = p(s_1) \prod^T_{t=1} \pi_{\theta}(a_t | s_t) p(s_{t+1} | s_t, a_t)\\ \theta^* = \text{argmax}_{\theta} E_{\tau \sim p_{\theta}(\tau)} \Big[ \sum_t r(s_t | a_t) \Big]\\ = \text{argmax}_{\theta} \sum^T_{t=1} E_{(s_t, a_t) \sim p_{\theta}(s_t, a_t)} \Big[ r(s_t, a_t) \Big] $$ ### Anatomy of a RL algorithm - generate samples - fit a model and estimate the return - improve the policy $$ Q^{\pi}(s_t, a_t) = \sum^T_{t'=t} E_{\pi^{\theta}} \big[ r(s_{'t}, a_{t'} | s_t, a_t) \big] \text{: total reward from taking } a_t \text{ in } s_t\\ V^{\pi}(s_t) = \sum^T_{t'=t} E_{\pi^{\theta}} \big[ r(s_{'t}, a_{t'} | s_t) \big] \\ = E_{a_t \sim \pi(a_t | s_t)} \big[ Q^{\pi}(s_t, a_t) \big] $$ #### Two ideas for Q-values and state-value functions 1. if we have policy $\pi$, and we know $Q^{\pi}(s,a)$, then we can improve $\pi$.**Deterministic policy** 2. Compute gradient to increase probability of good actions: **Action which has the maximum value is the optimal** #### Review - Definitions - Markov chain - MDP - RL Objectives - Expected Reward - How to evaluate expected reward? - Structure of RL algorithms - sample generation - fitting a model/estimating return - Policy improvement - Value functions and Q-functions ### Brief Overview of RL algorithm types - Policy Gradients: directly differentiate the objective function to optimise an approximated policy by some ML algorithms, e.g., Neural Networks. - Value-based: estimate value function of Q-function of the optimal policy - Actor-Critic: estimate value function of Q-function of the current policy, use it to improve policy - Model-based RL: estimate the transition model, and then - use it for planning on the pre-defined environment - use it to improve a policy - something else.. #### Model-based RL(Dyna, Guided Policy Search etc.) you need to somehow model the environment, then you can use algorithms like, Dynamic Programming or Search Trees. #### Value function based algorithms(Q-learning, DQN, TD etc.) you fit value-functions($V(s), Q(s,a)​$), then set the objective function as $\pi(s) = \text{argmax}_{\theta} Q(s,a)​$ #### Direct policy gradients(REINFORCE, Natural Policy Gradient TRPO etc.) you evaluate the returns like: $R_t = \sum_r r(s_t, a_t)$, then do an optimisation as follows $$ \theta \leftarrow \theta + \alpha \nabla_{\theta} E\big[ \sum_t r(s_t, a_t) \big] $$ #### Actor-critic: value functions + policy gradients(A3C, Soft Actor-Critic(SAC)) etc. you fit value-functions($V(s), Q(s,a)$), then set the objective function as $$ \theta \leftarrow \theta + \alpha \nabla_{\theta} E\big[ \sum_t r(s_t, a_t) \big] $$ #### Comparison: sample efficiency <img src="./images/slide40.png" width="80%">
Python
UTF-8
6,965
2.953125
3
[ "BSD-3-Clause" ]
permissive
import itertools import pprint import copy import numpy as np from shapely import geometry from shapely.strtree import STRtree from .join import Join from ..ops import insert_coords_in_line from ..ops import fast_split from ..ops import np_array_from_lists from ..ops import select_unique_combs from ..utils import serialize_as_svg class Cut(Join): """ This class targets the following objectives: 1. Split linestrings given the junctions of shared paths 2. Identifies indexes of linestrings that are duplicates The cut function is the third step in the topology computation. The following sequence is adopted: 1. extract 2. join 3. cut 4. dedup 5. hashmap # Arguments ---------- data : dict object created by the method topojson.Join. Returns ------- dict object updated and expanded with - updated key: linestrings - new key: bookkeeping_duplicates - new key: bookkeeping_linestrings """ def __init__(self, data, options={}): # execute previous step super().__init__(data, options) # initation topology items self.duplicates = [] self.bookkeeping_linestrings = [] # execute main function self.output = self.cutter(self.output) def __repr__(self): return "Cut(\n{}\n)".format(pprint.pformat(self.output)) def to_dict(self): """ Convert the Cut object to a dictionary. """ topo_object = copy.copy(self.output) topo_object["options"] = vars(self.options) return topo_object def to_svg(self, separate=False, include_junctions=False): """ Display the linestrings and junctions as SVG. Parameters ---------- separate : boolean If `True`, each of the linestrings will be displayed separately. Default is `False` include_junctions : boolean If `True`, the detected junctions will be displayed as well. Default is `False` """ serialize_as_svg(self.output, separate, include_junctions) def cutter(self, data): """ Entry point for the class Cut. The cut function is the third step in the topology computation. The following sequence is adopted: 1. extract 2. join 3. cut 4. dedup 5. hashmap Parameters ---------- data : dict object created by the method topojson.join. Returns ------- dict object updated and expanded with - updated key: linestrings - new key: bookkeeping_duplicates - new key: bookkeeping_linestrings """ if data["junctions"]: # split each feature given the intersections # prepare the junctions as a 2d coordinate array mp = data["junctions"] if isinstance(mp, geometry.Point): mp = geometry.MultiPoint([mp]) # create spatial index on junctions tree_splitter = STRtree(mp) # splitter = np.squeeze(np.array([pt.xy for pt in mp]), axis=(2,)) slist = [] for ls in data["linestrings"]: # slines = split(ls, mp) line, splitter = insert_coords_in_line(ls, tree_splitter) # prev function returns None for splitter if there is nothing to split if splitter is not None: slines = fast_split(line, splitter) slist.append(list(geometry.MultiLineString(slines))) else: slist.append([ls]) # flatten the splitted linestrings, create bookkeeping_geoms array # and find duplicates self.segments_list, bk_array = self.flatten_and_index(slist) self.find_duplicates(self.segments_list) self.bookkeeping_linestrings = bk_array.astype(float) elif data["bookkeeping_geoms"]: bk_array = np_array_from_lists(data["bookkeeping_geoms"]).ravel() bk_array = np.expand_dims( bk_array[~np.isnan(bk_array)].astype(np.int64), axis=1 ) self.segments_list = data["linestrings"] self.find_duplicates(data["linestrings"]) self.bookkeeping_linestrings = bk_array else: self.segments_list = data["linestrings"] # prepare to return object data["linestrings"] = self.segments_list data["bookkeeping_duplicates"] = np.array(self.duplicates) data["bookkeeping_linestrings"] = self.bookkeeping_linestrings return data def flatten_and_index(self, slist): """ Function to create a flattened list of splitted linestrings and create a numpy array of the bookkeeping_geoms for tracking purposes. Parameters ---------- slist : list of LineString list of splitted LineStrings Returns ------- list segmntlist flattens the nested LineString in slist numpy.array array_bk is a bookkeeping array with index values to each LineString """ # flatten segmntlist = list(itertools.chain(*slist)) # create slice pairs segmnt_idx = list(itertools.accumulate([len(geom) for geom in slist])) slice_pair = [ (segmnt_idx[idx - 1] if idx >= 1 else 0, current) for idx, current in enumerate(segmnt_idx) ] # index array list_bk = [range(len(segmntlist))[s[0] : s[1]] for s in slice_pair] array_bk = np_array_from_lists(list_bk) return segmntlist, array_bk def find_duplicates(self, segments_list): """ Function for solely detecting and recording duplicate LineStrings. Firstly creates couple-combinations of LineStrings. A couple is defined as two linestrings where the enveloppe overlaps. Indexes of duplicates are appended to the list self.duplicates. Parameters ---------- segments_list : list of LineString list of valid LineStrings """ # create list with unique combinations of lines using a rdtree line_combs = select_unique_combs(segments_list) # iterate over index combinations for i1, i2 in line_combs: g1 = segments_list[i1] g2 = segments_list[i2] # check if geometry are equal # being equal meaning the geometry object coincide with each other. # a rotated polygon or reversed linestring are both considered equal. if g1.equals(g2): idx_pop = i1 if len(g1.coords) <= len(g2.coords) else i2 idx_keep = i1 if i2 == idx_pop else i2 self.duplicates.append([idx_keep, idx_pop])
Java
UTF-8
3,770
3.21875
3
[]
no_license
package part1; import java.util.*; public class FlatFields { // public int flatFields (int numRows, int numColumns, List<List<Integer>> fields) { // // } public static int cutTreeInGolf(int[][] golf) { // corner case if (golf == null || golf.length == 0 || golf[0].length == 0) return 0; // put all tree and corresponding point into min heap int row = golf.length; int col = golf[0].length; PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); HashMap<Integer, Point> map = new HashMap<Integer, Point>(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (golf[i][j] > 1) { //means this point is a tree pq.offer(golf[i][j]); map.put(golf[i][j], new Point(i, j)); } } } int res = 0; // get the effective element form pq one by one Point src = new Point(row-1, col-1); while (!pq.isEmpty()) { int treeHigh = pq.poll(); Point tar = map.get(treeHigh); int currdistance = bfsFindDistance(golf, src, tar, treeHigh); if (currdistance != -1) { res += treeHigh + currdistance; // set the cutted tree as ground as 1 golf[tar.x][tar.y] = 1; src = tar; } else { return -1; } } return res; } public static int bfsFindDistance(int[][] golf, Point src, Point tar, int height) { if(golf == null || golf.length == 0) return 0; int row = golf.length; int col = golf[0].length; boolean[][] visited = new boolean[row][col]; if( !isValidGolfPlace(golf, visited, src.x, src.y, height) ) return -1; if( !isValidGolfPlace(golf, visited, tar.x, tar.y, height) ) return -1; int[] direcx = {-1,0,1,0}; int[] direcy = {0,-1,0,1}; PointNode root = new PointNode(new Point(src.x, src.y), 0); visited[src.x][src.y] = true; Queue<PointNode> queue = new LinkedList<PointNode>(); queue.add(root); while(!queue.isEmpty()) { int size = queue.size(); for(int i = 0; i < size; i++) { PointNode temp = queue.poll(); //find a matched solution if(temp.pt.x == tar.x && temp.pt.y == tar.y) return temp.dist; for(int j = 0; j < 4; j++) { // tranverse point is valid if(isValidGolfPlace(golf, visited, temp.pt.x+direcx[j], temp.pt.y+direcy[j], height)) { int rowtemp = temp.pt.x+direcx[j]; int coltemp = temp.pt.y+direcy[j]; visited[rowtemp][coltemp] = true; PointNode qadd = new PointNode(new Point(rowtemp, coltemp), temp.dist+1); queue.offer(qadd); } } } } return -1; } public static boolean isValidGolfPlace(int[][] golf, boolean[][] visited, int row, int col, int height) { int m = golf.length; int n = golf[0].length; return row >= 0 && row < m && col >= 0 && col < n && (golf[row][col] == 1 || golf[row][col] == height) && visited[row][col] == false; } static class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } } static class PointNode { Point pt; int dist; PointNode(Point pt, int dist) { //this.x = x; this.pt = pt; this.dist = dist; } } }
TypeScript
UTF-8
3,696
2.890625
3
[]
no_license
import {Article} from './article'; import {List} from '@everest/collections'; import {Customer} from './customer'; export class Order extends List<OrderItem> { id: number; registrationDate = Date.now(); public itemCount = 0; public price = 0; private _payment = 0; public customer: Customer; public payments: Payment[] = []; static anyToType(value: any): Order { const order = new Order(); order._payment = value._payment; order.price = value.price; order.id = value.id; order.registrationDate = value.registrationDate; if (value.customer) { order.customer = Customer.anyToType(value.customer); } if (value.orderItems) { value.orderItems.forEach(item => order.add(OrderItem.anyToType(item))); } if (value.payments) { value.payments.forEach(item => order.payments.push(Payment.anyToType(item))); } return order; } addItem(article: Article, quantity = 1) { const item = this.find(i => i.article.id === article.id); if (item && item.quantity < article.quantity) { item.quantity++; article.countInCart++; } else if (!item && quantity > 0 && article.quantity >= quantity) { this.add(new OrderItem(article, quantity)); article.countInCart += quantity; } this.calculate(); } remove(item: OrderItem) { item.article.countInCart = 0; super.remove(item); this.calculate(); return true; } clear() { this.forEach(i => i.article.countInCart = 0); super.clear(); this.price = 0; this.itemCount = 0; this.payment = 0; this.customer = null; } calculate() { this.itemCount = 0; this.price = 0; this.forEach(i => { this.itemCount += i.quantity; this.price += i.quantity * i.article.sellingPrice; }); } get payment(): number { return this._payment; } set payment(value: number) { if (value < 0) { value = -value; } if (value > this.price) { value = this.price; } this._payment = value; } // for relation in typeORM get orderItems() { return this.toArray(); } get totalPayments() { let payment = 0; this.payments.forEach(p => payment += p.amount); return payment + this.payment; } get paymentIsComplete() { return this.totalPayments === this.price; } get remainingPayment() { return this.price - this.totalPayments; } } export class OrderItem { constructor(public article?: Article, public _quantity?: number) { if (article) { this.price = article.sellingPrice; } } id: number; price = 0; order: Order; get totalPrice() { return this.article.sellingPrice * this._quantity; } get quantity(): number { return this._quantity; } set quantity(value: number) { if (value < 0) { value = -value; } this._quantity = value; } static anyToType(value: any): OrderItem { if (!value) { return null; } const item = new OrderItem(); item._quantity = value._quantity; item.price = value.price; item.id = value.id; if (value.article) { item.article = Article.anyToType(value.article); } if (value.order) { item.order = Order.anyToType(value.order); } return item; } } export class Payment { id: number; registrationDate: Date; constructor(amount: number, order: Order) { this.amount = amount; this.order = order; } amount = 0; order: Order; static anyToType(value: any): Payment { const payment = new Payment(value.amount, value.order); payment.id = value.id; payment.registrationDate = value.registrationDate; return payment; } }
JavaScript
UTF-8
3,134
3.046875
3
[]
no_license
(function($){ /* const menuV= $('.accordion_menu_v'); const menuDd = menuV.find('dd'); */ // 1. 이렇게 줄 경우에는 홈페이지에 접속할 경우 내용의 잔상이 보일 수 있음 (css에서 display:none을 주지 않고 했을 때) // 2. 첫번째 메뉴 내용만 펼쳐놓고 나머지 내용들을 감추고 시작했을 때 자바코드 const menuV= $('.accordion_menu_v'); const menuDt = menuV.find('dt'); const menuDd = menuV.find('dd'); menuDd.eq(0).show(); // let t = menuDt.eq(0).contents(); // 내용에 들어있는 모든 요소 파악 // menuDt.wrap('<div>'); // wrap : 부묘요소를 생성하거나 파악 menuDt.contents().wrap('<a href="#"></a>'); // js 사용시에는 반복문으로 처리해야한다. const menuDtLink = menuDt.find('a'); menuDtLink.css({'display':'block','width':'100%','height':'100%','color':'inherit'}) menuDtLink.on('click',function(){ $(this).parent(menuDt).next(menuDd).siblings('dd').slideUp(); // 1-2 .hide를 줄 경우 매끄럽지 않기 때문에 slideUp을 줘봄(매끄럽게 내려간다) // 1-1 siblings('menuDd')를 넣으면 지칭한 dd를 모두 변수로 지정했기 때문에 모든 dd들이 접힌다. 때로는 변수가 아닌 직접선택을 해주기도 한다. // 1-3 $(this).next('dd').slideDown(); // .show를 줄 경우 매끄럽지 않기 때문에 slideDown을 줘봄(매끄럽게 올라간다) // $(this).next('dd').slideToggle(); // 1-4 처음 지정했을 때 13줄에 eq(0)show를 줬기 때문에 닫고 싶어도 시간이 지날 경우에 다시 dd가 멋대로 나타난다. 그럴때 toggle을 준다. $(this).parent(menuDt).next(menuDd).stop().slideToggle(); // 1-5 toggle을 주면 여러번 연속적으로 빠르게 누르게되면 애니메이션을 멈추게하고 싶어도 누른 값을 치루기 위해 누른만큼 연출이 됨. // 그렇기 때문에 stop으로 제어해줘야 중간에 닫힐 수 있고 좀 더 자연스럽게? 연출됨..? 몰라...흑흑.. // 어떠한 animation 기능을 활용할 때 제어하는 stop은 애니메이션 기능 앞에 써준다. }); // parent를 주지 않고 따로 할 경우... //css에도 설정을 추가해줘야됨 /* menuDt.on('click',function(){ $(this).next(menuDd).siblings('dd').stop().slideUp(); $(this).next(menuDd).stop().slideToggle(); }); */ //dd가 여러개 일 경우 // 선택 요소 뒤에 오는 모든 dd부터 그다음 dt 이전의 요소인 dd까지 //$(this).nextAll('dd').next('dt').prev('dd') /* menuDt.on('click',function(){ let i = $(this).index()/2; menuDd.eq(i).siblings('dd').slideUp(); menuDd.eq(i).stop().slideToggle(); console.log($(this).nextAll('dd').next('dt').prev('dd')); }); //menuDtLink.on('focus', function(){$(this).addClass('action');}); 1번 방법 const addC = function() {($this).addClass('action');}; const removeC = function() {($this).removeClass('action');}; // menuDtLink.on('focus',addC); // menuDtLink.on('blur',removeC); menuDtLink.on({"focus":addC, "blur":removeC}); */ })(jQuery);
Python
UTF-8
1,556
2.609375
3
[]
no_license
#!/usr/bin/env python # split a multi-genbank file into fasta, plus associated metadata # Matthew J. Neave 05.12.2018 import sys from Bio import SeqIO # requires biopython gb_file = sys.argv[1] meta_file = open(sys.argv[2], "w") for record in SeqIO.parse(open(gb_file), "genbank"): try: country = record.features[0].qualifiers["country"][0] except: print("** country not found for: {}. Assigning to unknown".format(record.name)) country = "Unknown" try: collection_date = record.features[0].qualifiers["collection_date"][0] except: print("** collection date not found for: {}. Assigning to unknown.".format(record.name)) collection_date = "Unknown" try: host = record.features[0].qualifiers["host"][0] except: print("** host not found for: {}. Assigning to unknown".format(record.name)) host = "Unknown" authors = ",".join(record.annotations['references'][0].authors.split(",")[0:6]) + " et al" title = record.annotations['references'][0].title journal = record.annotations['references'][0].journal # my other meta file has these headers # strain location country state source date specimen host platform authors title journal meta_file.write("\t".join([record.name, "Unknown", country, "Unknown", "NCBI", collection_date, "Unknown", host, "Unknown", authors, title, journal]) + "\n") fasta_file = open(record.name + ".fasta", "w") fasta_file.write(">" + record.name + "\n" + str(record.seq) + "\n")
Markdown
UTF-8
6,363
3.03125
3
[ "Apache-2.0" ]
permissive
# MatlabRenderer MatlabRenderer is an offscreen renderer written entirely in pure Matlab with no dependencies. It is based on deferred shading, so provides a rasteriser based on z-buffering. It supports texture/normal mapping, shadowing, visibility and orthographic/perspective/perspective+distortion camera models. It is CPU based and hence not fast (around 0.2s to render the Stanford bunny images below on my MacBook Pro) but provides features and control not available with the 3D visualisation tools in Matlab, most notably texture mapping, total control over camera parameters and shadow mapping. Being entirely written in Matlab, it is very hackable if you wish to add your own features. ## Basic usage ```matlab obj = MR_obj_read('data/StanfordBunny.obj'); [cameraparams,renderparams] = MR_default_params(obj.V,400); render = MR_render_mesh(obj.F,obj.V,cameraparams,renderparams); figure; imshow(render) ``` This will render the Stanford bunny with some default camera and rendering parameters: ![Stanford bunny rendering with default parameters](/example1.jpg?raw=true "Stanford bunny rendering with default parameters") For UV texture mapping, insert the following before the call to **MR_render_mesh**: ```matlab renderparams.VT = obj.VT; renderparams.FT = obj.FT; renderparams.textureMode = 'useTextureMap'; renderparams.texmap = im2double(imread('data/StanfordBunny.jpg')); ``` ![Stanford bunny rendering with texture mapping](/example2.jpg?raw=true "Stanford bunny rendering with texture mapping") **MR_render_mesh** returns many other useful things including per vertex visibility, screen space depth map, normal map, shadow map and texture map. ## Citation If you use this renderer in your research, please cite the following paper for which it was developed: A. Bas and W. A. P. Smith. "What Does 2D Geometric Information Really Tell Us About 3D Face Shape?" International Journal of Computer Vision, 127(10):1455-1473, 2019. Bibtex: @article{bas2019what, title={What Does {2D} Geometric Information Really Tell Us About {3D} Face Shape?}, author={Bas, Anil and Smith, William A. P.}, journal={International Journal of Computer Vision}, volume={127}, number={10}, pages={1455--1473}, year={2019} } ## Overview **MR_rasterise_mesh** does the bulk of the work. This function performs z-buffering on the projected mesh and returns a face buffer (triangle index per pixel) and a weight buffer (barycentric weight for three triangle vertices per pixel). From these two buffers, any per-vertex or UV space quantity can be interpolated to produce a screen space value. This is exactly what **MR_compute_buffer_per_vertex** does (for per-vertex quantities) and **MR_compute_buffer_map** does (for UV mapped quantities). The function **MR_render_mesh** is essentially a wrapper to all of the underlying functions, executing the full rendering pipeline. You may want to edit aspects of this, for example to handle multiple light sources. If you want to introduce alternate reflectance models, you should edit **MR_render_buffers**. Consistent with Matlab, the MatlabRenderer uses a coordinate system in which the top left pixel centre has coordinates (1,1). Positive X is right, positive Y is down and positive Z is into the screen. This means that if up in your mesh coordinate system coincides with the positive Y axis, it will appear upside down in the image. The **MR_default_params** function has an optional third argument which, if set true (default), applies a 180 degree rotation about the X axis to orient the mesh the right way up. If you use default parameters and find your mesh is upside down, pass false as the third parameter to **MR_default_params**. ## Limitations Currently only supports point light source (local or distant), Blinn-Phong reflectance and scaled orthographic/perspective/perspective-with-distortion camera models. Since everything is written in pure matlab, it would be easy to modify the code to improve upon any of these. ## Normal map versus per vertex normals If you don't specify anything about surface normals then the default is to compute per-vertex normals and use these. You can alternatively specify your own per-vertex normals or you can use a UV space normal map. The variable names are the same in either case so be careful to avoid confusion. ### Per-vertex normals If you specify **renderparams.normalMode = 'perVertexNormals'** then **renderparams.VN** should have size n x 3 (where n is not necessarily the same as the number of vertices) and contain surface normal vectors. **renderparams.FN** is a triangulation that indexes into **renderparams.VN** and could be the same as the mesh triangulation. ### Normal mapping If you specify **renderparams.normalMode = 'normalMap'** then **renderparams.VN** should have size n x 2 (where n is not necessarily the same as the number of vertices) and contain 2D UV coordinates. You must also supply a normal map **renderparams.normalmap** of size h x w x 3 containing the normal map in UV space. **renderparams.FN** is a triangulation that indexes into **renderparams.VN** and could be the same as the mesh triangulation or the texture coordinate triangulation. ## Mex files Although written entirely in Matlab, it is still possible to compile to mex using Matlab's codegen for modest speed improvement. I have already done this for all key functions on Windows 64, Mac OS X and Linux. So, if you do not wish to edit the matlab source, you can safely use the mex files for faster performance. This option is chosen by setting **renderparams.usemex = true** (default). If you edit any of the functions with precompiled mex files, remember to recompile with codegen if you want to use **renderparams.usemex = true** with your edited version. ## Alternatives There are already a number of off-screen Matlab renderers so you may wonder why I wrote another one. There are two reasons: 1. they don't support all the features I wanted, 2. they have dependencies or require compiling in a way that means it is not always possible to get them to work. MatlabRenderer should work in any recent version of matlab. The alternatives that I know of are: 1. https://uk.mathworks.com/matlabcentral/fileexchange/25071-matlab-offscreen-rendering-toolbox 2. https://talhassner.github.io/home/publication/2014_MVAP
SQL
UTF-8
2,608
3.15625
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.22, for Win64 (x86_64) -- -- Host: localhost Database: stokproje -- ------------------------------------------------------ -- Server version 8.0.22 /*!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 */; /*!50503 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `urunekle` -- DROP TABLE IF EXISTS `urunekle`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `urunekle` ( `idUrunEkle` int NOT NULL AUTO_INCREMENT, `PersonelId` int DEFAULT NULL, `UrunId` int DEFAULT NULL, `Miktar` int DEFAULT NULL, `Tarih` datetime DEFAULT NULL, `Status` int DEFAULT NULL, PRIMARY KEY (`idUrunEkle`), KEY `urunPersonel_idx` (`PersonelId`), KEY `UrunUrun_idx` (`UrunId`), CONSTRAINT `urunPersonel` FOREIGN KEY (`PersonelId`) REFERENCES `personel` (`id`), CONSTRAINT `UrunUrun` FOREIGN KEY (`UrunId`) REFERENCES `urun` (`idUrun`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `urunekle` -- LOCK TABLES `urunekle` WRITE; /*!40000 ALTER TABLE `urunekle` DISABLE KEYS */; INSERT INTO `urunekle` VALUES (1,2,2,15,'2020-01-29 00:00:01',1),(2,2,2,15,'2020-01-31 00:00:01',1),(3,2,1,1,'2020-01-31 00:00:01',1),(4,3,1,1,'2020-01-31 00:00:01',1),(5,3,1,1,'2020-01-31 00:00:01',0),(7,2,2,2,'2020-01-01 00:00:01',1),(8,2,2,2,'2020-01-01 00:00:01',1),(9,2,2,2,'2020-01-01 00:00:01',1),(10,2,2,2,'2020-01-01 00:00:01',1),(11,2,2,2000,'2020-01-01 00:00:01',1); /*!40000 ALTER TABLE `urunekle` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2021-01-23 3:58:12
Python
UTF-8
223
3.859375
4
[]
no_license
print('Enter the first number to add: ') first = input() print('Enter the second number to add: ') second = input() print('Enter the third number to add: ') third = input() total = (first) + (second) + (third) print(total)
Markdown
UTF-8
3,708
2.796875
3
[]
no_license
--- description: 'https://wiki.polkadot.network/docs/en/maintain-guides-how-to-vote-councillor' --- # Voting for Council ## Intro <a id="__docusaurus"></a> The council is an elected body of on-chain accounts that are intended to represent the passive stakeholders of Edgeware. The council has two major tasks in governance: proposing referenda and vetoing dangerous or malicious referenda. This guide will walk you through voting for councillors in the elections. ### Voting for Councillors Voting for councillors requires you to lock your EDG for the duration of your vote. Like the validator elections, you can approve up to 16 different councillors and your vote will be equalized among the chosen group. Unlike validator elections, there is no unbonding period for your reserved tokens. Once you remove your vote, your tokens will be liquid again. > Warning: It is your responsibility not to put your entire balance into the reserved value when you make a vote for councillors. It's best to keep _at least_ a few KSM to pay for transaction fees. Go to the [Polkadot Apps Dashboard](https://polkadot.js.org/apps), **connect to the Edgeware endpoint**, and click on the "Council" tab. On the right side of the window there are two blue buttons, click on the one that says "Vote." ![](https://wiki.polkadot.network/docs/assets/council/vote.png) Since the council uses approval voting, when you vote you signal which of the validators you approve of and your voted tokens will be equalized among the selected candidates. Select up to 16 council candidates by moving the slider to "Aye" for each one that you want to be elected. When you've made the proper configuration submit your transaction. #### Voting for council members[¶](https://guide.kusama.network/en/latest/try/governance/#voting-for-council-members) <a id="voting-for-council-members"></a> 1. Using the [Polkadot UI](https://polkadot.js.org/apps/), make sure you have an account and selected the Kusama network under the [settings tab](https://polkadot.js.org/apps/#/settings). 2. Navigate to the [Council tab](https://polkadot.js.org/apps/#/council) to see current council candidates. 3. In the [Kusama forum](https://forum.kusama.network/), you will find a thread dedicated to council members proposing their candidacy and find out more information. 4. Head over to the [Extrinsics tab](https://polkadot.js.org/apps/#/extrinsics), select the account you wish to vote with, and select `council` under "submit the following extrinsic." Choose `setApprovals(votes, index)` in the second column, enter the council index of the candidate you wish to vote for, and select `yes` to support the candidate, and `nay` to vote against it. 5. Click `Submit transaction` and sign the transaction. ![](https://wiki.polkadot.network/docs/assets/council/vote_for_yourself.png) You should see your vote appear in the interface immediately after your transaction is included. ### Removing your Vote In order to get your reserved tokens back, you will need to remove your vote. Only remove your vote when you're done participating in elections and you no longer want your reserved tokens to count for the councillors that you approve. Go to the "Extrinsics" tab on [Substrate Apps Dashboard](https://polkadot.js.org/apps). Choose the account you want to remove the vote of and select the "electionsPhragmen -&gt; removeVoter\(\)" options and submit the transaction. ![](https://wiki.polkadot.network/docs/assets/council/remove_vote.png) When the transaction is included in a block you should have your reserved tokens made liquid again and your vote will no longer be counting for any councillors in the elections starting in the next term.
C++
UTF-8
401
2.53125
3
[]
no_license
#pragma once #ifndef __CLOUDS__ #define __CLOUDS__ #include "DisplayObject.h" #include "TextureManager.h" class Clouds final : public DisplayObject { public: Clouds(); ~Clouds(); // Life Cycle Functions void draw() override; void update() override; void clean() override; int getClouds(); void setClouds(int num); private: int m_Clouds; }; #endif // !__CLOUDS__
JavaScript
UTF-8
1,642
2.609375
3
[]
no_license
import React from 'react'; import browserHistory from 'react-router'; class SampleForm extends React.Component{ constructor(props){ super(props); this.state = { firstName: '', lastName: '', status : '' } } handleInputChange = (e) =>{ this.setState({ [e.target.name] : e.target.value }) } handleSubmit = (e)=>{ e.preventDefault(); console.log('clicked'); const data = { 'firstName' : this.state.firstName, 'lastName' : this.state.lastName, 'status' : this.state.status } const fn = this.state.firstName; localStorage.setItem("fn", JSON.stringify(fn)); // console.log(fn); console.log(data); fetch('http://localhost:5000/api/addNewDeck',{ method: 'POST', headers : { 'Accept' : 'application/json', 'Content-Type' : 'application/json' }, body: data }).then((res)=>res.json()) .then((data)=>console.log(data)) .then((err)=>console.log(err)) // let name = localStorage.getItem(fn); // console.log(name); this.props.history.push('/Display'); this.setState({ firstName: '', lastName: '', status: '' }) } render(){ return( <div> <input type="text" value={this.state.firstName} name="firstName" onChange={this.handleInputChange} /><br/> <input type="text" value={this.state.lastName} name="lastName" onChange={this.handleInputChange} /><br/> <input type="text" value={this.state.status} name="status" onChange={this.handleInputChange} /><br/> <button onClick={this.handleSubmit}> Submit </button> </div> ) } } export default SampleForm;
Python
UTF-8
1,128
3.015625
3
[]
no_license
from fractions import gcd import itertools import math class ThePermutationGame: def lcm(self, a, b): return a * b / gcd(a, b) def findMin(self, N): return reduce(self.lcm, range(1, N + 1)) % 1000000007 def rangeLCM(self, last): factors = range(last+1) result = 1 for n in range(1, last+1): print factors if factors[n] > 1: result *= factors[n] for j in range(2*n, last+1, n): factors[j] /= factors[n] return result # CUT begin #------------------------------------------------------------------------------- CASE_TIME_OUT = 2.0; TEST_CASES = [ ( [ 2 ], 2 ), ( [ 3 ], 6 ), ( [ 11 ], 27720 ), ( [ 102 ], 53580071), ( [ 99999], 53580071), #Your custom test goes here: #( [ ], None ), ] def isTestDisabled(i): return False #------------------------------------------------------------------------------- if __name__ == '__main__': import sys, tester tester.run_tests( ThePermutationGame, 'findMin', TEST_CASES, isTestDisabled, 1425913208, 250, CASE_TIME_OUT, tester.COMPACT_REPORT ) # CUT end
Java
UTF-8
1,207
2.21875
2
[]
no_license
package com.mogawe.mosurvei.model.db.entity; import androidx.room.PrimaryKey; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class Product implements Serializable { @PrimaryKey(autoGenerate = true) private int id; @SerializedName(value="uuid") @Expose private String uuid; @SerializedName(value="name") @Expose private String name; @SerializedName(value="icon") @Expose private String icon; private Boolean isChecked; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Boolean getChecked() { return isChecked; } public void setChecked(Boolean checked) { isChecked = checked; } }
Python
UTF-8
984
3.5
4
[]
no_license
"""------------------------------------------------------------------ PyParagraph Mario Vicente Martinez E. 2020-04-13 ------------------------------------------------------------------""" import os, re ofile = input("Please type a filename with extension in Resources Directory ") text = os.path.join("Resources/",ofile) with open (text, encoding = 'utf-8') as p_text: paragraph = p_text.read() word_count = len(paragraph.split()) sentences = re.split("(?<=[.!?]) +", paragraph) sentence_count = len(sentences) letter_count = len(paragraph.replace(" ","")) av_letter_count = round(letter_count / word_count,1) av_sentence_length = word_count / sentence_count print(f"Paragraph Analysis ") print(f"--------------------------------") print(f"Approximate Word count : {word_count}") print(f"Approximate Sentence count : {sentence_count}") print(f"Average Letter count: {av_letter_count}") print(f"Average Sentence length: {av_sentence_length}")
Python
UTF-8
617
2.625
3
[]
no_license
input_data = open('/Users/MaNTi/Desktop/A-large.in') input_data= input_data.read().splitlines() T = int(input_data[0]) f = open('outputlarge.in','w') for each in range(1,T+1): map1 = [0,0,0,0,0,0,0,0,0,0] counter = 1 num = int(input_data[each]) if num ==0: f.write("Case #"+str(each) +': '+ "INSOMNIA"+'\n') continue while sum(map1) < 10: num_temp =num*counter temp = [int(i) for i in str(num_temp)] for n in temp: map1[n] = 1 counter +=1 if sum(map1) >= 10: f.write("Case #"+str(each) +': '+ str(num_temp)+'\n')
Java
UTF-8
358
3.1875
3
[]
no_license
package queue; import java.util.LinkedList; public class Queue<T> { private LinkedList<T> list = new LinkedList<T>(); public void insert(T item) { list.addLast(item); } public T delete() { return list.poll(); } public boolean hasItems() { return !list.isEmpty(); } public int size() { return list.size(); } };
Java
UTF-8
764
1.84375
2
[]
no_license
package gov.hrm.config; import javax.annotation.PostConstruct; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; @Component public class ApplicationStartUp { private Logger log = LogManager.getLogger(); /*@Autowired private CacheSVC cacheSVC;*/ @PostConstruct public void afterApplicationStartUp() { log.debug("*************** Application Startup method execution Start *****************"); // loading config params //loadContextParams(); log.debug("*************** Application Startup method execution End *****************"); } /*private void loadContextParams() { BMUtils.getContextParams(cacheSVC.loadConfigParams()); }*/ }
C
UTF-8
2,107
3.546875
4
[]
no_license
#pragma warning(disable:4996) #include <stdio.h> #include <stdlib.h> #include <string.h> #define true 1 #define false 0 typedef int bool; typedef struct deque { struct deque *prev; struct deque *next; int data; }deque; bool isEmpty(deque *front, deque *rear) { return front == NULL && rear == NULL; } deque* allocNode() { return (deque *)calloc(1, sizeof(deque)); } void addFront(deque **front, deque **rear, int data) { deque *new_node = allocNode(); new_node->next = *front; if (*front == NULL) *rear = new_node; else (*front)->prev = new_node; *front = new_node; new_node->data = data; } void addRear(deque **front, deque **rear, int data) { deque *new_node = allocNode(); new_node->prev = *rear; if (*rear == NULL) *front = new_node; else (*rear)->next = new_node; *rear = new_node; new_node->data = data; } void deleteFront(deque **front, deque **rear) { deque *ptr = (*front); if (*front == *rear) *front = *rear = NULL; else { (*front) = (*front)->next; (*front)->prev = NULL; } free(ptr); } void deleteRear(deque **front, deque **rear) { deque *ptr = (*rear); if (*front == *rear) *front = *rear = NULL; else { (*rear) = (*rear)->prev; (*rear)->next = NULL; } free(ptr); } void printDeque(deque *front, deque *rear) { deque *ptr = front; while (ptr != NULL) { printf(" %d", ptr->data); ptr = ptr->next; } printf("\n"); } int main() { deque *front=NULL, *rear = NULL; int n,data; char op[3]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%s", op); if (strcmp(op, "AF") == 0) { scanf("%d", &data); addFront(&front, &rear, data); } else if (strcmp(op, "AR") == 0) { scanf("%d", &data); addRear(&front, &rear, data); } else if (strcmp(op, "DF") == 0) { if (isEmpty(front, rear)) { printf("underflow"); return -1; } deleteFront(&front, &rear); } else if (strcmp(op, "DR") == 0) { if (isEmpty(front, rear)) { printf("underflow"); return -1; } deleteRear(&front, &rear); } else if(strcmp(op,"P")==0) { printDeque(front, rear); } } }
C++
WINDOWS-1251
1,725
3.359375
3
[]
no_license
#include "pch.h" #include "TRectangle.h" // void TRectangle::setSides(double a, double b) { setA(a); setB(b); } // TRectangle::setSides // void TRectangle::setA(double a) { if (a <= 0) throw exception(" A"); this->a_ = a; } // TRectangle::setA void TRectangle::setB(double b) { if (b <= 0) throw exception(" B"); this->b_ = b; } // TRectangle::setB // void TRectangle::show(const char *title) const { cout << title << fixed << setw(6) << setprecision(3) << a_ << " x " << b_; } // TRectangle::show // istream &operator>>(istream &is, TRectangle &rect) { // - // is >> rect.a_ >> rect.b_; double a, b; is >> a >> b; // rect.setA(a); rect.setB(b); return is; } // // ( friend) ostream &operator<<(ostream &os, const TRectangle &rect) { os << fixed << setw(6) << setprecision(3) << rect.a_ << " x " << rect.b_; return os; } // operator<<
Markdown
UTF-8
6,060
2.890625
3
[ "Apache-2.0" ]
permissive
# Pasargad php-rest-sdk PHP package to connect your application to Pasargad Internet Payment Gateway through RESTful API # Installation For installation, use `composer` package: ```bash $ composer require pepco-api/php-rest-sdk ``` # Usage - To Read API Documentation, [Click Here! (دانلود مستندات کامل درگاه پرداخت)](https://www.pep.co.ir/wp-content/uploads/2019/06/1-__PEP_IPG_REST-13971020.Ver3_.00.pdf) - Save your private key into an `.xml` file inside your project directory. ## Redirect User to Payment Gateway ```php // Use pasargad package use Pasargad\Pasargad; use Pasargad\Classes\PaymentItem; // Always use try catch for handling errors try { // Tip! Initialize this property in your payment service __constructor() method! $pasargad = new Pasargad( "YOUR_MERCHANT_CODE", "YOUR_TERMINAL_ID", "http://yoursite.com/redirect-url-here/", "certificate_file_location"); //e.q: // $pasargad = new Pasargad(123456,555555,"http://pep.co.ir/ipgtest","../cert/cert.xml"); // Set Amount $pasargad->setAmount(100000); // Set Invoice Number (it MUST BE UNIQUE) $pasargad->setInvoiceNumber(4029); // set Invoice Date with below format (Y/m/d H:i:s) $pasargad->setInvoiceDate("2021/08/08 11:54:03"); // Optional Parameters // ---------------------- // User's Mobile and Email: $this->pasargad->setMobile("09121001234"); $this->pasargad->setEmail("user@email.com"); // IF YOU HAVE ACTIVATED "TAS-HIM" (تسهیم پرداخت), ADD SHABA AND PAYMENT SHARING PERCENTAGE/VALUE LIKE THIS: // شروع تسهیم --------------------------------------------- // فقط در صورتیکه قابلیت تسهیم شاپرکی را روی درگاه خود // فعال کرده‌اید از متد addPaymentType استفاده کنید. // تسهیم درصدی ۲۰ به ۸۰: $this->pasargad->addPaymentType("IR300570023980000000000000",PaymentItem::BY_PERCENTAGE, 20); $this->pasargad->addPaymentType("IR070570022080000000000001",PaymentItem::BY_PERCENTAGE, 80); // تسهیم مبلغی: $this->pasargad->addPaymentType("IR300570023980000000000000",PaymentItem::BY_VALUE, 20000); $this->pasargad->addPaymentType("IR070570022080000000000001",PaymentItem::BY_VALUE, 80000); // پایان تسهیم -------------------------------------------- // get the Generated RedirectUrl from Pasargad API: $redirectUrl = $pasargad->redirect(); var_dump($redirectUrl); // output example: https://pep.shaparak.ir/payment.aspx?n=bPo+Z8GLB4oh5W0KVNohihxCu1qBB3kziabGvO1xqg8Y= // and redirect user to payment gateway: return header("Location: $redirectUrl"); // ...or in Laravel/Symfony Controller (Controller extends Symfony\Component\HttpFoundation\Response): return $this->redirect($redirectUrl); } catch (\Exception $ex) { var_dump($ex->getMessage()); die(); } ``` ## Checking and Verifying Transaction After Payment Process, User is going to be returned to your redirect_url. payment gateway is going to answer the payment result with sending below parameters to your redirectURL (as `QueryString` parameters): - InvoiceNumber (IN field) - InvoiceDate (ID field) - TransactionReferenceID (tref field) Store this information in a proper data storage and let's check transaction result by sending a check api request to the Bank: ```php // Set Transaction refrence id received in $pasargad->setTransactionReferenceId("636843820118990203"); // Set Unique Invoice Number that you want to check the result $pasargad->setInvoiceNumber(4029); // set Invoice Date of your Invoice $pasargad->setInvoiceDate("2021/08/08 11:54:03"); // check Transaction result var_dump($pasargad->checkTransaction()); ``` Successful result is a PHP array: ```php $result = [ "TraceNumber" => 908768 "ReferenceNumber" => 141113323710 "TransactionDate" => "2021/09/16 12:08:28" "Action" => "1003" "TransactionReferenceID" => "637673907761796375" "InvoiceNumber" => "40209" "InvoiceDate" => "2021/09/16 11:54:03" "MerchantCode" => 4532980 "TerminalCode" => 1718577 "Amount" => 15000.0 "TrxHashedCardNumber" => "9EB09984BF3F0FDA07D6055997A32F363276D4BD029AE0C870E60DCFC37ED02C" "TrxMaskedCardNumber" => "5022-29**-****-0682" "IsSuccess" => true "Message" => "عمليات به اتمام رسيد" ] ``` If you got `IsSuccess` with `true` value, so everything is O.K! otherwise, you will get an Exception. Now, for your successful transaction, you should call `verifyPayment()` method to keep the money and Bank makes sure the checking process was done properly: ```php // Set Transaction refrence id received in $pasargad->setAmount(15000); // Set Unique Invoice Number that you want to check the result $pasargad->setInvoiceNumber(4029); // set Invoice Date of your Invoice $pasargad->setInvoiceDate("2021/08/08 11:54:03"); // verify payment: return $pasargad->verifyPayment(); ``` ...and the successful response, is an array: ```php $result = [ "MaskedCardNumber" => "5022-29**-****-0682" "HashedCardNumber" => "2DDB1E270C598677AE328AA37C2970E3075E1DB6665C5AAFD131C59F7FAD99F23680536B07C140D24AAD8355EA9725A5493AC48E0F48E39D50B54DB906958182" "ShaparakRefNumber" => "141113323710" "IsSuccess" => true "Message" => "عمليات با موفقيت انجام شد" ] ``` ## Payment Refund If for any reason, you decided to cancel an order in early hours after taking the order (maximum 2 hours later), you can refund the client payment to his/her bank card. for this, use `refundPayment()` method: ```php // Set Unique Invoice Number that you want to check the result $pasargad->setInvoiceNumber(4029); // set Invoice Date of your Invoice $pasargad->setInvoiceDate("2021/08/08 11:54:03"); // check Transaction result return $pasargad->refundPayment(); ``` # Support Please use your credentials to login into [Support Panel](https://my.pep.co.ir) Contact Author/Maintainer: [Reza Seyf](https://twitter.com/seyfcode)
Java
UTF-8
432
1.65625
2
[]
no_license
package vip.bigeye.blog.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import vip.bigeye.blog.vo.Text; import java.io.Serializable; import java.util.List; /** * @Author wolf VX:a815193474 * @Date 2019-08-28 22:28 */ public interface TextDao extends JpaRepository<Text, Serializable> { List<Text> findAll(); Text findByCommentId(String id); }
C++
UTF-8
1,205
2.84375
3
[ "MIT" ]
permissive
/* * PCAssignment.cpp * * Created on: 2012-05-09 * Author: e4k2 */ #include <cstdio> #include "PCAssignment.h" #include "PseudoContact.h" #include "Score.h" #include "NOE.h" PCAssignment::PCAssignment() : noe(0), pc(), score() { } PCAssignment::PCAssignment(NOE* n, const PseudoContact& p, const Score& s) : noe(n), pc(p), score(s) { } PCAssignment::PCAssignment(const PCAssignment& a) : noe(a.noe), pc(a.pc), score(a.score) { } void swap(PCAssignment& first, PCAssignment& second) { std::swap(first.noe,second.noe); swap(first.pc,second.pc); swap(first.score,second.score); } //PCAssignment::PCAssignment(PCAssignment&& a) : noe(0), pc(), score() //{ // swap(*this,a); //} PCAssignment& PCAssignment::operator=(PCAssignment a) { swap(*this,a); return *this; } void PCAssignment::print() const { printf("BEGIN ASSIGNMENT\n"); noe->print(); pc.print(); score.print(); printf("END ASSIGNMENT\n"); } PCAssignment::~PCAssignment() { } bool PCAssignment::operator==(const PCAssignment& a) const { return noe == a.noe && pc == a.pc; } bool PCAssignment::operator!=(const PCAssignment& a) const { return !(*this == a); } void PCAssignment::setReversePC() { pc.setReverse(); }
C++
UTF-8
598
3.03125
3
[ "MIT" ]
permissive
#pragma once #include "BaseExercise.h" // abstract class definition for Cardio. Inherits from BaseExercise class Cardio : public BaseExercise { public: // Cardio class constructor Cardio(double time, double dist, double lbs); // procedure to set distance void setDistance(double dist); // procedure to set speed void setSpeed(double rate); // function to return distance double getDistance(); // function to return speed double getSpeed(); // virtual fuction for calculating rate virtual void calcSpeed() = 0; private: // provate data memebers double distance; double speed; };
Java
UTF-8
1,951
3.515625
4
[]
no_license
package net.bishnu.leetcode.wordSquares; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * 425. Word Squares * https://leetcode.com/problems/word-squares/#/description * Created by karlb on 2017-04-02. */ public class WordSquares { private class Node{ List<String> word = new LinkedList<>(); Node[] nodes = new Node['z'-'a'+1]; } public List<List<String>> wordSquares(String[] words){ List<List<String>> result = new LinkedList<>(); Node root = buildStatusTree(words); for(String word: words){ List<String> strings = new ArrayList<>(words.length); strings.add(word); search(strings, root, result); } return result; } private void search(List<String> strings, Node root, List<List<String>> result) { int size = strings.size(); if(size==strings.get(0).length()){ result.add(new ArrayList<>(strings)); return; } Node curr = root; for(int i=0; i< strings.size(); i++){ char aChar = strings.get(i).charAt(size); int index = aChar - 'a'; if(curr.nodes[index] == null) return; curr = curr.nodes[index]; } for(String word: curr.word){ strings.add(word); search(strings, root, result); strings.remove(strings.size()-1); } } private Node buildStatusTree(String[] words) { Node root = new Node(); for(int i=0; i<words.length; i++){ String word = words[i]; Node curr = root; for(int j=0; j<word.length(); j++){ int index = word.charAt(j)-'a'; if(curr.nodes[index] == null) curr.nodes[index] = new Node(); curr.word.add(word); curr = curr.nodes[index]; } } return root; } }
C++
UTF-8
1,222
2.84375
3
[]
no_license
#ifndef LAZOR_H #define LAZOR_H #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include "GameObject.hpp" #include "Texture.hpp" class Lazor: public GameObject { double frame; glm::vec3 direction; bool isDescending; float speed; public: size_t getTextureIndex() { return (size_t)frame; } Lazor(glm::mat4 orientation, glm::vec3 direction, Mesh* mesh) : GameObject(mesh) { this->orientation = orientation * glm::translate(glm::vec3(1.5f, 0.0f, 0.0f)) * glm::rotate(90.0f, glm::vec3(1.0f, 0.0f, 0.0f)); this->direction = direction; isDescending = true; speed = 3.0f; frame = 2.0f; } void update(float time) { // Laser animation if(!isDescending) { frame += time * 10.0f; if(frame > 3.0f) { isDescending = true; frame = 2.99; } } else { frame -= time * 10.0f; if(frame < 0){ isDescending = false; frame = 0.0f; } } orientation = glm::translate(direction*time*speed) * orientation; } }; #endif // LAZOR_H
Java
UTF-8
36,645
1.890625
2
[ "MIT" ]
permissive
package de.tum.in.www1.artemis.programmingexercise; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.time.ZonedDateTime; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import org.eclipse.jgit.lib.ObjectId; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest; import de.tum.in.www1.artemis.config.Constants; import de.tum.in.www1.artemis.domain.*; import de.tum.in.www1.artemis.domain.enumeration.AssessmentType; import de.tum.in.www1.artemis.domain.enumeration.FeedbackType; import de.tum.in.www1.artemis.repository.*; import de.tum.in.www1.artemis.service.ProgrammingExerciseService; import de.tum.in.www1.artemis.service.ProgrammingExerciseTestCaseService; import de.tum.in.www1.artemis.util.DatabaseUtilService; import de.tum.in.www1.artemis.util.ModelFactory; import de.tum.in.www1.artemis.web.rest.dto.ProgrammingExerciseTestCaseDTO; public class ProgrammingExerciseTestCaseServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest { @Autowired ProgrammingSubmissionRepository programmingSubmissionRepository; @Autowired ProgrammingExerciseStudentParticipationRepository programmingExerciseStudentParticipationRepository; @Autowired ProgrammingExerciseTestCaseRepository testCaseRepository; @Autowired ParticipationRepository participationRepository; @Autowired StudentParticipationRepository studentParticipationRepository; @Autowired ResultRepository resultRepository; @Autowired ProgrammingExerciseTestCaseService testCaseService; @Autowired ProgrammingExerciseService programmingExerciseService; @Autowired ProgrammingExerciseRepository programmingExerciseRepository; @Autowired DatabaseUtilService database; private ProgrammingExercise programmingExercise; private Result result; @BeforeEach public void setUp() { database.addUsers(5, 1, 0); database.addCourseWithOneProgrammingExerciseAndTestCases(); result = new Result(); var programmingExercises = programmingExerciseRepository.findAllWithEagerTemplateAndSolutionParticipations(); programmingExercise = programmingExercises.get(0); bambooRequestMockProvider.enableMockingOfRequests(); } @AfterEach public void tearDown() { database.resetDatabase(); bambooRequestMockProvider.reset(); } @Test public void shouldSetAllTestCasesToInactiveIfFeedbackListIsEmpty() { List<Feedback> feedbacks = new ArrayList<>(); testCaseService.generateTestCasesFromFeedbacks(feedbacks, programmingExercise); Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId()); assertThat(testCases).hasSize(3); assertThat(testCases.stream().noneMatch(ProgrammingExerciseTestCase::isActive)).isTrue(); } @Test public void shouldUpdateActiveFlagsOfTestCases() { List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1")); feedbacks.add(new Feedback().text("test2")); feedbacks.add(new Feedback().text("test4")); feedbacks.add(new Feedback().text("test5")); testCaseService.generateTestCasesFromFeedbacks(feedbacks, programmingExercise); Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId()); assertThat(testCases).hasSize(5); assertThat(testCases.stream().allMatch(testCase -> { if (testCase.getTestName().equals("test3")) { return !testCase.isActive(); } else { return testCase.isActive(); } })).isTrue(); } @Test public void shouldGenerateNewTestCases() { testCaseRepository.deleteAll(); List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1")); feedbacks.add(new Feedback().text("test2")); testCaseService.generateTestCasesFromFeedbacks(feedbacks, programmingExercise); Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId()); assertThat(testCases).hasSize(2); assertThat(testCases.stream().allMatch(ProgrammingExerciseTestCase::isActive)).isTrue(); } @Test public void shouldNotGenerateNewTestCasesForStaticCodeAnalysisFeedback() { testCaseRepository.deleteAll(); List<Feedback> feedbackList = ModelFactory.generateStaticCodeAnalysisFeedbackList(5); testCaseService.generateTestCasesFromFeedbacks(feedbackList, programmingExercise); Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId()); assertThat(testCases).hasSize(0); } @Test public void shouldResetTestWeights() throws Exception { String dummyHash = "9b3a9bd71a0d80e5bbc42204c319ed3d1d4f0d6d"; when(gitService.getLastCommitHash(ArgumentMatchers.any())).thenReturn(ObjectId.fromString(dummyHash)); database.addProgrammingParticipationWithResultForExercise(programmingExercise, "student1"); new ArrayList<>(testCaseRepository.findByExerciseId(programmingExercise.getId())).get(0).weight(50.0); bambooRequestMockProvider.mockTriggerBuild(programmingExercise.getSolutionParticipation()); assertThat(programmingExercise.getTestCasesChanged()).isFalse(); testCaseService.reset(programmingExercise.getId()); Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId()); ProgrammingExercise updatedProgrammingExercise = programmingExerciseRepository.findWithTemplateParticipationAndSolutionParticipationById(programmingExercise.getId()).get(); assertThat(testCases.stream().mapToDouble(ProgrammingExerciseTestCase::getWeight).sum()).isEqualTo(testCases.size()); assertThat(updatedProgrammingExercise.getTestCasesChanged()).isTrue(); verify(groupNotificationService, times(1)).notifyInstructorGroupAboutExerciseUpdate(updatedProgrammingExercise, Constants.TEST_CASES_CHANGED_NOTIFICATION); verify(websocketMessagingService, times(1)).sendMessage("/topic/programming-exercises/" + programmingExercise.getId() + "/test-cases-changed", true); // After a test case update, the solution repository should be build, so the ContinuousIntegrationService needs to be triggered and a submission created. List<ProgrammingSubmission> submissions = programmingSubmissionRepository.findAll(); assertThat(submissions).hasSize(1); assertThat(submissions.get(0).getCommitHash()).isEqualTo(dummyHash); } @Test @WithMockUser(value = "tutor1", roles = "TA") public void shouldUpdateTestWeight() throws Exception { bambooRequestMockProvider.mockTriggerBuild(programmingExercise.getSolutionParticipation()); String dummyHash = "9b3a9bd71a0d80e5bbc42204c319ed3d1d4f0d6d"; doReturn(ObjectId.fromString(dummyHash)).when(gitService).getLastCommitHash(any()); database.addProgrammingParticipationWithResultForExercise(programmingExercise, "student1"); ProgrammingExerciseTestCase testCase = testCaseRepository.findAll().get(0); Set<ProgrammingExerciseTestCaseDTO> programmingExerciseTestCaseDTOS = new HashSet<>(); ProgrammingExerciseTestCaseDTO programmingExerciseTestCaseDTO = new ProgrammingExerciseTestCaseDTO(); programmingExerciseTestCaseDTO.setId(testCase.getId()); programmingExerciseTestCaseDTO.setWeight(400.0); programmingExerciseTestCaseDTOS.add(programmingExerciseTestCaseDTO); assertThat(programmingExercise.getTestCasesChanged()).isFalse(); testCaseService.update(programmingExercise.getId(), programmingExerciseTestCaseDTOS); ProgrammingExercise updatedProgrammingExercise = programmingExerciseRepository.findWithTemplateParticipationAndSolutionParticipationById(programmingExercise.getId()).get(); assertThat(testCaseRepository.findById(testCase.getId()).get().getWeight()).isEqualTo(400); assertThat(updatedProgrammingExercise.getTestCasesChanged()).isTrue(); verify(groupNotificationService, times(1)).notifyInstructorGroupAboutExerciseUpdate(updatedProgrammingExercise, Constants.TEST_CASES_CHANGED_NOTIFICATION); verify(websocketMessagingService, times(1)).sendMessage("/topic/programming-exercises/" + programmingExercise.getId() + "/test-cases-changed", true); // After a test case update, the solution repository should be build, so the ContinuousIntegrationService needs to be triggered and a submission created. List<ProgrammingSubmission> submissions = programmingSubmissionRepository.findAll(); assertThat(submissions).hasSize(1); assertThat(submissions.get(0).getCommitHash()).isEqualTo(dummyHash); } @Test public void shouldNotUpdateResultIfNoTestCasesExist() { testCaseRepository.deleteAll(); Long scoreBeforeUpdate = result.getScore(); testCaseService.updateResultFromTestCases(result, programmingExercise, true); assertThat(result.getScore()).isEqualTo(scoreBeforeUpdate); } @Test public void shouldRecalculateScoreBasedOnTestCasesWeight() { List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test2").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test3").positive(false).type(FeedbackType.AUTOMATIC)); result.feedbacks(feedbacks); result.successful(false); Long scoreBeforeUpdate = result.getScore(); testCaseService.updateResultFromTestCases(result, programmingExercise, true); Long expectedScore = 25L; assertThat(scoreBeforeUpdate).isNotEqualTo(result.getScore()); assertThat(result.getScore()).isEqualTo(expectedScore); assertThat(result.isSuccessful()).isFalse(); } @Test public void shouldRecalculateScoreWithTestCaseBonusButNoExerciseBonus() { // Set up test cases with bonus var testCases = testCaseService.findByExerciseId(programmingExercise.getId()).stream() .collect(Collectors.toMap(ProgrammingExerciseTestCase::getTestName, Function.identity())); testCases.get("test1").active(true).afterDueDate(false).weight(5.).bonusMultiplier(1D).setBonusPoints(7D); testCases.get("test2").active(true).afterDueDate(false).weight(2.).bonusMultiplier(2D).setBonusPoints(0D); testCases.get("test3").active(true).afterDueDate(false).weight(3.).bonusMultiplier(1D).setBonusPoints(10.5D); testCaseRepository.saveAll(testCases.values()); var result1 = new Result(); result1 = updateAndSaveAutomaticResult(result1, false, false, true); var result2 = new Result(); result2 = updateAndSaveAutomaticResult(result2, true, false, false); var result3 = new Result(); result3 = updateAndSaveAutomaticResult(result3, false, true, false); var result4 = new Result(); result4 = updateAndSaveAutomaticResult(result4, false, true, true); var result5 = new Result(); result5 = updateAndSaveAutomaticResult(result5, true, true, true); var result6 = new Result(); result6 = updateAndSaveAutomaticResult(result6, false, false, false); // Build failure var resultBF = new Result().feedbacks(List.of()).rated(true).score(0L).hasFeedback(false).resultString("Build Failed").completionDate(ZonedDateTime.now()) .assessmentType(AssessmentType.AUTOMATIC); testCaseService.updateResultFromTestCases(resultBF, programmingExercise, true); // Missing feedback var resultMF = new Result(); var feedbackMF = new Feedback().result(result).text("test3").positive(true).type(FeedbackType.AUTOMATIC).result(resultMF); resultMF.feedbacks(new ArrayList<>(List.of(feedbackMF))) // List must be mutable .rated(true).score(0L).hasFeedback(true).completionDate(ZonedDateTime.now()).assessmentType(AssessmentType.AUTOMATIC); testCaseService.updateResultFromTestCases(resultMF, programmingExercise, true); // Assertions result1 - calculated assertThat(result1.getScore()).isEqualTo(55L); assertThat(result1.getResultString()).isEqualTo("1 of 3 passed"); assertThat(result1.getHasFeedback()).isTrue(); assertThat(result1.isSuccessful()).isFalse(); assertThat(result1.getFeedbacks()).hasSize(3); // Assertions result2 - calculated assertThat(result2.getScore()).isEqualTo(66L); assertThat(result2.getResultString()).isEqualTo("1 of 3 passed"); assertThat(result2.getHasFeedback()).isTrue(); assertThat(result2.isSuccessful()).isFalse(); assertThat(result2.getFeedbacks()).hasSize(3); // Assertions result3 - calculated assertThat(result3.getScore()).isEqualTo(40L); assertThat(result3.getResultString()).isEqualTo("1 of 3 passed"); assertThat(result3.getHasFeedback()).isTrue(); assertThat(result3.isSuccessful()).isFalse(); assertThat(result3.getFeedbacks()).hasSize(3); // Assertions result4 - calculated assertThat(result4.getScore()).isEqualTo(95L); assertThat(result4.getResultString()).isEqualTo("2 of 3 passed"); assertThat(result4.getHasFeedback()).isTrue(); assertThat(result4.isSuccessful()).isFalse(); assertThat(result4.getFeedbacks()).hasSize(3); // Assertions result5 - capped to 100 assertThat(result5.getScore()).isEqualTo(100L); assertThat(result5.getResultString()).isEqualTo("3 of 3 passed"); assertThat(result5.getHasFeedback()).isFalse(); assertThat(result5.isSuccessful()).isTrue(); assertThat(result5.getFeedbacks()).hasSize(3); // Assertions result6 - only negative feedback assertThat(result6.getScore()).isEqualTo(0L); assertThat(result6.getResultString()).isEqualTo("0 of 3 passed"); assertThat(result6.getHasFeedback()).isTrue(); assertThat(result6.isSuccessful()).isFalse(); assertThat(result6.getFeedbacks()).hasSize(3); // Assertions resultBF - build failure assertThat(resultBF.getScore()).isEqualTo(0L); assertThat(resultBF.getResultString()).isEqualTo("Build Failed"); // Won't get touched by the service method assertThat(resultBF.getHasFeedback()).isFalse(); assertThat(resultBF.isSuccessful()).isNull(); // Won't get touched by the service method assertThat(resultBF.getFeedbacks()).hasSize(0); // Assertions resultMF - missing feedback will be created but is negative assertThat(resultMF.getScore()).isEqualTo(55L); assertThat(resultMF.getResultString()).isEqualTo("1 of 3 passed"); assertThat(resultMF.getHasFeedback()).isFalse(); // Generated missing feedback is omitted assertThat(resultMF.isSuccessful()).isFalse(); assertThat(resultMF.getFeedbacks()).hasSize(3); // Feedback is created for test cases if missing } @Test public void shouldRecalculateScoreWithTestCaseBonusAndExerciseBonus() { // Set up test cases with bonus var testCases = testCaseService.findByExerciseId(programmingExercise.getId()).stream() .collect(Collectors.toMap(ProgrammingExerciseTestCase::getTestName, Function.identity())); testCases.get("test1").active(true).afterDueDate(false).weight(4.).bonusMultiplier(1D).setBonusPoints(0D); testCases.get("test2").active(true).afterDueDate(false).weight(3.).bonusMultiplier(3D).setBonusPoints(21D); testCases.get("test3").active(true).afterDueDate(false).weight(3.).bonusMultiplier(2D).setBonusPoints(14D); testCaseRepository.saveAll(testCases.values()); // Score should be capped at 200% programmingExercise.setBonusPoints(programmingExercise.getMaxScore()); programmingExerciseRepository.save(programmingExercise); var result1 = new Result(); result1 = updateAndSaveAutomaticResult(result1, false, false, true); var result2 = new Result(); result2 = updateAndSaveAutomaticResult(result2, true, false, true); var result3 = new Result(); result3 = updateAndSaveAutomaticResult(result3, true, true, false); var result4 = new Result(); result4 = updateAndSaveAutomaticResult(result4, false, true, true); // Assertions result1 - calculated assertThat(result1.getScore()).isEqualTo(93L); assertThat(result1.getResultString()).isEqualTo("1 of 3 passed"); assertThat(result1.getHasFeedback()).isTrue(); assertThat(result1.isSuccessful()).isFalse(); assertThat(result1.getFeedbacks()).hasSize(3); // Assertions result2 - calculated assertThat(result2.getScore()).isEqualTo(133L); assertThat(result2.getResultString()).isEqualTo("2 of 3 passed"); assertThat(result2.getHasFeedback()).isTrue(); assertThat(result2.isSuccessful()).isTrue(); assertThat(result2.getFeedbacks()).hasSize(3); // Assertions result3 - calculated assertThat(result3.getScore()).isEqualTo(180L); assertThat(result3.getResultString()).isEqualTo("2 of 3 passed"); assertThat(result3.getHasFeedback()).isTrue(); assertThat(result3.isSuccessful()).isTrue(); assertThat(result3.getFeedbacks()).hasSize(3); // Assertions result4 - capped at 200% assertThat(result4.getScore()).isEqualTo(200L); assertThat(result4.getResultString()).isEqualTo("2 of 3 passed"); assertThat(result4.getHasFeedback()).isTrue(); assertThat(result4.isSuccessful()).isTrue(); assertThat(result4.getFeedbacks()).hasSize(3); } @Test public void shouldRemoveTestsWithAfterDueDateFlagIfDueDateHasNotPassed() { // Set programming exercise due date in future. programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusHours(10)); List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test2").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test3").positive(false).type(FeedbackType.AUTOMATIC)); result.feedbacks(feedbacks); result.successful(false); Long scoreBeforeUpdate = result.getScore(); testCaseService.updateResultFromTestCases(result, programmingExercise, true); // All available test cases are fulfilled, however there are more test cases that will be run after due date. Long expectedScore = 25L; assertThat(scoreBeforeUpdate).isNotEqualTo(result.getScore()); assertThat(result.getScore()).isEqualTo(expectedScore); assertThat(result.getResultString()).isEqualTo("1 of 1 passed"); assertThat(result.isSuccessful()).isFalse(); // The feedback of the after due date test case must be removed. assertThat(result.getFeedbacks().stream().noneMatch(feedback -> feedback.getText().equals("test3"))).isEqualTo(true); } @Test public void shouldNotRemoveTestsWithAfterDueDateFlagIfDueDateHasNotPassedForNonStudentParticipation() { // Set programming exercise due date in future. programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusHours(10)); List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test2").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test3").positive(false).type(FeedbackType.AUTOMATIC)); result.feedbacks(feedbacks); result.successful(false); Long scoreBeforeUpdate = result.getScore(); testCaseService.updateResultFromTestCases(result, programmingExercise, false); // All available test cases are fulfilled. Long expectedScore = 25L; assertThat(scoreBeforeUpdate).isNotEqualTo(result.getScore()); assertThat(result.getResultString()).isEqualTo("1 of 2 passed"); assertThat(result.getScore()).isEqualTo(expectedScore); assertThat(result.isSuccessful()).isFalse(); assertThat(result.getFeedbacks()).hasSize(2); } @Test public void shouldKeepTestsWithAfterDueDateFlagIfDueDateHasPassed() { // Set programming exercise due date in past. programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().minusHours(10)); List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test2").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test3").positive(false).type(FeedbackType.AUTOMATIC)); result.feedbacks(feedbacks); result.successful(false); Long scoreBeforeUpdate = result.getScore(); testCaseService.updateResultFromTestCases(result, programmingExercise, true); // All available test cases are fulfilled. Long expectedScore = 25L; assertThat(scoreBeforeUpdate).isNotEqualTo(result.getScore()); assertThat(result.getResultString()).isEqualTo("1 of 2 passed"); assertThat(result.getScore()).isEqualTo(expectedScore); assertThat(result.isSuccessful()).isFalse(); // The feedback of the after due date test case must be kept. assertThat(result.getFeedbacks().stream().noneMatch(feedback -> feedback.getText().equals("test3"))).isEqualTo(false); } @Test public void shouldGenerateZeroScoreIfThereAreNoTestCasesBeforeDueDate() { // Set programming exercise due date in future. programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusHours(10)); List<Feedback> feedbacks = new ArrayList<>(); feedbacks.add(new Feedback().text("test1").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test2").positive(true).type(FeedbackType.AUTOMATIC)); feedbacks.add(new Feedback().text("test3").positive(false).type(FeedbackType.AUTOMATIC)); result.feedbacks(feedbacks); result.successful(false); Long scoreBeforeUpdate = result.getScore(); // Set all test cases of the programming exercise to be executed after due date. Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId()); for (ProgrammingExerciseTestCase testCase : testCases) { testCase.setAfterDueDate(true); } testCaseRepository.saveAll(testCases); testCaseService.updateResultFromTestCases(result, programmingExercise, true); // No test case was executed. Long expectedScore = 0L; assertThat(scoreBeforeUpdate).isNotEqualTo(result.getScore()); assertThat(result.getResultString()).isEqualTo("0 of 0 passed"); assertThat(result.getScore()).isEqualTo(expectedScore); assertThat(result.isSuccessful()).isFalse(); // The feedback must be empty as not test should be executed yet. assertThat(result.getFeedbacks()).hasSize(0); } @Test @WithMockUser(value = "instructor1", roles = "INSTRUCTOR") public void shouldReEvaluateScoreOfTheCorrectResults() { programmingExercise = database.addTemplateParticipationForProgrammingExercise(programmingExercise); programmingExercise = database.addSolutionParticipationForProgrammingExercise(programmingExercise); programmingExercise = programmingExerciseService.findWithTemplateAndSolutionParticipationWithResultsById(programmingExercise.getId()); var testCases = testCaseService.findByExerciseId(programmingExercise.getId()).stream() .collect(Collectors.toMap(ProgrammingExerciseTestCase::getTestName, Function.identity())); testCases.get("test1").active(true).afterDueDate(false).setWeight(1.); testCases.get("test2").active(true).afterDueDate(false).setWeight(1.); testCases.get("test3").active(true).afterDueDate(false).setWeight(2.); testCaseRepository.saveAll(testCases.values()); // template does not pass any tests var participationTemplate = programmingExercise.getTemplateParticipation(); { // score 0 % var resultTemplate = new Result().participation(participationTemplate).resultString("x of y passed").successful(false).rated(true).score(100L); participationTemplate.setResults(Set.of(resultTemplate)); resultTemplate = updateAndSaveAutomaticResult(resultTemplate, false, false, false); } // solution passes most tests but is still faulty var participationSolution = programmingExercise.getSolutionParticipation(); { // score 75 % var resultSolution = new Result().participation(participationSolution).resultString("x of y passed").successful(false).rated(true).score(100L); participationSolution.setResults(Set.of(resultSolution)); resultSolution = updateAndSaveAutomaticResult(resultSolution, false, true, true); } // student1 only has one automatic result var participation1 = database.addStudentParticipationForProgrammingExercise(programmingExercise, "student1"); { // score 50 % var result1 = new Result().participation(participation1).resultString("x of y passed").successful(false).rated(true).score(100L); participation1.setResults(Set.of(result1)); result1 = updateAndSaveAutomaticResult(result1, true, true, false); } // student2 has an automatic result and a manual result as well var participation2 = database.addStudentParticipationForProgrammingExercise(programmingExercise, "student2"); { // score 75 % var result2a = new Result().participation(participation2).resultString("x of y passed").successful(false).rated(true).score(100L); result2a = updateAndSaveAutomaticResult(result2a, true, false, true); // score 100 % var result2b = new Result().participation(participation2).resultString("nice job").successful(false).rated(true).score(100L); result2b.feedbacks(List.of(new Feedback().text("Well done!").positive(true).type(FeedbackType.MANUAL))) // .score(100L) // .rated(true) // .hasFeedback(true) // .successful(true) // .completionDate(ZonedDateTime.now()) // .assessmentType(AssessmentType.MANUAL); result2b = resultRepository.save(result2b); participation2.setResults(Set.of(result2a, result2b)); } // student3 only started the exercise, but did not submit anything var participation3 = database.addStudentParticipationForProgrammingExercise(programmingExercise, "student3"); // student4 only has one automatic result var participation4 = database.addStudentParticipationForProgrammingExercise(programmingExercise, "student4"); { // score 100 % var result4 = new Result().participation(participation4).resultString("x of y passed").successful(false).rated(true).score(100L); result4 = updateAndSaveAutomaticResult(result4, true, true, true); participation4.setResults(Set.of(result4)); } // student5 has a build failure var participation5 = database.addStudentParticipationForProgrammingExercise(programmingExercise, "student5"); { // Build Failed var result5 = new Result().participation(participation5) // .feedbacks(List.of()) // .score(0L) // .resultString("Build Failed") // .rated(true) // .hasFeedback(false) // .successful(false) // .completionDate(ZonedDateTime.now()) // .assessmentType(AssessmentType.AUTOMATIC); testCaseService.updateResultFromTestCases(result5, programmingExercise, true); result5 = resultRepository.save(result5); participation5.setResults(Set.of(result5)); } // change test case weights testCases.get("test1").setWeight(0.); testCases.get("test2").setWeight(1.); testCases.get("test3").setWeight(3.); testCaseRepository.saveAll(testCases.values()); // TODO: we should instead invoke the REST call here // re-evaluate var updatedResults = testCaseService.updateAllResultsFromTestCases(programmingExercise); resultRepository.saveAll(updatedResults); // Tests programmingExercise = programmingExerciseService.findWithTemplateAndSolutionParticipationWithResultsById(programmingExercise.getId()); // template 0 % { var participation = programmingExercise.getTemplateParticipation(); var results = participation.getResults(); assertThat(results).hasSize(1); var singleResult = results.iterator().next(); assertThat(singleResult.getScore()).isEqualTo(0L); assertThat(singleResult.getResultString()).isEqualTo("0 of 3 passed"); assertThat(singleResult.getHasFeedback()).isTrue(); assertThat(singleResult.getFeedbacks()).hasSize(3); assertThat(singleResult.getAssessmentType()).isEqualTo(AssessmentType.AUTOMATIC); assertThat(singleResult).isEqualTo(participation.findLatestResult()); } // solution 100 % { var participation = programmingExercise.getSolutionParticipation(); var results = participation.getResults(); assertThat(results).hasSize(1); var singleResult = results.iterator().next(); assertThat(singleResult.getScore()).isEqualTo(100L); assertThat(singleResult.getResultString()).isEqualTo("2 of 3 passed"); assertThat(singleResult.getHasFeedback()).isTrue(); assertThat(singleResult.getFeedbacks()).hasSize(3); assertThat(singleResult.getAssessmentType()).isEqualTo(AssessmentType.AUTOMATIC); assertThat(singleResult).isEqualTo(participation.findLatestResult()); } // student1 25 % { var participation = studentParticipationRepository.findWithEagerResultsAndFeedbackById(participation1.getId()).get(); var results = participation.getResults(); assertThat(results).hasSize(1); var singleResult = results.iterator().next(); assertThat(singleResult.getScore()).isEqualTo(25L); assertThat(singleResult.getResultString()).isEqualTo("2 of 3 passed"); assertThat(singleResult.getHasFeedback()).isTrue(); assertThat(singleResult.getFeedbacks()).hasSize(3); assertThat(singleResult.getAssessmentType()).isEqualTo(AssessmentType.AUTOMATIC); assertThat(singleResult).isEqualTo(participation.findLatestResult()); } // student2 100 % / 75 % { var participation = studentParticipationRepository.findWithEagerResultsAndFeedbackById(participation2.getId()).get(); var results = participation.getResults(); assertThat(results).hasSize(2); var manualResultOptional = results.stream().filter(result -> result.getAssessmentType() == AssessmentType.MANUAL).findAny(); assertThat(manualResultOptional).isPresent(); var manualResult = manualResultOptional.get(); assertThat(manualResult.getScore()).isEqualTo(100L); assertThat(manualResult.getResultString()).isEqualTo("nice job"); assertThat(manualResult.getHasFeedback()).isTrue(); assertThat(manualResult.getFeedbacks()).hasSize(0); assertThat(manualResult).isEqualTo(participation.findLatestResult()); var automaticResultOptional = results.stream().filter(result -> result.getAssessmentType() == AssessmentType.AUTOMATIC).findAny(); assertThat(automaticResultOptional).isPresent(); var automaticResult = automaticResultOptional.get(); assertThat(automaticResult.getScore()).isEqualTo(75L); assertThat(automaticResult.getResultString()).isEqualTo("2 of 3 passed"); assertThat(manualResult.getHasFeedback()).isTrue(); assertThat(automaticResult.getFeedbacks()).hasSize(3); } // student3 no result { var participation = studentParticipationRepository.findWithEagerResultsAndFeedbackById(participation3.getId()).get(); var results = participation.getResults(); assertThat(results).isNullOrEmpty(); assertThat(participation.findLatestResult()).isNull(); } // student4 100% { var participation = studentParticipationRepository.findWithEagerResultsAndFeedbackById(participation4.getId()).get(); var results = participation.getResults(); assertThat(results).hasSize(1); var singleResult = results.iterator().next(); assertThat(singleResult.getScore()).isEqualTo(100L); assertThat(singleResult.getResultString()).isEqualTo("3 of 3 passed"); assertThat(singleResult.getHasFeedback()).isFalse(); assertThat(singleResult.getFeedbacks()).hasSize(3); assertThat(singleResult.getAssessmentType()).isEqualTo(AssessmentType.AUTOMATIC); assertThat(singleResult).isEqualTo(participation.findLatestResult()); } // student5 Build Failed { var participation = studentParticipationRepository.findWithEagerResultsAndFeedbackById(participation5.getId()).get(); var results = participation.getResults(); assertThat(results).hasSize(1); var singleResult = results.iterator().next(); assertThat(singleResult.getScore()).isEqualTo(0L); assertThat(singleResult.getResultString()).isEqualTo("Build Failed"); assertThat(singleResult.getHasFeedback()).isFalse(); assertThat(singleResult.getFeedbacks()).isEmpty(); assertThat(singleResult.getAssessmentType()).isEqualTo(AssessmentType.AUTOMATIC); assertThat(singleResult).isEqualTo(participation.findLatestResult()); } } private Result updateAndSaveAutomaticResult(Result result, boolean test1Passes, boolean test2Passes, boolean test3Passes) { var feedback1 = new Feedback().result(result).text("test1").positive(test1Passes).type(FeedbackType.AUTOMATIC); result.addFeedback(feedback1); var feedback2 = new Feedback().result(result).text("test2").positive(test2Passes).type(FeedbackType.AUTOMATIC); result.addFeedback(feedback2); var feedback3 = new Feedback().result(result).text("test3").positive(test3Passes).type(FeedbackType.AUTOMATIC); result.addFeedback(feedback3); result.rated(true) // .hasFeedback(true) // .successful(test1Passes && test2Passes && test3Passes) // .completionDate(ZonedDateTime.now()) // .assessmentType(AssessmentType.AUTOMATIC); testCaseService.updateResultFromTestCases(result, programmingExercise, true); return resultRepository.save(result); } }
Java
UTF-8
465
3.453125
3
[]
no_license
package basics; public class Selection_Sort { public static void main(String[] args) { int[] arr= {11,2,3,4,5,6}; for(int i=0;i<arr.length;i++) { int min=i; for(int j=i+1;j<arr.length;j++) { if(arr[j]<arr[min]) { min=j; } } int temp=arr[min]; arr[min]=arr[i]; arr[i]=temp; } System.out.println("Array Sorted using selection sort!!"); for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
Shell
UTF-8
221
3.0625
3
[ "MIT" ]
permissive
#!/bin/bash minimumMem=400 while true; do totalk=$(awk '/^MemFree:/{print $2}' /proc/meminfo) if [ "$totalk" -lt "$minimumMem" ] then bash /root/tma/scripts/parse_files.sh fi sleep 30 done
PHP
UTF-8
8,192
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php declare(strict_types=1); namespace Endroid\QrCode\Builder; use Endroid\QrCode\Color\ColorInterface; use Endroid\QrCode\Encoding\EncodingInterface; use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelInterface; use Endroid\QrCode\Exception\ValidationException; use Endroid\QrCode\Label\Alignment\LabelAlignmentInterface; use Endroid\QrCode\Label\Font\FontInterface; use Endroid\QrCode\Label\Label; use Endroid\QrCode\Label\LabelInterface; use Endroid\QrCode\Label\Margin\MarginInterface; use Endroid\QrCode\Logo\Logo; use Endroid\QrCode\Logo\LogoInterface; use Endroid\QrCode\QrCode; use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeInterface; use Endroid\QrCode\Writer\PngWriter; use Endroid\QrCode\Writer\Result\ResultInterface; use Endroid\QrCode\Writer\ValidatingWriterInterface; use Endroid\QrCode\Writer\WriterInterface; class Builder implements BuilderInterface { /** * @var array<string, mixed>{ * data: string, * writer: WriterInterface, * writerOptions: array, * qrCodeClass: class-string, * logoClass: class-string, * labelClass: class-string, * validateResult: bool, * size?: int, * encoding?: EncodingInterface, * errorCorrectionLevel?: ErrorCorrectionLevelInterface, * roundBlockSizeMode?: RoundBlockSizeModeInterface, * margin?: int, * backgroundColor?: ColorInterface, * foregroundColor?: ColorInterface, * labelText?: string, * labelFont?: FontInterface, * labelAlignment?: LabelAlignmentInterface, * labelMargin?: MarginInterface, * labelTextColor?: ColorInterface, * logoPath?: string, * logoResizeToWidth?: int, * logoResizeToHeight?: int, * logoPunchoutBackground?: bool * } */ private array $options; public function __construct() { $this->options = [ 'data' => '', 'writer' => new PngWriter(), 'writerOptions' => [], 'qrCodeClass' => QrCode::class, 'logoClass' => Logo::class, 'labelClass' => Label::class, 'validateResult' => false, ]; } public static function create(): BuilderInterface { return new self(); } public function writer(WriterInterface $writer): BuilderInterface { $this->options['writer'] = $writer; return $this; } /** @param array<string, mixed> $writerOptions */ public function writerOptions(array $writerOptions): BuilderInterface { $this->options['writerOptions'] = $writerOptions; return $this; } public function data(string $data): BuilderInterface { $this->options['data'] = $data; return $this; } public function encoding(EncodingInterface $encoding): BuilderInterface { $this->options['encoding'] = $encoding; return $this; } public function errorCorrectionLevel(ErrorCorrectionLevelInterface $errorCorrectionLevel): BuilderInterface { $this->options['errorCorrectionLevel'] = $errorCorrectionLevel; return $this; } public function size(int $size): BuilderInterface { $this->options['size'] = $size; return $this; } public function margin(int $margin): BuilderInterface { $this->options['margin'] = $margin; return $this; } public function roundBlockSizeMode(RoundBlockSizeModeInterface $roundBlockSizeMode): BuilderInterface { $this->options['roundBlockSizeMode'] = $roundBlockSizeMode; return $this; } public function foregroundColor(ColorInterface $foregroundColor): BuilderInterface { $this->options['foregroundColor'] = $foregroundColor; return $this; } public function backgroundColor(ColorInterface $backgroundColor): BuilderInterface { $this->options['backgroundColor'] = $backgroundColor; return $this; } public function logoPath(string $logoPath): BuilderInterface { $this->options['logoPath'] = $logoPath; return $this; } public function logoResizeToWidth(int $logoResizeToWidth): BuilderInterface { $this->options['logoResizeToWidth'] = $logoResizeToWidth; return $this; } public function logoResizeToHeight(int $logoResizeToHeight): BuilderInterface { $this->options['logoResizeToHeight'] = $logoResizeToHeight; return $this; } public function logoPunchoutBackground(bool $logoPunchoutBackground): BuilderInterface { $this->options['logoPunchoutBackground'] = $logoPunchoutBackground; return $this; } public function labelText(string $labelText): BuilderInterface { $this->options['labelText'] = $labelText; return $this; } public function labelFont(FontInterface $labelFont): BuilderInterface { $this->options['labelFont'] = $labelFont; return $this; } public function labelAlignment(LabelAlignmentInterface $labelAlignment): BuilderInterface { $this->options['labelAlignment'] = $labelAlignment; return $this; } public function labelMargin(MarginInterface $labelMargin): BuilderInterface { $this->options['labelMargin'] = $labelMargin; return $this; } public function labelTextColor(ColorInterface $labelTextColor): BuilderInterface { $this->options['labelTextColor'] = $labelTextColor; return $this; } public function validateResult(bool $validateResult): BuilderInterface { $this->options['validateResult'] = $validateResult; return $this; } public function build(): ResultInterface { $writer = $this->options['writer']; if ($this->options['validateResult'] && !$writer instanceof ValidatingWriterInterface) { throw ValidationException::createForUnsupportedWriter(strval(get_class($writer))); } /** @var QrCode $qrCode */ $qrCode = $this->buildObject($this->options['qrCodeClass']); /** @var LogoInterface|null $logo */ $logo = $this->buildObject($this->options['logoClass'], 'logo'); /** @var LabelInterface|null $label */ $label = $this->buildObject($this->options['labelClass'], 'label'); $result = $writer->write($qrCode, $logo, $label, $this->options['writerOptions']); if ($this->options['validateResult'] && $writer instanceof ValidatingWriterInterface) { $writer->validateResult($result, $qrCode->getData()); } return $result; } /** * @param class-string $class * * @return mixed */ private function buildObject(string $class, string $optionsPrefix = null) { /** @var \ReflectionClass<object> $reflectionClass */ $reflectionClass = new \ReflectionClass($class); $arguments = []; $hasBuilderOptions = false; $missingRequiredArguments = []; /** @var \ReflectionMethod $constructor */ $constructor = $reflectionClass->getConstructor(); $constructorParameters = $constructor->getParameters(); foreach ($constructorParameters as $parameter) { $optionName = null === $optionsPrefix ? $parameter->getName() : $optionsPrefix.ucfirst($parameter->getName()); if (isset($this->options[$optionName])) { $hasBuilderOptions = true; $arguments[] = $this->options[$optionName]; } elseif ($parameter->isDefaultValueAvailable()) { $arguments[] = $parameter->getDefaultValue(); } else { $missingRequiredArguments[] = $optionName; } } if (!$hasBuilderOptions) { return null; } if (count($missingRequiredArguments) > 0) { throw new \Exception(sprintf('Missing required arguments: %s', implode(', ', $missingRequiredArguments))); } return $reflectionClass->newInstanceArgs($arguments); } }
JavaScript
UTF-8
1,152
2.59375
3
[]
no_license
/** * Track Jetpack social shares as Google Analytics Social Interactions * https://github.com/gregoryfoster/jetpack-shares-google-analytics * * Adapted from: * https://gist.github.com/devinsays/e9a5a42c1416b16f8bae#file-tracking-js */ jQuery(document).ready((function($){ if( typeof(ga) == 'function' ){ var target = [ { network: 'Twitter', selector: 'a.share-twitter' }, { network: 'Facebook', selector: 'a.share-facebook' }, { network: 'Google', selector: 'a.share-google-plus-1' }, { network: 'LinkedIn', selector: 'a.share-linkedin' }, { network: 'Reddit', selector: 'a.share-reddit' } ]; // On click, send GA a Social Interaction message // Uses immediate function closure to distinguish anonymous functions for( var i = 0; i < target.length; i++ ) (function(n){ $(target[n].selector).on('click', function(){ ga('send', { hitType: 'social', socialNetwork: target[n].network, socialAction: 'share', socialTarget: $(this).attr('href').substr(0, $(this).attr('href').indexOf('?')) }); }); })(i); } })(jQuery));
C#
UTF-8
1,933
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace SaltConfigTester { public enum ReportType { AttributeNotFound = 1, AttributeFound = 2, } public static class ReportOutput { private static int LongestKeyname { get { return 30; //Math.Max(""); } } public static string CreatePadding(string key) { string returnStr = null; int numSpaces = LongestKeyname - key.Length; for (int index=0; index<numSpaces; index++) { returnStr += ' '; } return returnStr; } public static string ReportTypeStr(ReportType reportType) { switch (reportType) { case ReportType.AttributeNotFound: return "Attribute Not Found"; } return null; } public static void Run(IList<Report> reportList, string logfileName = null) { if (logfileName != null) { var file = new StreamWriter(logfileName, false); foreach (Report report in reportList) { file.WriteLine(report.ToLog()); Console.WriteLine(report.ToConsole()); } file.Close(); } } } public abstract class Report { public string AttributeName { get; set; } public string Path { get; set; } public int NumPageFeeds { get; set; } public ReportType ReportType { get; set; } public string MessageConsole { get; set; } public string MessageLog { get; set; } public string Value { get; set; } public abstract string ToConsole(); public abstract string ToLog(); } }
JavaScript
UTF-8
1,627
2.515625
3
[]
no_license
const { hash } = require('../person/helper'); const AccountTable = require('../account/table'); const PersonTable = require('../person/table'); class RegisterAccount { static storeAccount( { accountName, username, password } ) { return new Promise((resolve, reject) => { const usernameHash = hash(username); const passwordHash = hash(password); PersonTable.getPerson({ usernameHash }) .then(( { person } ) => { if ( ! person ) { AccountTable.storeAccount( { accountName } ) .then(( { accountId } ) => { const isAdmin = true; PersonTable.storePerson({ usernameHash, passwordHash, accountId, isAdmin }) .then(({ personId }) => { resolve({ personId }) }) .catch(error => reject(error)); }) .catch(error => reject(error)); } else { const error = new Error('Provided username already exist'); error.statusCode = 409; reject(error); } }) .catch(error => reject(error)); }); } static isPersonExist({ usernameHash }) { return new Promise((resolve, reject) => { PersonTable.getPerson( { usernameHash } ) .then(({ person }) => resolve({ isExist: person != undefined })) .catch(error => reject(error)); }) } } module.exports = RegisterAccount;
Python
UTF-8
645
2.578125
3
[]
no_license
fo = open('D-large.out', 'w') data = open('D-large.in').readlines() print (data) num = int(data[0].strip()) for z in range(1, num + 1): n = data[(z - 1) * 3 + 2].split() k = data[(z - 1) * 3 + 3].split() for i in range(len(n)): n[i] = float(n[i]) k[i] = float(k[i]) n = sorted(n, reverse=True) k = sorted(k, reverse=True) j = 0 b = 0 for i in range(len(n)): if n[i] > k[j]: b += 1 else: j += 1 a = 0 idx = 0 for i in range(len(n)): for j in range(idx, len(n)): idx += 1 if n[i] > k[j]: a += 1 j += 1 break print (n) print (k) s = 'Case #%d: %d %d' % (z, a, b) print (s) fo.write(s + '\n')
Java
UTF-8
1,526
1.984375
2
[]
no_license
package com.ansel.coountrynews.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.ansel.coountrynews.R; import com.ansel.coountrynews.adapter.SimpleFragmentPagerAdapter; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Junguo.L on 2017/7/5. */ public class NewsFragment extends Fragment { @BindView(R.id.tl) TabLayout tl; @BindView(R.id.vp) ViewPager vp; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View inflate = inflater.inflate(R.layout.fragment_news, null); ButterKnife.bind(this, inflate); return inflate; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String[] title = getResources().getStringArray(R.array.home_title); SimpleFragmentPagerAdapter simpleFragmentPagerAdapter = new SimpleFragmentPagerAdapter(getFragmentManager(), getActivity(),title); vp.setAdapter(simpleFragmentPagerAdapter); tl.setupWithViewPager(vp); // tl.setTabMode(TabLayout.MODE_FIXED); tl.setTabMode(TabLayout.MODE_SCROLLABLE); } }
Java
UTF-8
55,114
1.96875
2
[]
no_license
/* * 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. */ /** * * @author Jose */ import java.text.*; import java.awt.print.*; import java.awt.event.*; import java.awt.*; import java.util.GregorianCalendar; import java.util.Calendar; import java.sql.*; import javax.swing.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import javax.swing.text.Position; public class Billspare extends javax.swing.JFrame { /** * Creates new form Bill */ String pd=""; int no1; int tamount=0; String rate1; //String amo=amount.getText(); String cname; String bill1; String addr1; int i=0; String str1; String qty1; DefaultTableModel model; public void FillList(){ try { String sql1="select * from lubricants"; String sqla="select * from accessories"; String sqls="select * from spareparts"; Class.forName("com.mysql.jdbc.Driver"); Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors","root",""); Statement stmt=con.createStatement(); Statement stmt1=con.createStatement(); Statement stmt2=con.createStatement(); ResultSet rs1=stmt.executeQuery(sql1); ResultSet rs2=stmt1.executeQuery(sqla); ResultSet rs3=stmt2.executeQuery(sqls); DefaultListModel DLM=new DefaultListModel(); while(rs1.next()) { DLM.addElement(rs1.getString(2)); //DLM.addElement(rs1.getString(2)); } while(rs2.next()) { DLM.addElement(rs2.getString(2)); //DLM.addElement(rs1.getString(2)); } while(rs3.next()) { DLM.addElement(rs3.getString(2)); // DLM.addElement(rs1.getString(2)); } List.setModel(DLM); } catch(Exception e) { JOptionPane.showMessageDialog(null,"e.getString()"); } } public Billspare() { initComponents(); FillList(); setLocationRelativeTo(null); CurrentDate(); Connection con=null; ResultSet rs=null; PreparedStatement pst=null; model=(DefaultTableModel)Table.getModel(); } public void CurrentDate() { Calendar cal=new GregorianCalendar(); int mnth=cal.get(Calendar.MONTH); int year=cal.get(Calendar.YEAR); int day=cal.get(Calendar.DAY_OF_MONTH); bill.setText(day+"/"+(mnth+1)+"/"+year); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); jMenu10 = new javax.swing.JMenu(); jPopupMenu1 = new javax.swing.JPopupMenu(); popupMenu1 = new java.awt.PopupMenu(); jPopupMenu2 = new javax.swing.JPopupMenu(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); no = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); addr = new javax.swing.JTextArea(); cmd_print = new javax.swing.JButton(); custname = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); Table = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); lcharge = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); total = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); toamnt = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); partno = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); name = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); qty = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); rate = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); amount = new javax.swing.JTextField(); bill = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); tax = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); List = new javax.swing.JList(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); search = new javax.swing.JTextField(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); chrg = new javax.swing.JTextField(); jLabel17 = new javax.swing.JLabel(); con = new javax.swing.JTextField(); la = new javax.swing.JTextField(); jLabel18 = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); table1 = new javax.swing.JTable(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu8 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenu9 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenu13 = new javax.swing.JMenu(); jMenuItem20 = new javax.swing.JMenuItem(); jMenuItem21 = new javax.swing.JMenuItem(); jMenu14 = new javax.swing.JMenu(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem22 = new javax.swing.JMenuItem(); jMenuItem23 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem9 = new javax.swing.JMenuItem(); jMenuItem13 = new javax.swing.JMenuItem(); jMenuItem14 = new javax.swing.JMenuItem(); jMenuItem15 = new javax.swing.JMenuItem(); jMenu4 = new javax.swing.JMenu(); jMenuItem10 = new javax.swing.JMenuItem(); jMenu12 = new javax.swing.JMenu(); jMenuItem11 = new javax.swing.JMenuItem(); jMenuItem12 = new javax.swing.JMenuItem(); jMenuItem16 = new javax.swing.JMenuItem(); jMenuItem17 = new javax.swing.JMenuItem(); jMenuItem18 = new javax.swing.JMenuItem(); jMenuItem19 = new javax.swing.JMenuItem(); jMenu15 = new javax.swing.JMenu(); jMenu11 = new javax.swing.JMenu(); jMenuItem7 = new javax.swing.JMenuItem(); jMenuItem8 = new javax.swing.JMenuItem(); jMenu5 = new javax.swing.JMenu(); jMenu7 = new javax.swing.JMenu(); jMenu10.setText("jMenu10"); popupMenu1.setLabel("popupMenu1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("bharathmotors/bill\n"); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel1.setText("BillNo"); getContentPane().add(jLabel1); jLabel1.setBounds(10, 230, 76, 20); jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel4.setText("Customer Name"); getContentPane().add(jLabel4); jLabel4.setBounds(10, 270, 90, 30); jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel5.setText("Address"); getContentPane().add(jLabel5); jLabel5.setBounds(540, 280, 70, 20); no.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { noActionPerformed(evt); } }); getContentPane().add(no); no.setBounds(160, 230, 230, 30); jButton1.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jButton1.setText("ADD"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(1040, 270, 120, 50); jButton2.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jButton2.setText("BACK"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(1040, 560, 120, 50); addr.setColumns(20); addr.setRows(5); jScrollPane1.setViewportView(addr); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(640, 270, 260, 50); cmd_print.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N cmd_print.setText("PRINT"); cmd_print.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmd_printActionPerformed(evt); } }); getContentPane().add(cmd_print); cmd_print.setBounds(1040, 460, 120, 50); getContentPane().add(custname); custname.setBounds(160, 270, 230, 30); jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel8.setText("BillDate"); getContentPane().add(jLabel8); jLabel8.setBounds(540, 230, 50, 20); jLabel10.setFont(new java.awt.Font("Imprint MT Shadow", 1, 18)); // NOI18N jLabel10.setForeground(new java.awt.Color(0, 0, 153)); jLabel10.setText("BHARATH MOTORS"); getContentPane().add(jLabel10); jLabel10.setBounds(380, 150, 220, 30); Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Sl.No", "Part_No", "Item_Name", "Tax%", "Qty", "Rate", "Amount" } )); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, bill, org.jdesktop.beansbinding.ObjectProperty.create(), Table, org.jdesktop.beansbinding.BeanProperty.create("selectedElement")); bindingGroup.addBinding(binding); jScrollPane3.setViewportView(Table); getContentPane().add(jScrollPane3); jScrollPane3.setBounds(0, 340, 980, 130); jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel2.setText("LabourCharge"); getContentPane().add(jLabel2); jLabel2.setBounds(680, 610, 100, 30); getContentPane().add(lcharge); lcharge.setBounds(820, 610, 160, 30); jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel3.setText("Spares"); getContentPane().add(jLabel3); jLabel3.setBounds(680, 490, 100, 20); getContentPane().add(total); total.setBounds(820, 490, 160, 30); jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel6.setText("TotalAmount"); getContentPane().add(jLabel6); jLabel6.setBounds(680, 650, 100, 20); toamnt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toamntActionPerformed(evt); } }); getContentPane().add(toamnt); toamnt.setBounds(820, 640, 160, 30); jLabel7.setText("Part_No"); getContentPane().add(jLabel7); jLabel7.setBounds(160, 20, 70, 30); partno.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { partnoKeyReleased(evt); } }); getContentPane().add(partno); partno.setBounds(230, 20, 170, 30); jLabel9.setText("Item_Name"); getContentPane().add(jLabel9); jLabel9.setBounds(430, 20, 70, 20); getContentPane().add(name); name.setBounds(530, 20, 200, 30); jLabel11.setText("Qty"); getContentPane().add(jLabel11); jLabel11.setBounds(160, 60, 50, 20); qty.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { qtyKeyReleased(evt); } }); getContentPane().add(qty); qty.setBounds(230, 60, 170, 30); jLabel12.setText("Rate"); getContentPane().add(jLabel12); jLabel12.setBounds(430, 70, 60, 20); getContentPane().add(rate); rate.setBounds(530, 60, 200, 30); jLabel13.setText("Amount"); getContentPane().add(jLabel13); jLabel13.setBounds(750, 70, 50, 20); getContentPane().add(amount); amount.setBounds(810, 60, 200, 30); getContentPane().add(bill); bill.setBounds(640, 220, 260, 30); jLabel14.setText("Tax"); getContentPane().add(jLabel14); jLabel14.setBounds(750, 30, 40, 14); tax.setText("14.5"); tax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { taxActionPerformed(evt); } }); getContentPane().add(tax); tax.setBounds(810, 20, 200, 30); List.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { ListValueChanged(evt); } }); jScrollPane2.setViewportView(List); getContentPane().add(jScrollPane2); jScrollPane2.setBounds(0, 50, 130, 80); jButton3.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jButton3.setText("SUBMIT"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(1040, 170, 120, 50); jButton4.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jButton4.setText("CALCULATE"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); getContentPane().add(jButton4); jButton4.setBounds(1040, 370, 120, 50); search.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { searchKeyReleased(evt); } }); getContentPane().add(search); search.setBounds(0, 10, 130, 30); jLabel15.setText("Bharath TVS, Opp.All Saints Church,Udayaperoor, Thripunithra, Pin: 682 307, Tin No: 32071035881 , Ph No: 9072111366/ 9072111355"); getContentPane().add(jLabel15); jLabel15.setBounds(130, 180, 700, 20); jLabel16.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N jLabel16.setText("Washing_chrg"); getContentPane().add(jLabel16); jLabel16.setBounds(680, 520, 100, 20); chrg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chrgActionPerformed(evt); } }); getContentPane().add(chrg); chrg.setBounds(820, 520, 160, 30); jLabel17.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N jLabel17.setText("Consumable"); getContentPane().add(jLabel17); jLabel17.setBounds(680, 550, 90, 20); getContentPane().add(con); con.setBounds(820, 580, 160, 30); getContentPane().add(la); la.setBounds(820, 550, 160, 30); jLabel18.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N jLabel18.setText("Laith"); getContentPane().add(jLabel18); jLabel18.setBounds(680, 584, 70, 20); table1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane4.setViewportView(table1); getContentPane().add(jScrollPane4); jScrollPane4.setBounds(0, 150, 1000, 560); jMenu1.setText("StockEntry"); jMenu1.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu1.setMaximumSize(new java.awt.Dimension(75, 32767)); jMenu8.setText("Motors"); jMenuItem1.setText("Bike"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu8.add(jMenuItem1); jMenuItem2.setText("Scooty"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu8.add(jMenuItem2); jMenu1.add(jMenu8); jMenu9.setText("Spare"); jMenuItem3.setText("Lubricants"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu9.add(jMenuItem3); jMenuItem4.setText("SpareParts"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu9.add(jMenuItem4); jMenuItem5.setText("Accessories"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu9.add(jMenuItem5); jMenu1.add(jMenu9); jMenuBar1.add(jMenu1); jMenu2.setText("Purchase"); jMenu2.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu2.setMaximumSize(new java.awt.Dimension(75, 32767)); jMenu2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu2ActionPerformed(evt); } }); jMenu13.setText("Bill"); jMenuItem20.setText("Spare"); jMenuItem20.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem20ActionPerformed(evt); } }); jMenu13.add(jMenuItem20); jMenuItem21.setText("Motors"); jMenuItem21.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem21ActionPerformed(evt); } }); jMenu13.add(jMenuItem21); jMenu2.add(jMenu13); jMenuBar1.add(jMenu2); jMenu14.setText("Sale"); jMenu14.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu14.setMaximumSize(new java.awt.Dimension(65, 32767)); jMenuItem6.setText("Sale"); jMenuItem6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem6ActionPerformed(evt); } }); jMenu14.add(jMenuItem6); jMenuItem22.setText("Service"); jMenuItem22.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem22ActionPerformed(evt); } }); jMenu14.add(jMenuItem22); jMenuItem23.setText("Certificate"); jMenuItem23.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem23ActionPerformed(evt); } }); jMenu14.add(jMenuItem23); jMenuBar1.add(jMenu14); jMenu3.setText("StockAvailable"); jMenu3.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu3.setMaximumSize(new java.awt.Dimension(115, 32767)); jMenu3.addMenuListener(new javax.swing.event.MenuListener() { public void menuCanceled(javax.swing.event.MenuEvent evt) { } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuSelected(javax.swing.event.MenuEvent evt) { jMenu3MenuSelected(evt); } }); jMenu3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu3ActionPerformed(evt); } }); jMenuItem9.setText("Motors"); jMenuItem9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem9ActionPerformed(evt); } }); jMenu3.add(jMenuItem9); jMenuItem13.setText("Lubricants"); jMenuItem13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem13ActionPerformed(evt); } }); jMenu3.add(jMenuItem13); jMenuItem14.setText("SpareParts"); jMenuItem14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem14ActionPerformed(evt); } }); jMenu3.add(jMenuItem14); jMenuItem15.setText("Accessories"); jMenuItem15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem15ActionPerformed(evt); } }); jMenu3.add(jMenuItem15); jMenuBar1.add(jMenu3); jMenu4.setText("Report"); jMenu4.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu4.setMaximumSize(new java.awt.Dimension(60, 32767)); jMenu4.addMenuListener(new javax.swing.event.MenuListener() { public void menuCanceled(javax.swing.event.MenuEvent evt) { } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuSelected(javax.swing.event.MenuEvent evt) { jMenu4MenuSelected(evt); } }); jMenu4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu4ActionPerformed(evt); } }); jMenuItem10.setText("Sale"); jMenuItem10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem10ActionPerformed(evt); } }); jMenu4.add(jMenuItem10); jMenu12.setText("Bill"); jMenuItem11.setText("BillNo"); jMenuItem11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem11ActionPerformed(evt); } }); jMenu12.add(jMenuItem11); jMenuItem12.setText("BillDate"); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem12ActionPerformed(evt); } }); jMenu12.add(jMenuItem12); jMenu4.add(jMenu12); jMenuItem16.setText("Lubricants"); jMenuItem16.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem16ActionPerformed(evt); } }); jMenu4.add(jMenuItem16); jMenuItem17.setText("SpareParts"); jMenuItem17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem17ActionPerformed(evt); } }); jMenu4.add(jMenuItem17); jMenuItem18.setText("Accessories"); jMenuItem18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem18ActionPerformed(evt); } }); jMenu4.add(jMenuItem18); jMenuItem19.setText("Motors"); jMenuItem19.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem19ActionPerformed(evt); } }); jMenu4.add(jMenuItem19); jMenuBar1.add(jMenu4); jMenu15.setText("Payroll"); jMenu15.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu15.setMaximumSize(new java.awt.Dimension(60, 32767)); jMenu15.addMenuListener(new javax.swing.event.MenuListener() { public void menuCanceled(javax.swing.event.MenuEvent evt) { } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuSelected(javax.swing.event.MenuEvent evt) { jMenu15MenuSelected(evt); } }); jMenuBar1.add(jMenu15); jMenu11.setLabel("Employee"); jMenu11.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu11.setMaximumSize(new java.awt.Dimension(70, 32767)); jMenu11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu11ActionPerformed(evt); } }); jMenuItem7.setText("New"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu11.add(jMenuItem7); jMenuItem8.setText("Update/Delete"); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem8ActionPerformed(evt); } }); jMenu11.add(jMenuItem8); jMenuBar1.add(jMenu11); jMenu5.setText("AboutUs"); jMenu5.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu5.setMaximumSize(new java.awt.Dimension(75, 32767)); jMenu5.addMenuListener(new javax.swing.event.MenuListener() { public void menuCanceled(javax.swing.event.MenuEvent evt) { } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuSelected(javax.swing.event.MenuEvent evt) { jMenu5MenuSelected(evt); } }); jMenu5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu5ActionPerformed(evt); } }); jMenuBar1.add(jMenu5); jMenu7.setText("Exit"); jMenu7.setMargin(new java.awt.Insets(0, 5, 0, 0)); jMenu7.setMaximumSize(new java.awt.Dimension(35, 32767)); jMenu7.addMenuListener(new javax.swing.event.MenuListener() { public void menuCanceled(javax.swing.event.MenuEvent evt) { } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuSelected(javax.swing.event.MenuEvent evt) { jMenu7MenuSelected(evt); } }); jMenu7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu7ActionPerformed(evt); } }); jMenuBar1.add(jMenu7); setJMenuBar(jMenuBar1); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: Stock s=new Stock(); s.setVisible(true); setVisible(false); dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void cmd_printActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmd_printActionPerformed MessageFormat header=new MessageFormat("Report Print"); MessageFormat footer=new MessageFormat("page{0,number,integer}"); try { table1.print(JTable.PrintMode.NORMAL,header,footer); } catch(java.awt.print.PrinterException e1) { System.err.format("cannot print %s%n", e1.getMessage()); } }//GEN-LAST:event_cmd_printActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String part=partno.getText(); String itemname=name.getText(); String qty1=qty.getText(); String rate1=rate.getText(); String no1=no.getText(); String cname=custname.getText(); String bill1=bill.getText(); String addr1=addr.getText(); String ta=tax.getText(); String str1=amount.getText(); DefaultTableModel model=(DefaultTableModel) Table.getModel(); model.addRow(new Object[]{(String.valueOf(++i)),partno.getText(),name.getText(),tax.getText(),qty.getText(),rate.getText(),amount.getText()}); pd=pd+","+"("+part+","+itemname+","+qty1+")"; tamount= tamount+ Integer.parseInt(str1); try { Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors","root",""); Statement stmt2=con.createStatement(); Statement stmt3=con.createStatement(); Statement stmt4=con.createStatement(); stmt2.executeUpdate("UPDATE LUBRICANTS SET QUANTITY=QUANTITY-'"+qty1+"' WHERE PART_NO='"+part+"'"); stmt3.executeUpdate("UPDATE SPAREPARTS SET QUANTITY=QUANTITY-'"+qty1+"' WHERE PART_NO='"+part+"'"); stmt4.executeUpdate("UPDATE ACCESSORIES SET QUANTITY=QUANTITY-'"+qty1+"' WHERE PART_NO='"+part+"'"); } catch(Exception e) { JOptionPane.showMessageDialog(null,e.toString()); } }//GEN-LAST:event_jButton1ActionPerformed private void toamntActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toamntActionPerformed // TODO add your handling code here: String a=lcharge.getText(); String b=total.getText(); //String c=toamnt.getText(); int d=Integer.parseInt(b); int e=Integer.parseInt(a); int f=d+e; toamnt.setText(String.valueOf(f)); }//GEN-LAST:event_toamntActionPerformed private void partnoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_partnoKeyReleased // TODO add your handling code here: }//GEN-LAST:event_partnoKeyReleased private void ListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_ListValueChanged // TODO add your handling code here: //String part=partno.getText(); try { String sql="SELECT PART_NO,ITEM_NAME,QUANTITY,MRP FROM LUBRICANTS WHERE PART_NO='"+List.getSelectedValue()+"'"; String sqla="SELECT PART_NO,ITEM_NAME,QUANTITY,MRP FROM ACCESSORIES WHERE PART_NO='"+List.getSelectedValue()+"'"; String sqlb="SELECT PART_NO,ITEM_NAME,QUANTITY,MRP FROM SPAREPARTS WHERE PART_NO='"+List.getSelectedValue()+"'"; Class.forName("com.mysql.jdbc.Driver"); Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors","root",""); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(sql); Statement stmt1=con.createStatement(); ResultSet rs1=stmt1.executeQuery(sqla); Statement stmt2=con.createStatement(); ResultSet rs2=stmt2.executeQuery(sqlb); while(rs.next()) { partno.setText(rs.getString("PART_NO")); name.setText(rs.getString("ITEM_NAME")); qty.setText(rs.getString("QUANTITY")); rate.setText(rs.getString("MRP")); } while(rs1.next()) { partno.setText(rs1.getString("PART_NO")); name.setText(rs1.getString("ITEM_NAME")); qty.setText(rs1.getString("QUANTITY")); rate.setText(rs1.getString("MRP")); } while(rs2.next()) { partno.setText(rs2.getString("PART_NO")); name.setText(rs2.getString("ITEM_NAME")); qty.setText(rs2.getString("QUANTITY")); rate.setText(rs2.getString("MRP")); } } catch(Exception e) { JOptionPane.showMessageDialog(null,e.toString()); } }//GEN-LAST:event_ListValueChanged private void taxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_taxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_taxActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed try { Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors","root",""); Statement stmt=con.createStatement(); ResultSet resultSet = stmt.executeQuery("select Bill_No from bill;"); String productCode=null; while (resultSet.next()) { productCode = resultSet.getString("Bill_No"); } int pc=Integer.parseInt(productCode); System.out.println(pc); no.setText((String.valueOf(++pc))); // TODO add your handling code here: String part=partno.getText(); String itemname=name.getText(); String qty1=qty.getText(); String rate1=rate.getText(); //String amo=amount.getText(); String noo=no.getText(); no1=Integer.parseInt(noo); cname=custname.getText(); bill1=bill.getText(); addr1=addr.getText(); String ta=tax.getText(); int a=Integer.parseInt(qty1); int b=Integer.parseInt(rate1); int c=a*b; String str=Integer.toString(c); amount.setText(str); String str1=amount.getText(); /* String sql1="select Quantity from lubricants"; String sql2="UPDATE LUBRICANTS SET QUANTITY=QUANTITY-qty1 WHERE PART_NO='"+partno+"'"; Statement stmt1=con.createStatement(); ResultSet rs1= stmt1.executeQuery(sql1); String ch=rs1.getString("QUANTITY"); int q=Integer.parseInt(qty1); int r=Integer.parseInt(ch); if(q >r) { JOptionPane.showMessageDialog(this,"STOCK UNAVAILABLE"); } else { stmt1.executeUpdate(sql2); }*/ } catch (SQLException ex) { Logger.getLogger(Billspare.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: String wash=chrg.getText(); cname=custname.getText(); addr1=addr.getText(); total.setText(String.valueOf(tamount)); String a=lcharge.getText(); String b=total.getText(); String j=la.getText(); String c=con.getText(); int d=Integer.parseInt(b); int e=Integer.parseInt(a); int g=Integer.parseInt(wash); int h=Integer.parseInt(c); int i=Integer.parseInt(j); int f=d+e+g+h+i; toamnt.setText(String.valueOf(f)); String sql="insert into bill(Bill_No,Bill_Date,Cust_Name,Cust_Addr,P_Details,Amount) values('"+no1+"','"+bill1+"','"+cname+"','"+addr1+"','"+pd+"','"+toamnt+"')"; try { Class.forName("com.mysql.jdbc.Driver"); Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors","root",""); Statement stmt=con.createStatement(); stmt.executeUpdate(sql); } catch (Exception e2){ JOptionPane.showMessageDialog(this, e2.getMessage()); } }//GEN-LAST:event_jButton4ActionPerformed private void noActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_noActionPerformed // TODO add your handling code here: }//GEN-LAST:event_noActionPerformed private void searchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchKeyReleased // TODO add your handling code here: int r= List.getNextMatch(search.getText(), 0, Position.Bias.Forward); List.setSelectedIndex(r); }//GEN-LAST:event_searchKeyReleased private void qtyKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_qtyKeyReleased // TODO add your handling code here: }//GEN-LAST:event_qtyKeyReleased private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed Bike b=new Bike(); b.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed Scooty s=new Scooty(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed Lubricants l=new Lubricants(); l.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem3ActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed SpareParts p=new SpareParts(); p.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed Accessories a=new Accessories(); a.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem5ActionPerformed private void jMenuItem20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem20ActionPerformed // TODO add your handling code here: Billspare b=new Billspare(); b.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem20ActionPerformed private void jMenuItem21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem21ActionPerformed // TODO add your handling code here: billmotors b=new billmotors(); b.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem21ActionPerformed private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenu2ActionPerformed private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed // TODO add your handling code here: Sale s=new Sale(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem6ActionPerformed private void jMenuItem22ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem22ActionPerformed // TODO add your handling code here: Service s=new Service(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem22ActionPerformed private void jMenuItem23ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem23ActionPerformed // TODO add your handling code here: salescert c=new salescert(); c.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem23ActionPerformed private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed // TODO add your handling code here: stockAvilable s=new stockAvilable(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem9ActionPerformed private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem13ActionPerformed // TODO add your handling code here: stockLubricants s=new stockLubricants(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem13ActionPerformed private void jMenuItem14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem14ActionPerformed // TODO add your handling code here: stockspareparts s=new stockspareparts(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem14ActionPerformed private void jMenuItem15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem15ActionPerformed // TODO add your handling code here: stockaccessories s=new stockaccessories(); s.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem15ActionPerformed private void jMenu3MenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_jMenu3MenuSelected // TODO add your handling code here: }//GEN-LAST:event_jMenu3MenuSelected private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenu3ActionPerformed private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed // TODO add your handling code here: Report1 r=new Report1(); r.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem10ActionPerformed private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed // TODO add your handling code here: Report3 r=new Report3(); r.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem11ActionPerformed private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed Report r=new Report(); r.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem12ActionPerformed private void jMenuItem16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem16ActionPerformed // TODO add your handling code here: lubricantsreport l=new lubricantsreport(); l.setVisible(true); setVisible(false); dispose(); }//GEN-LAST:event_jMenuItem16ActionPerformed private void jMenuItem17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem17ActionPerformed // TODO add your handling code here: sparepartsreport s=new sparepartsreport(); s.setVisible(true); setVisible(false); dispose(); }//GEN-LAST:event_jMenuItem17ActionPerformed private void jMenuItem18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem18ActionPerformed // TODO add your handling code here: accessoriessreport a=new accessoriessreport(); a.setVisible(true); setVisible(false); dispose(); }//GEN-LAST:event_jMenuItem18ActionPerformed private void jMenuItem19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem19ActionPerformed // TODO add your handling code here: motorsreport m=new motorsreport(); m.setVisible(true); setVisible(false); dispose(); }//GEN-LAST:event_jMenuItem19ActionPerformed private void jMenu4MenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_jMenu4MenuSelected }//GEN-LAST:event_jMenu4MenuSelected private void jMenu4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenu4ActionPerformed private void jMenu15MenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_jMenu15MenuSelected // TODO add your handling code here: payroll p=new payroll(); p.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenu15MenuSelected private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed // TODO add your handling code here: EmployeeEntry u=new EmployeeEntry(); u.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenuItem7ActionPerformed private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed // TODO add your handling code here: empupdate u=new empupdate(); u.setVisible(true); setVisible(false); dispose(); }//GEN-LAST:event_jMenuItem8ActionPerformed private void jMenu11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu11ActionPerformed // TODO add your handling code here: empupdate u=new empupdate(); u.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenu11ActionPerformed private void jMenu5MenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_jMenu5MenuSelected // TODO add your handling code here: company1 c=new company1(); c.setVisible(true); setVisible(false); }//GEN-LAST:event_jMenu5MenuSelected private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenu5ActionPerformed private void jMenu7MenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_jMenu7MenuSelected String message = " Are you sure you want to exit the application!!! "; int answer = JOptionPane.showConfirmDialog(null, message, "Confirmation!!!", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { dispose(); } else if (answer == JOptionPane.NO_OPTION) { // User clicked NO. } }//GEN-LAST:event_jMenu7MenuSelected private void jMenu7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu7ActionPerformed }//GEN-LAST:event_jMenu7ActionPerformed private void chrgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chrgActionPerformed // TODO add your handling code here: }//GEN-LAST:event_chrgActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Billspare.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Billspare.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Billspare.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Billspare.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Billspare().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JList List; private javax.swing.JTable Table; private javax.swing.JTextArea addr; private javax.swing.JTextField amount; private javax.swing.JTextField bill; private javax.swing.JTextField chrg; private javax.swing.JButton cmd_print; private javax.swing.JTextField con; private javax.swing.JTextField custname; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu10; private javax.swing.JMenu jMenu11; private javax.swing.JMenu jMenu12; private javax.swing.JMenu jMenu13; private javax.swing.JMenu jMenu14; private javax.swing.JMenu jMenu15; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenu jMenu7; private javax.swing.JMenu jMenu8; private javax.swing.JMenu jMenu9; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem10; private javax.swing.JMenuItem jMenuItem11; private javax.swing.JMenuItem jMenuItem12; private javax.swing.JMenuItem jMenuItem13; private javax.swing.JMenuItem jMenuItem14; private javax.swing.JMenuItem jMenuItem15; private javax.swing.JMenuItem jMenuItem16; private javax.swing.JMenuItem jMenuItem17; private javax.swing.JMenuItem jMenuItem18; private javax.swing.JMenuItem jMenuItem19; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem20; private javax.swing.JMenuItem jMenuItem21; private javax.swing.JMenuItem jMenuItem22; private javax.swing.JMenuItem jMenuItem23; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JMenuItem jMenuItem9; private javax.swing.JPopupMenu jPopupMenu1; private javax.swing.JPopupMenu jPopupMenu2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTextField la; private javax.swing.JTextField lcharge; private javax.swing.JTextField name; private javax.swing.JTextField no; private javax.swing.JTextField partno; private java.awt.PopupMenu popupMenu1; private javax.swing.JTextField qty; private javax.swing.JTextField rate; private javax.swing.JTextField search; private javax.swing.JTable table1; private javax.swing.JTextField tax; private javax.swing.JTextField toamnt; private javax.swing.JTextField total; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }
C
UTF-8
6,042
2.84375
3
[ "MIT" ]
permissive
// // Created by eugen on 5/6/2017. // #include "parser.h" void xtra_parser_brackets_exchage(xtra_parser_brackets_p brackets, xtra_sign_p sign) { enum xtra_sign_e type = sign->type; if (type == XTRA_SIGN_SQUARE_L) { brackets->square++; } else if (type == XTRA_SIGN_SQUARE_R) { brackets->square--; } else if (type == XTRA_SIGN_ROUND_L) { brackets->round++; } else if (type == XTRA_SIGN_ROUND_R) { brackets->round--; } else if (type == XTRA_SIGN_CURLY_L) { brackets->curly++; } else if (type == XTRA_SIGN_CURLY_R) { brackets->curly--; } else if (type == XTRA_SIGN_ANGLE_L) { brackets->angle++; } else if (type == XTRA_SIGN_ANGLE_R) { brackets->angle--; } else if (type == XTRA_SIGN_UNALLOWED) { brackets->unallowed++; } if (brackets->square < 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Redundant bracket \"]\" in %s on %lu line %lu column", token->__file, token->__line, token->__column); xtra_error("Redundant bracket \"]\"", 1); } else if (brackets->round < 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Redundant bracket \")\" in %s on %lu line %lu column", token->__file, token->__line, token->__column); xtra_error("Redundant bracket \")\"", 1); } else if (brackets->curly < 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Redundant bracket \"}\" in %s on %lu line %lu column", token->__file, token->__line, token->__column); xtra_error("Redundant bracket \"}\"", 1); } else if (brackets->angle < 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Redundant bracket \">\" in %s on %lu line %lu column", token->__file, token->__line, token->__column); xtra_error("Redundant bracket \">\"", 1); } } void xtra_parser_circle(xtra_sign_p sign) { long position = -1; // printf("> script %d\n", script->size); while (++position < xtra_sign_arry_len(sign)) { xtra_sign_p _sign = xtra_sign_arry_get(sign, position); if (xtra_brackets_is_curly(_sign) == 1) { /** * Go into {} * * @recursion */ xtra_parser_circle(_sign); } else if (xtra_if_join_elseif(sign, &position) == 1) { /** * Convertation "else if" to "elseif" * * @silence */ } else if (xtra_bracket_is_left(_sign) == 1) { /** * Convertation "{" and "}" to "{}" * * @silence */ xtra_brackets_join_conditions(sign, &position); // open-close } else if (_sign->type == XTRA_SIGN_IF) { xtra_if_parse(sign, &position); } else if (_sign->type == XTRA_SIGN_FOR) { xtra_for_parse(sign, &position); } else if (_sign->type == XTRA_SIGN_DO) { /** * Convertation "do {} while ()" to "while () {}" * * @silence */ xtra_do_parse(sign, &position); } else if (_sign->type == XTRA_SIGN_WHILE) { xtra_while_parse(sign, &position); } else if (_sign->type == XTRA_SIGN_SWITCH) { xtra_switch_parse(sign, &position); } else { // other condition } // if (script->child[position]->type == XTRA_SIGN_FOR) { // // for confidition // xtra_parser_for_condition(script, &position); // } else if (script->child[position]->type == XTRA_SIGN_DO) { // // for confidition // xtra_parser_do_condition(script, &position); // } else if (script->child[position]->type == XTRA_SIGN_WHILE) { // // for confidition // xtra_parser_while_condition(script, &position); // } else if (script->child[position]->type == XTRA_SIGN_IF) { // // if confidition // printf("> if \n"); // xtra_parser_if_condition(script, &position); // } } } void xtra_parser_check(xtra_sign_p sign) { xtra_parser_brackets_t brackets = {0, 0, 0, 0, 0}; // brackets open close // global rule checker long iterator = -1; while(++iterator < xtra_sign_arry_len(sign)) { xtra_parser_brackets_exchage(&brackets, xtra_sign_arry_get(sign, iterator)); } if (brackets.square != 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Unexpected end of file. Bracket \"]\" missed in %s", sign->__file); xtra_error("Unexpected end of file. Bracket \"]\"", 6); } if (brackets.round != 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Unexpected end of file. Bracket \")\" missed in %s", sign->__file); xtra_error("Unexpected end of file. Bracket \")\"", 6); } if (brackets.curly != 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Unexpected end of file. Bracket \"}\" missed in %s", sign->__file); xtra_error("Unexpected end of file. Bracket \"}\"", 6); } if (brackets.angle != 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "Unexpected end of file. Bracket \">\" missed in %s", sign->__file); xtra_error("Unexpected end of file. Bracket \">\"", 1); } // if (brackets.unallowed != 0) { // char * error = (char *) malloc(sizeof(char)); // sprintf(error, "error: \"%d\" unallowed.\n", brackets.unallowed); // xtra_error(error, 0); // } // condition logical condition //xtra_parser_normalize_condition(script); // condition logical condition xtra_parser_circle(sign); }
TypeScript
UTF-8
811
2.71875
3
[ "MIT" ]
permissive
import { useState, useEffect, RefObject } from 'react'; function useHover(ref: RefObject<HTMLElement>) { const [isHovering, setIsHovering] = useState(false); useEffect(() => { if (!ref.current) { return; } const setHoveringTrue = () => setIsHovering(true); const setHoveringFalse = () => setIsHovering(false); ref.current.addEventListener('mouseenter', setHoveringTrue); ref.current.addEventListener('mouseleave', setHoveringFalse); // Remove event listeners while unmounting. return () => { if (!ref.current) { return; } ref.current.removeEventListener('mouseenter', setHoveringTrue); ref.current.removeEventListener('mouseleave', setHoveringFalse); } }, [ref, setIsHovering]); return isHovering; } export { useHover }
Python
UTF-8
2,174
3.046875
3
[]
no_license
import threading import logging import random import time from regionCondicional import * logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(threadName)s] - %(message)s', datefmt='%H:%M:%S', level=logging.INFO) class miRecurso (Recurso): # hereda de Recurso, porqué allí se encuentra el mutex y su logica correspondiente encargada de la exclusion mutua. dato1 = 0 numLectores = 0 numEscritores = 0 escribiendo = False informacion = miRecurso() def condicionLector(): return (not informacion.escribiendo) and (informacion.numEscritores == 0) def condicionEscritor(): return not informacion.escribiendo def condicionTrue(): return True regionLector = RegionCondicional(informacion,condicionLector) regionEscritor = RegionCondicional(informacion,condicionEscritor) regionLectorEscritorTrue = RegionCondicional(informacion,condicionTrue) # Esta region tiene una condicion siempre TRUE, ergo proceso que entra aquí siempre podra HACER (do). @regionLector.condicion def doLector1(): informacion.numLectores += 1 @regionLectorEscritorTrue.condicion def doLector2(): informacion.numLectores -= 1 @regionLectorEscritorTrue.condicion def doEscritor1(): informacion.numEscritores += 1 @regionEscritor.condicion def doEscritor2(): informacion.escribiendo= True informacion.numEscritores -=1 @regionLectorEscritorTrue.condicion def doEscritor3(): informacion.escribiendo=False def Lector(): while True: doLector1() logging.info(f'Lector lee dato1 = {regionLector.recurso.dato1}') time.sleep(1) doLector2() def Escritor(): while True: doEscritor1() doEscritor2() regionEscritor.recurso.dato1 = random.randint(0,100) logging.info(f'Escritor escribe dato1 = {regionEscritor.recurso.dato1}') doEscritor3() time.sleep(3) def main(): numLector = 20 numEscritor = 2 for k in range(numLector): threading.Thread(target=Lector, daemon=True).start() for k in range(numEscritor): threading.Thread(target=Escritor, daemon=True).start() time.sleep(300) if __name__ == "__main__": main()
Markdown
UTF-8
5,600
3.078125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Overview of Azure Relay .NET Standard APIs | Microsoft Docs description: This article summarizes some of the key an overview of Azure Relay Hybrid Connections .NET Standard API. ms.topic: article ms.custom: devx-track-csharp, devx-track-dotnet ms.date: 08/10/2023 --- # Azure Relay Hybrid Connections .NET Standard API overview This article summarizes some of the key Azure Relay Hybrid Connections .NET Standard [client APIs](/dotnet/api/microsoft.azure.relay). ## Relay Connection String Builder class The [RelayConnectionStringBuilder][RelayConnectionStringBuilder] class formats connection strings that are specific to Relay Hybrid Connections. You can use it to verify the format of a connection string, or to build a connection string from scratch. See the following code for an example: ```csharp var endpoint = "[Relay namespace]"; var entityPath = "[Name of the Hybrid Connection]"; var sharedAccessKeyName = "[SAS key name]"; var sharedAccessKey = "[SAS key value]"; var connectionStringBuilder = new RelayConnectionStringBuilder() { Endpoint = endpoint, EntityPath = entityPath, SharedAccessKeyName = sasKeyName, SharedAccessKey = sasKeyValue }; ``` You can also pass a connection string directly to the `RelayConnectionStringBuilder` method. This operation enables you to verify that the connection string is in a valid format. If any of the parameters are invalid, the constructor generates an `ArgumentException`. ```csharp var myConnectionString = "[RelayConnectionString]"; // Declare the connectionStringBuilder so that it can be used outside of the loop if needed RelayConnectionStringBuilder connectionStringBuilder; try { // Create the connectionStringBuilder using the supplied connection string connectionStringBuilder = new RelayConnectionStringBuilder(myConnectionString); } catch (ArgumentException ae) { // Perform some error handling } ``` ## Hybrid connection stream The [HybridConnectionStream][HCStream] class is the primary object used to send and receive data from an Azure Relay endpoint, whether you're working with a [HybridConnectionClient][HCClient], or a [HybridConnectionListener][HCListener]. ### Getting a Hybrid connection stream #### Listener Using a [HybridConnectionListener][HCListener] object, you can obtain a `HybridConnectionStream` object as follows: ```csharp // Use the RelayConnectionStringBuilder to get a valid connection string var listener = new HybridConnectionListener(csb.ToString()); // Open a connection to the Relay endpoint await listener.OpenAsync(); // Get a `HybridConnectionStream` var hybridConnectionStream = await listener.AcceptConnectionAsync(); ``` #### Client Using a [HybridConnectionClient][HCClient] object, you can obtain a `HybridConnectionStream` object as follows: ```csharp // Use the RelayConnectionStringBuilder to get a valid connection string var client = new HybridConnectionClient(csb.ToString()); // Open a connection to the Relay endpoint and get a `HybridConnectionStream` var hybridConnectionStream = await client.CreateConnectionAsync(); ``` ### Receiving data The [HybridConnectionStream][HCStream] class enables two-way communication. In most cases, you continuously receive from the stream. If you're reading text from the stream, you might also want to use a [StreamReader](/dotnet/api/system.io.streamreader) object, which enables easier parsing of the data. For example, you can read data as text, rather than as `byte[]`. The following code reads individual lines of text from the stream until a cancellation is requested: ```csharp // Create a CancellationToken, so that we can cancel the while loop var cancellationToken = new CancellationToken(); // Create a StreamReader from the hybridConnectionStream var streamReader = new StreamReader(hybridConnectionStream); while (!cancellationToken.IsCancellationRequested) { // Read a line of input until a newline is encountered var line = await streamReader.ReadLineAsync(); if (string.IsNullOrEmpty(line)) { // If there's no input data, we will signal that // we will no longer send data on this connection // and then break out of the processing loop. await hybridConnectionStream.ShutdownAsync(cancellationToken); break; } } ``` ### Sending data Once you have a connection established, you can send a message to the Relay endpoint. Because the connection object inherits [Stream](/dotnet/api/system.io.stream), send your data as a `byte[]`. The following example shows how to do it: ```csharp var data = Encoding.UTF8.GetBytes("hello"); await clientConnection.WriteAsync(data, 0, data.Length); ``` However, if you want to send text directly, without needing to encode the string each time, you can wrap the `hybridConnectionStream` object with a [StreamWriter](/dotnet/api/system.io.streamwriter) object. ```csharp // The StreamWriter object only needs to be created once var textWriter = new StreamWriter(hybridConnectionStream); await textWriter.WriteLineAsync("hello"); ``` ## Next steps To learn more about Azure Relay, visit these links: * [Microsoft.Azure.Relay reference](/dotnet/api/microsoft.azure.relay) * [What is Azure Relay?](relay-what-is-it.md) * [Available Relay APIs](relay-api-overview.md) [RelayConnectionStringBuilder]: /dotnet/api/microsoft.azure.relay.relayconnectionstringbuilder [HCStream]: /dotnet/api/microsoft.azure.relay.hybridconnectionstream [HCClient]: /dotnet/api/microsoft.azure.relay.hybridconnectionclient [HCListener]: /dotnet/api/microsoft.azure.relay.hybridconnectionlistener
Markdown
UTF-8
2,913
3.40625
3
[ "MIT" ]
permissive
--- title: ספירה לאחור date: 20/09/2021 --- כאשר ישבו על הר הזיתים, צייר ישוע במשיכות מכחול רחבות את מהלך ההיסטוריה, כמענה לשאלות תלמידיו: “ הַגֵּד נָא לָנוּ מָתַי יִהְיֶה הַדָּבָר הַזֶּה וּמַה הוּא אוֹת בּוֹאֲךָ וְקֵץ הָעוֹלָם? ” (מתי כ”ד: 3). דרשתו המפורסמת של ישוע במתי כ"ד, עוברת ברציפות על ציר הזמן ההיסטורי מימי חייו על פני האדמה ועד ביאתו השנייה ומעבר לה. ישוע רצה להעניק לאנשיו בכל העידנים סקיצה כללית של התוכנית השמיימית לנבואות סוף הזמנים, כך שאלו אשר יחיו בסוף הזמנים יוכלו להתכונן לאירוע הגדול מכל. הוא חפץ בכך שנוכל לנוח בביטחה באהבתו, גם בעת שהעולם מסביבנו נקרע לגזרים. אדוונטיסטים מכירים טוב את תיאורו של דניאל: " וְהָיְתָה עֵת צָרָה, אֲשֶׁר לֹא־נִהְיְתָה מִהְיוֹת גּוֹי, עַד הָעֵת הַהִיא ” (דניאל י"ב: 1). ישוע רוצה שנהיה מוכנים למאורע זה, המקדים את ביאתו השנייה. `כיצד תיראה ביאתו של ישוע? כיצד נוכל להימנע מהולכה בשולל? קרא את מתי כ"ד: 4-8, 23-31.` שיבתו של ישוע תהא אירוע אמת בסוף הזמנים. בהתחשב במקום הניתן לה בנבואות ובדרשותיו של ישוע, מדובר באירוע רציני. בפעם האחרונה שהתרחש אירוע קיצוני בסדר עולמי, רק שמונה אנשים בכל העולם כולו היו מוכנים לכך. ישוע משווה בין הפתעתו של אירוע זה- המבול, לבין ביאתו השנייה (מתי כ”ד: 37-39). אך למרות שאף אדם אינו יודע את היום או השעה של הביאה השנייה (מתי כ”ד: 36), ה' העניק לנו ספירה נבואית לאחור שניתן לצפות בה דרך התרחשויות בעולם סביבנו. ניתן לנו תפקיד למלא בדרמה נבואית זו. מהו? התמקד במתי כ"ד: 9-14. בעימות יקומי זה, אנו יותר מאשר צופים גרידא. עלינו לקחת חלק פעיל בהפצת הבשורה לקצוות העולם, ועל כן אנו גם צפויים לעמוד בפני רדיפות. `מהי הכוונה ב" מַּחֲזִיק מַעֲמָד עַד קֵץ ”? כיצד אנו יכולים לעשות זאת? אילו בחירות עלינו לעשות מדי יום ביומו על מנת שלא נלך שולל, כפי שהלכו רבים ורבים עוד ילכו?`
PHP
UTF-8
4,978
3.5625
4
[ "MIT" ]
permissive
<?php /** * File handling utility class * * @author Frederic BAYLE */ namespace FastTrack\IO; use FastTrack\ObjectBase; /** * File handling utility class * * @property-read bool $EOF Get a flag that determines whether the end of file has been reached */ class File extends ObjectBase { /** * File opening mode: Read only * * @var int */ const MODE_READONLY = 0; /** * File opening mode: Write only * * @var int */ const MODE_WRITEONLY = 1; /** * File opening mode: Write only at the end of a file * * @var int */ const MODE_WRITEONLYAPPEND = 2; /** * File resource handler (used by close, readBytes and writeBytes functions) * * @var resource */ protected $_FileHandler = NULL; /** * Get a flag that determines whether the end of file has been reached * * @return bool * @throws \Exception */ protected function &getEOF() { if($this->_FileHandler !== NULL) { throw new \Exception('This file is closed.'); } $ReturnValue = feof($this->_FileHandler); return $ReturnValue; } /** * Create an instance of this class, opens a file * * @param string $pFilePath Path of the file to open * @param int $pFileMode Opening Mode (consts in the FileMode class) */ function __construct($pFilePath, $pFileMode) { $FileMode = ''; switch(pFileMode) { case File::MODE_WRITEONLY: $FileMode = 'wb'; break; case File::MODE_WRITEONLYAPPEND: $FileMode = 'ab'; break; case File::MODE_READONLY: default: $FileMode = 'rb'; break; } $this->_FileHandler = fopen($pFilePath, $FileMode); } /** * Class destructor */ public function __destruct() { if($this->_FileHandler !== NULL) { $this->close(); } } /** * Close the current opened file * * @throws \Exception */ public function close() { if($this->_FileHandler === NULL) { throw new \Exception('This file is already closed.'); } fclose($this->_FileHandler); $this->_FileHandler = NULL; } /** * Delete a file or a symbolic link from the file system * * @param string $pFilePath Path od the file to delete * @return bool True on success, otherwise false */ public static function delete($pFilePath) { return unlink($pFilePath); } /** * Check if a file exists * * @param string $pFilePath Path of the file that we need to check the existence * @return bool True if the given file exists, otherwise false */ public static function exists($pFilePath) { return file_exists($pFilePath) && is_file($pFilePath); } /** * Read and returns all file content as a string * * @param string $pFilePath Path of the file to read * @return string File content */ public static function readAllText($pFilePath) { return file_get_contents($pFilePath); } /** * Read bytes from a file * * @param int $pCount Number of bytes to read * @return array Array of bytes. Its size can be lesser than $pCount if the end of file is reached * @throws \Exception */ public function readBytes($pCount) { if($this->_FileHandler === null) { // No file opened throw new \Exception('You must open a file before reading bytes.'); } // Reads bytes from file $Result = fread($this->_FileHandler, $pCount); // Converts the result to a byte array $ReturnValue = array_values(unpack('C*', $Result)); return $ReturnValue; } /** * Rename or moves a file * * @param string $pSourcePath Path of the file to rename or move * @param string $pDestPath Destination path */ public static function rename($pSourcePath, $pDestPath) { rename($pSourcePath, $pDestPath); } /** * Write a text content into a file * * @param string $pFilePath Path of the file to write into * @param string $pTextContent Text content to write */ public static function writeAllText($pFilePath, $pTextContent) { file_put_contents($pFilePath, $pTextContent); } /** * Write bytes to an opened file * * @param array $pData Array of bytes to write into the file * @return int Number of bytes that have been written * @throws \Exception */ public function writeBytes($pData) { if($this->_FileHandler === null) { // No file opened throw new \Exception('You must open a file before writing bytes.'); } // Writes bytes into the file $Data = ''; foreach($pData as $currentByte) { $Data .= pack('C*', $currentByte); } $ReturnValue = fwrite($this->_FileHandler, $Data); if($ReturnValue === false) { // Unable to write throw new \Exception('Unable to write bytes into this file.'); } return $ReturnValue; } }
TypeScript
UTF-8
743
2.90625
3
[ "MIT" ]
permissive
// @ts-nocheck import { DIError } from './error'; export function getParentClass(klass) { return Object.getPrototypeOf(klass); } /* eslint-disable */ const STRING_CAMELIZE_REGEXP_1 = /(\-|\_|\.|\s)+(.)?/g; const STRING_CAMELIZE_REGEXP_2 = /(^|\/)([A-Z])/g; // Transfrom string to camel case, from Ember String export function camelize(key) { return key .replace(STRING_CAMELIZE_REGEXP_1, (match, separator, chr) => chr ? chr.toUpperCase() : '', ) .replace(STRING_CAMELIZE_REGEXP_2, (match, separator, chr) => match.toLowerCase(), ); } /* eslint-enable */ export function assert(cond, msg, ...args) { if (!cond) { if (msg) throw DIError(msg, ...args); else throw DIError('Assertion Failed'); } }